<?php

namespace app\admin\controller\coupon;

use app\admin\service\sys_manage\CategoryService;
use app\controller\Curd;
use app\model\Card;
use app\model\CardIssue;
use app\model\CardMain;
use app\model\Goods;
use app\model\SysDept;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use support\Db;
use support\exception\BusinessException;
use support\Log;
use support\Model;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;

class CardMainController extends Curd
{
    public function __construct()
    {
        $this->model = new CardMain();
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $field ?? 'card_main_addtimes';

        if (!empty($where['card_main_name'])) {
            $where['card_main_name'] = ['like', $where['card_main_name']];
        }
        if (!empty($where['card_main_addtimes'])) {
            $where['card_main_addtimes'][0] = strtotime($where['card_main_addtimes'][0]);
            $where['card_main_addtimes'][1] = strtotime($where['card_main_addtimes'][1]);
        }

        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * 指定查询where条件,并没有真正的查询数据库操作
     * @param array $where
     * @param string|null $field
     * @param string $order
     * @return EloquentBuilder|QueryBuilder|Model
     */
    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with('category');
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        return $model;
    }

    /**
     * @Desc 查询后处理
     * @Author Gorden
     * @Date 2024/11/15 8:35
     *
     * @param $items
     * @return mixed
     */
    public function afterQuery($items)
    {
        foreach ($items as &$item) {
            if ($item['card_main_valid_mode'] == 'DAYS') {
                $item['valid_term'] = $item['card_main_valid_days'] ? $item['card_main_valid_days'] . '天' : 0;
            } elseif ($item['card_main_valid_mode'] == 'LONG') {
                $item['valid_term'] = '长期有效';
            } elseif ($item['card_main_valid_mode'] == 'DATE') {
                $item['valid_term'] = date('Y/m/d', strtotime($item['card_main_valid_begin'])) . '-' . date('Y/m/d', strtotime($item['card_main_valid_end']));
            }

            $item['total'] = Card::where('join_card_main_id', $item['card_main_id'])->count();
            $item['amount'] = sprintf('%.2f', $item['total'] * $item['card_main_amount']);
        }

        return $items;
    }

    /**
     * @Desc 卡的下拉搜索
     * @Author Gorden
     * @Date 2024/11/18 9:51
     *
     * @return Response
     */
    public function selectList()
    {
        $cardMain = CardMain::where('card_main_status', 'ACTIVED')
            ->orderBy('card_main_addtimes', 'DESC')
            ->select('card_main_id', 'card_main_name')
            ->get()
            ->toArray();

        return json_success('success', $cardMain);
    }

