<?php

namespace app\admin\controller\coupon;

use app\admin\service\coupon\CardService;
use app\controller\Curd;
use app\model\Card;
use app\model\CardIssue;
use app\model\CardMain;
use app\model\SysCategory;
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 CardIssueController extends Curd
{
    public function __construct()
    {
        $this->model = new CardIssue();
    }


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

        if (!empty($where['card_issue_name'])) {
            $where['card_issue_name'] = ['like', $where['card_issue_name']];
        }
        if (!empty($where['card_issue_addtimes'])) {
            $where['card_issue_addtimes'][0] = strtotime($where['card_issue_addtimes'][0]);
            $where['card_issue_addtimes'][1] = strtotime($where['card_issue_addtimes'][1]);
        }
        if (!empty($cardMainName)) {
            $cardMainIds = CardMain::where('card_main_name', 'like', '%' . $cardMainName . '%')->pluck('card_main_id')->toArray();
            $where['join_issue_card_main_id'] = ['in', $cardMainIds];
        }

        $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([
            'main',
            'user'
        ]);
        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') {
                    $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 (!empty($item['main']['join_card_main_category_id'])) {
                $item['main']['category_name'] = SysCategory::where('category_id', $item['main']['join_card_main_category_id'])->value('category_name');
            }
            if (!empty($item['main']['card_main_valid_mode']) && $item['main']['card_main_valid_mode'] == 'DAYS') {
                $item['main']['valid_term'] = $item['main']['card_main_valid_days'] ? $item['main']['card_main_valid_days'] . '天' : 0;
            } elseif (!empty($item['main']['card_main_valid_mode']) && $item['main']['card_main_valid_mode'] == 'LONG') {
                $item['main']['valid_term'] = '长期有效';
            } elseif (!empty($item['main']['card_main_valid_mode']) && $item['main']['card_main_valid_mode'] == 'DATE') {
                $item['main']['valid_term'] = date('Y/m/d H:i:s', strtotime($item['main']['card_main_valid_begin'])) . '-' . date('Y/m/d H:i:s', strtotime($item['main']['card_main_valid_end']));
            }

            if (empty($item['main'])) {
                continue;
            }

//            $item['main']['cardMainJson'] = json_decode($item['main']['card_main_json'], true);

            // 总发行金额
            $item['issue_total_amount'] = sprintf('%.2f', $item['card_issue_num'] * $item['main']['card_main_amount']);

            $cardModel = Card::where('join_card_issue_id', $item['card_issue_id']);
            // 未激活
            $inactiveTotalModel = clone $cardModel;
            $item['inactive_total'] = $inactiveTotalModel->whereIn('card_status', ['INIT', 'WAITING', 'PENDING'])->count();
            $item['inactive_amount'] = sprintf('%.2f', $item['inactive_total'] * $item['main']['card_main_amount']);
            // 已激活
            $activeTotalModel = clone $cardModel;
            $item['active_total'] = $activeTotalModel->whereIn('card_status', ['USED', 'DONE'])->count();
            $item['active_amount'] = sprintf('%.2f', $item['active_total'] * $item['main']['card_main_amount']);
            // 无效
            $invalidTotalModel = clone $cardModel;
            $item['invalid_total'] = $invalidTotalModel->whereIn('card_status', ['EXPIRED', 'PAUSED', 'DISABLED'])->count();
            $item['invalid_amount'] = sprintf('%.2f', $item['invalid_total'] * $item['main']['card_main_amount']);
        }

        return $items;
    }

    /**
     * @Desc 创建发行
     * @Author Gorden
     * @Date 2024/11/18 10:09
     *
     * @param Request $request
     * @return Response
     */
    public function insert(Request $request): Response
    {
        $params = $request->post();
        Db::beginTransaction();
        try {
            if (empty($params['card_issue_serial_fill'])) {
                $params['card_issue_serial_fill'] = '0';
            }
            // 验证是否有相同的前缀，长度相同，且开始结束数字有交叉的
            $cardIssueExists = CardIssue::where('card_issue_serial_length', $params['card_issue_serial_length'])
                ->where('card_issue_serial_prefix', $params['card_issue_serial_prefix'])
                ->where(function ($query) use ($params) {
                    $query->whereBetween('card_issue_serial_begin', [$params['card_issue_serial_begin'], $params['card_issue_serial_end']])
                        ->orWhereBetween('card_issue_serial_end', [$params['card_issue_serial_begin'], $params['card_issue_serial_end']]);
                })->exists();
            if ($cardIssueExists) {
                throw new BusinessException("当前设置的发行规则在前缀、长度、开始数字、结束数字与已存在的规则存在冲突，请重新设置");
            }

            $cardIds = [];
            $i = 0;
            // 创建卡号
            while (count($cardIds) < intval($params['card_issue_num'])) {
                // 防死循环
                if ($i > 20000) {
                    throw new BusinessException("生成规则异常");
                }

                $cardId = CardService::generateCardId($params, $i);
                if ($cardId !== false) {
                    $cardIds[] = $cardId;
                }
                $i++;
            }

            // 写入发行表
            $issueId = CardIssue::insertGetId([
                'join_issue_card_main_id' => $params['join_issue_card_main_id'],
                'card_issue_name' => $params['card_issue_name'],
                'card_issue_num' => $params['card_issue_num'],
                'card_issue_datetime' => date('Y-m-d H:i:s'),
                'card_issue_serial_length' => $params['card_issue_serial_length'],
                'card_issue_serial_prefix' => $params['card_issue_serial_prefix'],
                'card_issue_serial_suffix' => $params['card_issue_serial_suffix'],
                'card_issue_serial_begin' => $params['card_issue_serial_begin'],
                'card_issue_serial_end' => $params['card_issue_serial_begin'] + $i - 1,
                'card_issue_serial_fill' => $params['card_issue_serial_fill'],
                'card_issue_begin_nbr' => $cardIds[0],
                'card_issue_end_nbr' => $cardIds[count($cardIds) - 1],
                'card_issue_creator_user_id' => JwtToken::getCurrentId(),
                'card_issue_addtimes' => time()
            ]);
            // 分批入库
            $cardsCollect = collect($cardIds);
            $chunks = $cardsCollect->chunk(200);
            foreach ($chunks as $chunk) {
                $insertData = [];
                foreach ($chunk as $key => $item) {
                    $insertData[$key] = [
                        'card_id' => $item,
                        'join_card_main_id' => $params['join_issue_card_main_id'],
                        'join_card_issue_id' => $issueId,
                        'card_status' => 'INIT',
                        'card_cdkey' => random_string(8, 'number'),
                        'card_addtimes' => time()
                    ];
                }

                Card::insert($insertData);
            }

            Db::commit();
            _syslog("储值卡批次", '创建成功', false, $request->all());
            return json_success('success');
        } catch (BusinessException $e) {
            Db::rollBack();
            _syslog("储值卡批次", '创建失败', false, $request->all());
            Log::error("储值卡批次创建失败", ['msg' => $e->getMessage()]);

            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            Db::rollBack();
            _syslog("储值卡批次", '创建失败', false, $request->all());
            Log::error("储值卡发行失败", ['msg' => $e->getMessage()]);

            return json_fail("储值卡批次创建失败");
        }
    }

    /**
     * @Desc 删除批次
     * @Author Gorden
     * @Date 2024/11/18 11:05
     *
     * @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_issue_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);
            // 同时删除卡记录
            Card::whereIn('join_card_issue_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/18 14:44
     *
     * @param Request $request
     * @return Response
     */
    public function getIssueList(Request $request)
    {
        $cardMainId = $request->get('card_main_id');
        if (!$cardMainId) {
            return json_fail('参数异常');
        }
        $isIssue = $request->get('is_issue');
        $allocation = $request->get('allocation');

        $cardIssues = CardIssue::where('join_issue_card_main_id', $cardMainId)
            ->select('card_issue_id', 'card_issue_name')
            ->get()
            ->toArray();
        if (empty($isIssue) && empty($allocation)) {
            return json_success('success', $cardIssues);
        }
        $cardIssueIds = array_column($cardIssues, 'card_issue_id');
        $inCardsIssueIds = Card::whereIn('join_card_issue_id', $cardIssueIds)
            ->when(!empty($isIssue), function ($query) use ($isIssue) {
                $query->where('is_issue', $isIssue);
            })->when(!empty($allocation), function ($query) use ($allocation) {
                if ($allocation == 'N') {
                    $query->where('join_card_dept_id', '');
                } elseif ($allocation == 'Y') {
                    $query->where('join_card_dept_id', '<>', '');
                }
            })
            ->groupBy('join_card_issue_id')
            ->pluck('join_card_issue_id')
            ->toArray();
        $data = [];
        foreach ($cardIssues as $cardIssue) {
            foreach ($inCardsIssueIds as $issueId) {
                if ($cardIssue['card_issue_id'] == $issueId) {
                    $data[] = [
                        'card_issue_id' => $cardIssue['card_issue_id'],
                        'card_issue_name' => $cardIssue['card_issue_name']
                    ];
                }
            }
        }

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