<?php

namespace app\admin\controller\coupon;

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


    /**
     * 查询
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function select(Request $request): Response
    {
        $cardMainName = $request->get('card_main_name');
        $cardMainAmount = $request->get('card_main_amount');
        $cardIssueName = $request->get('card_issue_name');
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $field ?? 'card_addtimes';

        if (!empty($where['card_addtimes'])) {
            $where['card_addtimes'][0] = strtotime($where['card_addtimes'][0]);
            $where['card_addtimes'][1] = strtotime($where['card_addtimes'][1]);
        }
        $cardMainIds = [];
        if (!empty($cardMainName)) {
            $cardMainIds = CardMain::where('card_main_name', 'like', '%' . $cardMainName . '%')->pluck('card_main_id')->toArray();
        }
        if (!empty($cardMainAmount) && !empty($cardMainName)) {
            $mainIds = CardMain::where('card_main_amount', $cardMainAmount)->pluck('card_main_id')->toArray();
            $cardMainIds = array_intersect($cardMainIds, $mainIds);
        } else if (!empty($cardMainAmount)) {
            $cardMainIds = CardMain::where('card_main_amount', $cardMainAmount)->pluck('card_main_id')->toArray();
        }
        if (!empty($cardMainName) || !empty($cardMainAmount)) {
            $where['join_card_main_id'] = ['in', $cardMainIds];
        }
        if (!empty($cardIssueName)) {
            $cardIssueIds = CardIssue::where('card_issue_name', 'like', '%' . $cardIssueName . '%')->pluck('card_issue_id')->toArray();
            $where['join_card_issue_id'] = ['in', $cardIssueIds];
        }
        if (!empty($where['card_id'])) {
            $where['card_id'] = ['like', $where['card_id']];
        }

        $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([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'cert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            },
            'dept',
            'user',
            'main' => function ($query) {
                $query->select('card_main_id', 'card_main_name', 'card_main_amount', 'card_main_valid_mode');
            },
            'issue' => function ($query) {
                $query->select('card_issue_id', 'card_issue_name');
            }
        ]);
        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)->orderByDesc('card_id');
        }
        return $model;
    }

    public function afterQuery($items)
    {
        foreach ($items as &$item) {
            $mobile = $item['member']['member_mobile'] ?? '';
            $certName = $item['cert']['member_cert_name'] ?? '';
            $item['member_name'] = MemberService::getMemberCertName($mobile, $certName, '');
            if (!empty($item['main']['card_main_valid_mode'])) {
                if ($item['main']['card_main_valid_mode'] == 'LONG') {
                    $item['valid_datetime'] = '长期有效';
                } else if (!empty($item['card_deadline_datetime'])) {
                    $item['valid_datetime'] = date('Y/m/d', strtotime($item['card_assign_datetime'])) . '-' . date('Y/m/d', strtotime($item['card_deadline_datetime']));
                }
            }
            $cardExtendJson = [];
            if (!empty($item['card_extend_json'])) {
                $cardExtendJson = json_decode($item['card_extend_json'], true);
            }
            if (!empty($cardExtendJson['issue_datetime'])) {
                $item['issue_datetime'] = $cardExtendJson['issue_datetime'];
            }
        }

        return $items;
    }

    /**
     * @Desc 储值卡统计
     * @Author Gorden
     * @Date 2024/11/22 13:06
     *
     * @param Request $request
     * @return Response
     */
    public function statistics(Request $request)
    {
        $cardStatus = $request->get('card_status');
        $isIssue = $request->get('is_issue');
        $issueName = $request->get('card_issue_name');
        $mainName = $request->get('card_main_name');
        $addtimes = $request->get('card_addtimes');
        $amount = $request->get('card_main_amount');
        $deptId = $request->get('join_card_dept_id');
        $cardId = $request->get('card_id');
        $memberId = $request->get('join_card_member_id');

        $cardMainIds = [];
        if (!empty($mainName)) {
            $cardMainIds = CardMain::where('card_main_name', 'like', '%' . $mainName . '%')->pluck('card_main_id')->toArray();
        }
        if (!empty($amount)) {
            $mainIds = CardMain::where('card_main_amount', $amount)->pluck('card_main_id')->toArray();
            $cardMainIds = array_intersect($cardMainIds, $mainIds);
        }
        $cardIssueIds = [];
        if (!empty($issueName)) {
            $cardIssueIds = CardIssue::where('card_issue_name', 'like', '%' . $issueName . '%')->pluck('card_issue_id')->toArray();
        }

        $cardModel = Card::with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'cert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            },
            'dept',
            'user',
            'main' => function ($query) {
                $query->select('card_main_id', 'card_main_name', 'card_main_amount', 'card_main_valid_mode');
            },
            'issue' => function ($query) {
                $query->select('card_issue_id', 'card_issue_name');
            }
        ])->when(!empty($cardId), function ($query) use ($cardId) {
            $query->where('card_id', 'like', '%' . $cardId . '%');
        })->when(!empty($deptId), function ($query) use ($deptId) {
            $query->where('join_card_dept_id', $deptId);
        })->when(!empty($memberId), function ($query) use ($memberId) {
            $query->where('join_card_member_id', $memberId);
        })->when(!empty($isIssue), function ($query) use ($isIssue) {
            $query->where('is_issue', $isIssue);
        })->when(!empty($cardStatus), function ($query) use ($cardStatus) {
            $query->where('card_status', $cardStatus);
        })->when(!empty($addtimes), function ($query) use ($addtimes) {
            $addtimes[0] = strtotime($addtimes[0]);
            $addtimes[1] = strtotime($addtimes[1]);
            $query->whereBetween('card_addtimes', $addtimes);
        })->when(!empty($mainName) && !empty($amount), function ($query) use ($cardMainIds) {
            $query->whereIn('join_card_main_id', $cardMainIds);
        })->when(!empty($issueName), function ($query) use ($cardIssueIds) {
            $query->whereIn('join_card_issue_id', $cardIssueIds);
        });


        $totalList = CardMain::when(!empty($mainName), function ($query) use ($mainName) {
            $query->where('card_main_name', 'like', '%' . $mainName . '%');
        })->when(!empty($amount), function ($query) use ($amount) {
            $query->where('card_main_amount', $amount);
        })->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) {
            // 发行统计
            $issueModel = clone $cardModel;
            $isIssueTotal = $issueModel->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']);
            // 待分配统计
            $initModel = clone $cardModel;
            $initTotal = $initModel->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']);
            // 已分配，待售统计
            $waitingModel = clone $cardModel;
            $waitingTotal = $waitingModel->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']);
            // 已售，待激活统计
            $pendingModel = clone $cardModel;
            $pendingTotal = $pendingModel->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']);
            // 已激活统计
            $usedModel = clone $cardModel;
            $usedTotal = $usedModel->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']);
            // 使用完成统计
            $doneModel = clone $cardModel;
            $doneTotal = $doneModel->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']);
            // 过期统计
            $expiredModel = clone $cardModel;
            $doneTotal = $expiredModel->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']);
            // 冻结统计
            $pausedModel = clone $cardModel;
            $pausedTotal = $pausedModel->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);
    }

    public function info(Request $request): Response
    {
        $cardId = $request->get('card_id');
        if (!$cardId) {
            return json_fail("参数异常");
        }

        $info = Card::with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile', 'join_member_role_id', 'member_is_owner', 'member_is_vip', 'member_is_partner', 'member_is_referrer', 'member_is_franchisee');
            },
            'cert',
            'info',
            'dept',
            'user',
            'main',
            'issue'
        ])->where('card_id', $cardId)
            ->first();
        $info = $info ? $info->toArray() : [];
        if (!empty($info['member']) && !empty($info['member']['join_member_role_id'])) {
            $info['role_name'] = MemberRole::where('member_role_id', $info['member']['join_member_role_id'])->value('member_role_name');
        }
        // 头像
        $memberAvatar = !empty($info['info']) && !empty($info['info']['member_info_headimg']) ? $info['info']['member_info_headimg'] : '';
        $info['info']['member_info_headimg'] = MemberService::getAvatarUrl($memberAvatar);
        // 昵称
        $memberNickname = !empty($info['info']) && !empty($info['info']['member_info_nickname']) ? $info['info']['member_info_nickname'] : '';
        $memberMobile = !empty($info['member']) && !empty($info['member']['member_mobile']) ? $info['member']['member_mobile'] : '';
        $info['info']['member_info_nickname'] = MemberService::getNickname($memberNickname, $memberMobile);

        if (!empty($info['main'])) {
            if (!empty($info['main']['join_card_main_category_id'])) {
                $info['main_category_name'] = SysCategory::where('category_id', $info['main']['join_card_main_category_id'])->value('category_name');
            }
            if (!empty($info['main']['card_main_valid_mode']) && $info['main']['card_main_valid_mode'] == 'LONG') {
                $info['valid_term'] = '长期有效';
            } elseif (!empty($info['main']['card_main_valid_mode']) && $info['main']['card_main_valid_mode'] == 'DAYS') {
                $info['valid_term'] = $info['main']['card_main_valid_days'] . '天';
            } elseif (!empty($info['main']['card_main_valid_mode']) && $info['main']['card_main_valid_mode'] == 'DATE') {
                $info['valid_term'] = date('Y/m/d', strtotime($info['main']['card_main_valid_begin'])) . '-' . date('Y/m/d', strtotime($info['main']['card_main_valid_end']));
            }
            if (!empty($info['main']['card_main_json'])) {
                $cardMainJson = json_decode($info['main']['card_main_json'], true);
                $info['is_recharge'] = $cardMainJson['is_recharge'];
                $info['issue_mode'] = $cardMainJson['issue'];
            }
            if (!empty($info['main']['card_main_valid_mode'])) {
                if ($info['main']['card_main_valid_mode'] == 'LONG') {
                    $info['valid_datetime'] = '长期有效';
                } else if (!empty($info['card_deadline_datetime'])) {
                    $info['valid_datetime'] = date('Y/m/d', strtotime($info['card_assign_datetime'])) . '-' . date('Y/m/d', strtotime($info['card_deadline_datetime']));
                }
            }
        }
        if (!empty($info['issue']) && !empty($info['issue']['card_issue_creator_user_id'])) {
            $info['issue_username'] = SysUser::where('user_id', $info['issue']['card_issue_creator_user_id'])->value('user_name');
        }
        if (!empty($info['card_extend_json'])) {
            $cardExtendJson = json_decode($info['card_extend_json'], true);
            if (!empty($info['card_assign_datetime'])) {
                $info['info_assign']['datetime'] = $info['card_assign_datetime'];
                if (!empty($cardExtendJson['assign_user_id'])) {
                    $info['info_assign']['username'] = SysUser::where('user_id', $cardExtendJson['assign_user_id'])->value('user_name');
                }
            }
            if (!empty($cardExtendJson['buy_datetime'])) {
                $info['info_buy']['datetime'] = $cardExtendJson['buy_datetime'];
                if (!empty($cardExtendJson['buy_user_id'])) {
                    $info['info_buy']['username'] = SysUser::where('user_id', $cardExtendJson['buy_user_id'])->value('user_name');
                }
                if (!empty($cardExtendJson['buy_member'])) {
                    $member = Member::with([
                        'cert' => function ($query) {
                            $query->select('join_cert_member_id', 'member_cert_name');
                        }
                    ])->where('member_id', $cardExtendJson['buy_member'])
                        ->first();
                    $mobile = $member->member_mobile ?? '';
                    $certName = !empty($member->cert) ? $member->cert->member_cert_name : '';
                    $info['info_buy']['member_name'] = MemberService::getMemberCertName($mobile, $certName, '');
                }
                if (!empty($cardExtendJson['buy_order_id'])) {
                    $info['info_buy']['order_id'] = $cardExtendJson['buy_order_id'];
                }
            }
            if (!empty($cardExtendJson['used_datetime'])) {
                $info['info_used']['datetime'] = $cardExtendJson['used_datetime'];
                $info['info_used']['username'] = '会员';
                if (!empty($cardExtendJson['used_user_id'])) {
                    $info['info_used']['username'] = SysUser::where('user_id', $cardExtendJson['used_user_id'])->value('user_name');
                }
            }
            if (!empty($cardExtendJson['done_time'])) {
                $info['info_done']['datetime'] = $cardExtendJson['done_time'];
                if (!empty($cardExtendJson['done_user_id'])) {
                    $info['info_done']['username'] = SysUser::where('user_id', $cardExtendJson['done_user_id'])->value('user_name');
                }
            }
            if (!empty($cardExtendJson['expired_datetime'])) {
                $info['info_expired']['datetime'] = $cardExtendJson['expired_datetime'];
            }
            if (!empty($cardExtendJson['paused_datetime'])) {
                $info['info_paused']['datetime'] = $cardExtendJson['paused_datetime'];
                if (!empty($cardExtendJson['paused_user_id'])) {
                    $info['info_paused']['username'] = SysUser::where('user_id', $cardExtendJson['paused_user_id'])->value('user_name');
                }
            }
            if (!empty($cardExtendJson['issue_datetime'])) {
                $info['info_issue']['datetime'] = $cardExtendJson['issue_datetime'];
                if (!empty($cardExtendJson['issue_user_id'])) {
                    $info['info_issue']['username'] = SysUser::where('user_id', $cardExtendJson['issue_user_id'])->value('user_name');
                }
            }
        }

        return json_success('', $info);
    }


    /**
     * 更新前置方法
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function updateInput(Request $request): array
    {
        $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);
        }
        $cardExtendJson = [];
        if (!empty($model->card_extend_json)) {
            $cardExtendJson = json_decode($model->card_extend_json, true);
        }
        if ($data['is_issue'] == 'N') {
            unset($cardExtendJson['issue_datetime']);
        } elseif ($data['is_issue'] == 'Y') {
            $cardExtendJson['issue_datetime'] = date('Y-m-d H:i:s');
        }
        $data['card_extend_json'] = json_encode($cardExtendJson);

        if ($model->join_card_dept_id != $data['join_card_dept_id'] && empty($model->join_card_member_id)) {
            $data['card_assign_datetime'] = date('Y-m-d H:i:s');
        }
        if (!empty($data['join_card_dept_id']) && $model->card_status == 'INIT') {
            $data['card_status'] = 'WAITING';
        }

        _syslog('储值卡', '编辑', $data, $request->all());

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

    /**
     * @Desc 获取指定状态的 card_id
     * @Author Gorden
     * @Date 2024/11/15 17:21
     *
     * @param Request $request
     * @return Response
     */
    public function getCardIdsByMainId(Request $request)
    {
        $mainId = $request->get('main_id');
        if (!$mainId) {
            return json_fail('参数异常');
        }
        $status = $request->get('status');
        $isIssue = $request->get('is_issue');
        $allocation = $request->get('allocation');

        $cardIds = Card::where('join_card_main_id', $mainId)
            ->when(!empty($status), function ($query) use ($status) {
                $query->where('card_status', $status);
            })->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', '<>', '');
                }
            })->pluck('card_id')
            ->toArray();

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

    /**
     * @Desc 储值卡发行
     * @Author Gorden
     * @Date 2024/11/18 15:13
     *
     * @param Request $request
     * @return Response
     */
    public function issue(Request $request)
    {
        $params = $request->post();

        Db::beginTransaction();
        try {
            $issueMode = $params['issue'];
            // 1.按卡号
            if ($issueMode == 'CARDID' && !empty($params['card_id'])) {
                foreach ($params['card_id'] as $card_id) {
                    $card = Card::where('card_id', $card_id)->select('card_id', 'is_issue', 'card_extend_json')->first();
                    if (!empty($card)) {
                        $cardExtendJson = json_decode($card->card_extend_json, true);
                        $cardExtendJson['issue_datetime'] = date('Y-m-d H:i:s');
                        $cardExtendJson['issue_user_id'] = JwtToken::getCurrentId();
                        $card->card_extend_json = json_encode($cardExtendJson);
                        $card->is_issue = 'Y';
                        $card->save();
                    } else {
                        throw new BusinessException($card_id . "不存在");
                    }
                }
            } elseif ($issueMode == 'ISSUE' && !empty($params['card_issue_id'])) {
                // 2.按批次
                $cards = Card::where('join_card_issue_id', $params['card_issue_id'])
                    ->where('is_issue', 'N')
                    ->select('card_id', 'card_extend_json')
                    ->get()
                    ->toArray();
                if (!empty($cards)) {
                    foreach ($cards as $cardItem) {
                        $cardExtendJson = json_decode($cardItem['card_extend_json'], true);
                        $cardExtendJson['issue_datetime'] = date('Y-m-d H:i:s');
                        $cardExtendJson['issue_user_id'] = JwtToken::getCurrentId();
                        Card::where('card_id', $cardItem['card_id'])->update([
                            'is_issue' => 'Y',
                            'card_extend_json' => json_encode($cardExtendJson)
                        ]);
                    }
                } else {
                    throw new BusinessException("批次不存在");
                }
            }

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

    /**
     * @Desc 储值卡分配
     * @Author Gorden
     * @Date 2024/11/18 16:02
     *
     * @param Request $request
     * @return Response
     */
    public function allocation(Request $request)
    {
        $params = $request->post();

        try {
            $allocation = $params['allocation'];
            // 1.按卡号分配
            if ($allocation == 'CARDID' && !empty($params['card_id'])) {
                foreach ($params['card_id'] as $card_id) {
                    $card = Card::where('card_id', $card_id)->select('card_id', 'card_extend_json')->first();
                    if (!empty($card)) {
                        $cardExtendJson = json_decode($card->card_extend_json, true);
                        $cardExtendJson['assign_user_id'] = JwtToken::getCurrentId();
                        $card->card_status = 'WAITING';
                        $card->card_assign_datetime = date('Y-m-d H:i:s');
                        $card->join_card_dept_id = $params['join_card_dept_id'];
                        $card->card_extend_json = json_encode($cardExtendJson);
                        $card->save();
                    } else {
                        throw new BusinessException($card_id . "不存在");
                    }
                }

//                Card::whereIn('card_id', $params['card_id'])->where('join_card_dept_id', 0)->update([
//                    'join_card_dept_id' => $params['join_card_dept_id'],
//                    'card_status' => 'WAITING',
//                    'card_assign_datetime' => date('Y-m-d H:i:s')
//                ]);
            } elseif ($allocation == 'ISSUE' && !empty($params['card_issue_id'])) {
                $cards = Card::where('join_card_issue_id', $params['card_issue_id'])
                    ->where('card_status', 'INIT')
                    ->select('card_id', 'card_extend_json')
                    ->get()
                    ->toArray();
                if (!empty($cards)) {
                    foreach ($cards as $cardItem) {
                        $cardExtendJson = json_decode($cardItem['card_extend_json'], true);
                        $cardExtendJson['assign_user_id'] = JwtToken::getCurrentId();

                        Card::where('card_id', $cardItem['card_id'])->update([
                            'card_status' => 'WAITING',
                            'card_assign_datetime' => date('Y-m-d H:i:s'),
                            'join_card_dept_id' => $params['join_card_dept_id'],
                            'card_extend_json' => json_encode($cardExtendJson)
                        ]);
                    }
                } else {
                    throw new BusinessException("批次不存在");
                }

//                Card::where('join_card_issue_id', $params['card_issue_id'])->where('join_card_dept_id', 0)->update([
//                    'join_card_dept_id' => $params['join_card_dept_id'],
//                    'card_status' => 'WAITING',
//                    'card_assign_datetime' => date('Y-m-d H:i:s')
//                ]);
            }

            _syslog("储值卡", '分配成功');
            return json_success('success');
        } catch (\Exception $e) {
            _syslog("储值卡", '分配失败');
            Log::error('储值卡分配失败', ['msg' => $e->getMessage()]);
            return json_fail('分配失败');
        }
    }

    /**
     * @Desc 导出储值卡
     * @Author Gorden
     * @Date 2024/11/21 13:03
     *
     * @param Request $request
     * @return Response
     */
    public function exportCard(Request $request)
    {
        $cardStatus = $request->get('card_status');
        $isIssue = $request->get('is_issue');
        $cardMainName = $request->get('card_main_name');
        $cardIssueName = $request->get('card_issue_name');
        $deptId = $request->get('join_card_dept_id');
        $cardAddtimes = $request->get('card_addtimes');
        $cardIds = $request->get('card_ids');

        $cards = Card::with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'cert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            },
            'dept',
            'user',
            'main' => function ($query) {
                $query->select('card_main_id', 'card_main_name', 'card_main_amount', 'card_main_valid_mode');
            },
            'issue' => function ($query) {
                $query->select('card_issue_id', 'card_issue_name');
            }
        ])->when(!empty($cardStatus), function ($query) use ($cardStatus) {
            $query->where('card_status', $cardStatus);
        })->when(!empty($isIssue), function ($query) use ($isIssue) {
            $query->where('is_issue', $isIssue);
        })->when(!empty($deptId), function ($query) use ($deptId) {
            $query->where('join_card_dept_id', $deptId);
        })->when(!empty($cardAddtimes), function ($query) use ($cardAddtimes) {
            $cardAddtimes[0] = strtotime($cardAddtimes[0]);
            $cardAddtimes[1] = strtotime($cardAddtimes[1]);
            $query->whereBetween('card_addtimes', $cardAddtimes);
        })->when(!empty($cardIds), function ($query) use ($cardIds) {
            $query->whereIn('card_id', $cardIds);
        })->when(!empty($cardMainName), function ($query) use ($cardMainName) {
            $cardMainIds = CardMain::where('card_main_name', 'like', '%' . $cardMainName . '%')->pluck('card_main_id')->toArray();
            $query->whereIn('join_card_main_id', $cardMainIds);
        })->when(!empty($cardIssueName), function ($query) use ($cardIssueName) {
            $cardIssueIds = CardIssue::where('card_issue_name', 'like', '%' . $cardIssueName . '%')->pluck('card_issue_id')->toArray();
            $query->whereIn('join_card_issue_id', $cardIssueIds);
        })->orderByDesc('card_addtimes')
            ->get()
            ->toArray();
        $data = [];
        foreach ($cards as $item) {
            $mobile = $item['member']['member_mobile'] ?? '';
            $certName = $item['cert']['member_cert_name'] ?? '';
            $item['member_name'] = MemberService::getMemberCertName($mobile, $certName, '');
            if (!empty($item['main']['card_main_valid_mode'])) {
                if ($item['main']['card_main_valid_mode'] == 'LONG') {
                    $item['valid_datetime'] = '长期有效';
                } else if (!empty($item['card_deadline_datetime'])) {
                    $item['valid_datetime'] = date('Y/m/d H:i:s', strtotime($item['card_assign_datetime'])) . '-' . date('Y/m/d H:i:s', strtotime($item['card_deadline_datetime']));
                }
            }
            $cardExtendJson = [];
            if (!empty($item['card_extend_json'])) {
                $cardExtendJson = json_decode($item['card_extend_json'], true);
            }
            if (!empty($cardExtendJson['issue_datetime'])) {
                $item['issue_datetime'] = $cardExtendJson['issue_datetime'];
            }

            $data[] = [
                'card_id' => $item['card_id'],
                'main_name' => !empty($item['main']['card_main_name']) ? $item['main']['card_main_name'] : '--',
                'issue_name' => !empty($item['issue']['card_issue_name']) ? $item['issue']['card_issue_name'] : '--',
                'main_amount' => !empty($item['main']['card_main_amount']) ? $item['main']['card_main_amount'] : '--',
                'dept_name' => !empty($item['dept']['dept_name']) ? $item['dept']['dept_name'] : '--',
                'member_name' => $item['member_name'] ?? '--',
                'valid_datetime' => $item['valid_datetime'] ?? '--',
                'status' => CardService::$status[$item['card_status']],
                'is_issue' => $item['is_issue'] == 'Y' ? '已发行' : '未发行',
                'issue_datetime' => $item['issue_datetime'] ?? '--',
                'card_addtimes' => $item['card_addtimes']
            ];

        }

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

    /**
     * @Desc 激活记录
     * @Author Gorden
     * @Date 2024/11/27 16:04
     *
     * @param Request $request
     * @return Response
     */
    public function usedList(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 10);
        $mainId = $request->get('main_id');
        if (!$mainId) {
            return json_fail("参数异常");
        }

        $cards = Card::leftJoin("member", 'member.member_id', '=', 'card.join_card_member_id')
            ->leftJoin('member_cert', 'member_cert.join_cert_member_id', '=', 'card.join_card_member_id')
            ->leftJoin('sys_dept', 'sys_dept.dept_id', '=', 'card.join_card_dept_id')
            ->where('join_card_main_id', $mainId)
            ->whereRaw("CAST(UNIX_TIMESTAMP(JSON_UNQUOTE(JSON_EXTRACT(card_extend_json,'$.used_datetime'))) as SIGNED) > 0");
        $total = $cards->count();
        $rows = $cards->selectRaw("CAST(UNIX_TIMESTAMP(JSON_UNQUOTE(JSON_EXTRACT(card_extend_json,'$.used_datetime'))) as SIGNED) as used_time,
            member_mobile,member_cert_name,dept_name,card_id,card_status,card_addtimes")
            ->orderByDesc('used_time')
            ->forPage($page, $pageSize)
            ->get()
            ->toArray();
        foreach ($rows as &$row) {
            $mobile = $row['member_mobile'] ?? '';
            $certName = $row['member_cert_name'] ?? '';
            $row['member_name'] = MemberService::getMemberCertName($mobile, $certName, '');
            $row['used_time'] = date('Y-m-d H:i:s', $row['used_time']);
        }

        return json_success('', compact('rows', 'page', 'pageSize', 'total'));
    }

    /**
     * @Desc 发行记录
     * @Author Gorden
     * @Date 2024/11/27 16:05
     *
     * @param Request $request
     * @return Response
     */
    public function issueList(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 10);
        $mainId = $request->get('main_id');
        if (!$mainId) {
            return json_fail("参数异常");
        }

        $cards = Card::leftJoin("member", 'member.member_id', '=', 'card.join_card_member_id')
            ->leftJoin('member_cert', 'member_cert.join_cert_member_id', '=', 'card.join_card_member_id')
            ->leftJoin('sys_dept', 'sys_dept.dept_id', '=', 'card.join_card_dept_id')
            ->where('join_card_main_id', $mainId)
            ->whereRaw("CAST(UNIX_TIMESTAMP(JSON_UNQUOTE(JSON_EXTRACT(card_extend_json,'$.issue_datetime'))) as SIGNED) > 0");
        $total = $cards->count();
        $rows = $cards->selectRaw("CAST(UNIX_TIMESTAMP(JSON_UNQUOTE(JSON_EXTRACT(card_extend_json,'$.issue_datetime'))) as SIGNED) as issue_time,
            member_mobile,member_cert_name,dept_name,card_id,card_status,card_addtimes")
            ->orderByDesc('issue_time')
            ->forPage($page, $pageSize)
            ->get()
            ->toArray();
        foreach ($rows as &$row) {
            $mobile = $row['member_mobile'] ?? '';
            $certName = $row['member_cert_name'] ?? '';
            $row['member_name'] = MemberService::getMemberCertName($mobile, $certName, '');
            $row['issue_time'] = date('Y-m-d H:i:s', $row['issue_time']);
        }

        return json_success('', compact('rows', 'page', 'pageSize', 'total'));
    }
}