    /**
     * @Desc 储值卡详情
     * @Author Gorden
     * @Date 2024/11/15 11:33
     *
     * @param Request $request
     * @return Response
     */
    public function info(Request $request): Response
    {
        $cardMainId = $request->get('card_main_id');
        if (!$cardMainId) {
            return json_fail('参数异常');
        }
        $main = CardMain::with('category')->where('card_main_id', $cardMainId)->first();
        if ($main->card_main_valid_mode == 'DAYS') {
            $main->valid_term = $main->card_main_valid_days ? $main->card_main_valid_days . '天' : 0;
        } elseif ($main->card_main_valid_mode == 'LONG') {
            $main->valid_term = '长期有效';
        } elseif ($main->card_main_valid_mode == 'DATE') {
            $main->valid_term = date('Y/m/d', strtotime($main->card_main_valid_begin)) . '-' . date('Y/m/d', strtotime($main->card_main_valid_end));
        }
        // 发行记录
        $cardIssue = CardIssue::where('join_issue_card_main_id', $cardMainId)->orderBy('card_issue_addtimes', 'DESC')->get()->toArray();
        $cardMainJson = json_decode($main->card_main_json, true);
        // 适用门店
        $premises = [];
        if (!empty($cardMainJson['premises_ary'])){
            $premises = SysDept::whereIn('dept_id',$cardMainJson['premises_ary'])->pluck('dept_name');
        }
        $category = [];
        if (!empty($cardMainJson['goods_category_ary'])){
            $category = CategoryService::getCategoryAndSupper($cardMainJson['goods_category_ary']);
        }
        // 适用产品
        $goods = [];
        if (!empty($cardMainJson['goods_ary'])){
            $goods = Goods::whereIn('goods_id',$cardMainJson['goods_ary'])
                ->select('goods_id','goods_name','goods_cover','goods_sales_price','goods_addtimes')
                ->orderByDesc('goods_sort')->orderByDesc('goods_addtimes')->get()->toArray();
            foreach ($goods as &$goodsItem){
                $goodsItem['goods_cover'] = getenv("STORAGE_DOMAIN").$goodsItem['goods_cover'];
            }
        }

        // 发行统计
        $cardTotal = Card::where('join_card_main_id', $cardMainId)->count();
        $isIssueTotal = Card::where('join_card_main_id', $cardMainId)->where('is_issue', 'Y')->count();
        $cardInitTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'INIT')->count();
        $cardWaitingTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'WAITING')->count();
        $cardPendingTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'PENDING')->count();
        $cardUsedTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'USED')->count();
        $cardDoneTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'DONE')->count();
        $cardExpiredTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'EXPIRED')->count();
        $cardPausedTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'PAUSED')->count();
        $statistics = [
            [
                'total' => $cardTotal,
                'isIssueTotal' => $isIssueTotal,
                'initTotal' => $cardInitTotal,
                'waitingTotal' => $cardWaitingTotal,
                'pendingTotal' => $cardPendingTotal,
                'usedTotal' => $cardUsedTotal,
                'doneTotal' => $cardDoneTotal,
                'expiredTotal' => $cardExpiredTotal,
                'pausedTotal' => $cardPausedTotal
            ]
        ];

        $data = [
            'main' => $main,
            'issue' => $cardIssue,
            'premises'=>$premises,
            'category'=>$category,
            'goods'=>$goods,
            'statistics' => $statistics
        ];

        return json_success('', $data);
    }

    /**
     * @Desc 插入前置方法
     * @Author Gorden
     * @Date 2024/11/14 14:29
     *
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    public function insertInput(Request $request): array
    {
        $params = $request->post();

        $data = $this->inputFilter($request->post());

        if ($data['card_main_valid_mode'] == 'DATE') {
            $data['card_main_valid_begin'] = date('Y-m-d 00:00:00', strtotime($data['card_main_valid_begin']));
            $data['card_main_valid_end'] = date('Y-m-d 23:59:59', strtotime($data['card_main_valid_end']));
            $data['card_main_valid_days'] = 0;
        } elseif ($data['card_main_valid_mode'] == 'LONG' || $data['card_main_valid_mode'] == 'DAYS') {
            $data['card_main_valid_begin'] = '';
            $data['card_main_valid_end'] = '';
        }


        $cardMainJson = [
            'desc' => $params['card_main_desc'] ?? [],
            'is_recharge' => $params['is_recharge'] ?? 'N',
            'issue' => $params['issue'] ?? 'BATCH',
            'demand_config' => []
        ];
        if ($params['issue'] == 'DEMAND') {
            $cardMainJson['demand_config'] = [
                'length' => $params['card_length'],
                'begin' => $params['card_begin'],
                'end' => $params['card_end'],
                'prefix' => $params['card_prefix'],
                'suffix' => $params['card_suffix'],
                'rand' => $params['card_rand'],
                'rand_varchar' => is_numeric($params['card_rand']) ? 'NUMBER' : 'STRING',
            ];
        }
        // 关联产品
        $cardMainJson['goods_ary'] = $params['goods_id'] ?? [];
        // 关联产品分类
        $cardMainJson['goods_category_ary'] = $params['category_id'] ?? [];
        // 关联门店
        $cardMainJson['premises_ary'] = $params['premises'] ?? [];

        $data['card_main_json'] = json_encode($cardMainJson);

        return $data;
    }

    /**
     * 更新前置方法
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function updateInput(Request $request): array
    {
        $params = $request->post();

        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }

        if ($data['card_main_valid_mode'] == 'DATE') {
            $data['card_main_valid_begin'] = date('Y-m-d 00:00:00', strtotime($data['card_main_valid_begin']));
            $data['card_main_valid_end'] = date('Y-m-d 23:59:59', strtotime($data['card_main_valid_end']));
            $data['card_main_valid_days'] = 0;
        } elseif ($data['card_main_valid_mode'] == 'LONG' || $data['card_main_valid_mode'] == 'DAYS') {
            $data['card_main_valid_begin'] = '';
            $data['card_main_valid_end'] = '';
        }

        $cardMainJson = [];
        if (!empty($model->card_main_json)) {
            $cardMainJson = json_decode($model->card_main_json, true);
        }
        $cardMainJson['desc'] = $params['card_main_desc'] ?? [];
        if (!empty($params['is_recharge'])) {
            $cardMainJson['is_recharge'] = $params['is_recharge'];
        }
        if (!empty($params['issue'])) {
            $cardMainJson['issue'] = $params['issue'];
        }
        if ($cardMainJson['issue'] == 'BATCH') {
            $cardMainJson['demand_config'] = [];
        } elseif ($cardMainJson['issue'] == 'DEMAND') {
            $cardMainJson['demand_config'] = [
                'length' => $params['card_length'],
                'begin' => $params['card_begin'],
                'end' => $params['card_end'],
                'prefix' => $params['card_prefix'],
                'suffix' => $params['card_suffix'],
                'rand' => $params['card_rand'],
                'rand_varchar' => is_numeric($params['card_rand']) ? 'NUMBER' : 'STRING',
            ];
        }
        // 关联产品
        $cardMainJson['goods_ary'] = $params['goods_id'] ?? [];
        // 关联产品分类
        $cardMainJson['goods_category_ary'] = $params['category_id'] ?? [];
        // 关联门店
        $cardMainJson['premises_ary'] = $params['premises'] ?? [];

        $data['card_main_json'] = json_encode($cardMainJson);

        // 卡状态设置为禁用，则未绑定的卡冻结，恢复未发行状态
        if ($data['card_main_status'] == 'DISABLED' && $model->card_main_status != 'DISABLED') {
            Card::where('join_card_main_id', $id)->where('join_card_member_id', '')->update(['card_status' => 'PAUSED', 'is_issue' => 'N']);
            // 记录日志
            _syslog("储值卡", "禁用");
        } elseif ($data['card_main_status'] == 'ACTIVED' && $model->card_main_status == 'DISABLED') {
            Card::where('join_card_main_id', $id)->where('join_card_member_id', '')
                ->where('card_status', 'PAUSED')
                ->update(['card_status' => 'INIT']);
            // 记录日志
            _syslog("储值卡", "启用");
        }

        unset($data[$primary_key]);
        return [$id, $data];
    }

    /**
     * @Desc 删除储值卡
     * @Author Gorden
     * @Date 2024/11/18 16:33
     *
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function delete(Request $request): Response
    {
        $ids = $this->deleteInput($request);

        Db::beginTransaction();
        try {
            if (Card::whereIn('join_card_main_id', $ids)->where(function ($query) {
                $query->where('card_status', '<>', 'INIT')
                    ->orWhere('join_card_dept_id', '<>', '')
                    ->orWhere('join_card_member_id', '<>', '');
            })->exists()) {
                return json_fail("存在已发行、已分配的卡，无法删除!");
            }

            $this->doDelete($ids);
            // 同时删除批次记录
            CardIssue::whereIn('join_issue_card_main_id', $ids)->delete();
            // 同时删除卡记录
            Card::whereIn('join_card_main_id', $ids)->delete();

            Db::commit();
            _syslog("储值卡", '删除成功');
            return json_success('success');
        } catch (\Exception $e) {
            Db::rollBack();
            _syslog("储值次", '删除失败');
            Log::error("储值卡删除失败", ['msg' => $e->getMessage()]);

            return json_fail("删除失败");
        }

    }

    /**
     * @Desc 储值卡统计
     * @Author Gorden
     * @Date 2024/11/22 13:06
     *
     * @param Request $request
     * @return Response
     */
    public function statistics(Request $request)
    {
        $classify = $request->get('card_main_classify');
        $categoryId = $request->get('join_card_main_category_id');
        $name = $request->get('card_main_name');
        $addtimes = $request->get('card_main_addtimes');
        $amount = $request->get('card_main_amount');

        $cardMain = CardMain::when(!empty($classify), function ($query) use ($classify) {
            $query->where('card_main_classify', $classify);
        })->when(!empty($categoryId), function ($query) use ($categoryId) {
            $query->where('join_card_main_category_id', $categoryId);
        })->when(!empty($name), function ($query) use ($name) {
            $query->where('card_main_name', 'like', '%' . $name . '%');
        })->when(!empty($amount), function ($query) use ($amount) {
            $query->where('card_main_amount', $amount);
        })->when(!empty($addtimes), function ($query) use ($addtimes) {
            $addtimes[0] = strtotime($addtimes[0]);
            $addtimes[1] = strtotime($addtimes[1]);
            $query->whereBetween('card_main_addtimes', $addtimes);
        });
        $totalModel = clone $cardMain;
        $totalList = $totalModel->select('card_main_id', 'card_main_amount')->get()->toArray();
        $statistics = [
            'total' => ['total' => 0, 'amount' => 0],
            'is_issue' => ['total' => 0, 'amount' => 0],
            'init' => ['total' => 0, 'amount' => 0],
            'waiting' => ['total' => 0, 'amount' => 0],
            'pending' => ['total' => 0, 'amount' => 0],
            'used' => ['total' => 0, 'amount' => 0],
            'done' => ['total' => 0, 'amount' => 0],
            'expired' => ['total' => 0, 'amount' => 0],
            'paused' => ['total' => 0, 'amount' => 0]
        ];
        foreach ($totalList as $total) {
            // 发行统计
            $isIssueTotal = Card::where('is_issue', 'Y')->where('join_card_main_id', $total['card_main_id'])->count();
            $statistics['is_issue']['total'] += $isIssueTotal;
            $statistics['is_issue']['amount'] = sprintf('%.2f', $isIssueTotal * $total['card_main_amount'] + $statistics['is_issue']['amount']);
            // 待分配统计
            $initTotal = Card::where('card_status', 'INIT')->where('join_card_main_id', $total['card_main_id'])->count();
            $statistics['init']['total'] += $initTotal;
            $statistics['init']['amount'] = sprintf('%.2f', $initTotal * $total['card_main_amount'] + $statistics['init']['amount']);
            // 已分配，待售统计
            $waitingTotal = Card::where('card_status', 'WAITING')->where('join_card_main_id', $total['card_main_id'])->count();
            $statistics['waiting']['total'] += $waitingTotal;
            $statistics['waiting']['amount'] = sprintf('%.2f', $waitingTotal * $total['card_main_amount'] + $statistics['waiting']['amount']);
            // 已售，待激活统计
            $pendingTotal = Card::where('card_status', 'PENDING')->where('join_card_main_id', $total['card_main_id'])->count();
            $statistics['pending']['total'] += $pendingTotal;
            $statistics['pending']['amount'] = sprintf('%.2f', $pendingTotal * $total['card_main_amount'] + $statistics['pending']['amount']);
            // 已激活统计
            $usedTotal = Card::where('card_status', 'USED')->where('join_card_main_id', $total['card_main_id'])->count();
            $statistics['used']['total'] += $usedTotal;
            $statistics['used']['amount'] = sprintf('%.2f', $usedTotal * $total['card_main_amount'] + $statistics['used']['amount']);
            // 使用完成统计
            $doneTotal = Card::where('card_status', 'DONE')->where('join_card_main_id', $total['card_main_id'])->count();
            $statistics['done']['total'] += $doneTotal;
            $statistics['done']['amount'] = sprintf('%.2f', $doneTotal * $total['card_main_amount'] + $statistics['done']['amount']);
            // 过期统计
            $doneTotal = Card::where('card_status', 'EXPIRED')->where('join_card_main_id', $total['card_main_id'])->count();
            $statistics['expired']['total'] += $doneTotal;
            $statistics['expired']['amount'] = sprintf('%.2f', $doneTotal * $total['card_main_amount'] + $statistics['expired']['amount']);
            // 冻结统计
            $pausedTotal = Card::where('card_status', 'PAUSED')->where('join_card_main_id', $total['card_main_id'])->count();
            $statistics['paused']['total'] += $pausedTotal;
            $statistics['paused']['amount'] = sprintf('%.2f', $pausedTotal * $total['card_main_amount'] + $statistics['paused']['total']);
        }
        $statistics['total']['total'] = $statistics['init']['total'] + $statistics['waiting']['total']
            + $statistics['pending']['total'] + $statistics['used']['total'] + $statistics['done']['total']
            + $statistics['expired']['total'] + $statistics['paused']['total'];
        $statistics['total']['amount'] = sprintf('%.2f', $statistics['init']['amount']
            + $statistics['waiting']['amount'] + $statistics['pending']['amount'] + $statistics['used']['amount']
            + $statistics['expired']['amount'] + $statistics['done']['amount'] + $statistics['paused']['amount']);

        return json_success('success', $statistics);
    }
}