<?php
/**
 * CardBatchService.php
 * User: ZhouBenXu
 * Date: 2024/6/27
 * Time: 上午9:46
 * Notes:
 */

namespace app\admin\service\card;

use support\Db;
use support\exception\BusinessException;
use support\Response;
use app\model\CardBatch;
use app\model\Card;
use app\admin\service\card\CardService;
use app\admin\service\sys_manage\CategoryService;

class CardBatchService
{

    /**
     * Notes: 添加卡批次
     * User: ZhouBenXu
     * DateTime: 2024/6/27 上午10:04
     * @param $params
     */
    public static function insert($params)
    {
        Db::beginTransaction();
        try {
            // 添加卡批次
            $model = new CardBatch();
            if (is_array($params['join_card_batch_category_id'])) {
                $params['join_card_batch_category_id'] = end($params['join_card_batch_category_id']);
            }

            $model->join_card_batch_user_id = $params['join_card_batch_user_id']; // 批次创建用户 user_id
            $model->join_card_batch_category_id = $params['join_card_batch_category_id']; // 批次卡分类ID
            $model->card_batch_status = $params['card_batch_status']; // 批次状态
            $model->card_batch_category = $params['card_batch_category'] ?? "NORMAL"; // 批次类型 NORMAL
            $model->card_batch_name = $params['card_batch_name']; // 卡批次名称
            $model->card_batch_prefix = $params['card_batch_prefix']; // 卡批次前缀
            $model->card_batch_suffix = $params['card_batch_suffix']; // 卡批次后缀
            $model->card_batch_serial_begin = $params['card_batch_serial_begin']; // 卡批次序号起始
            $model->card_batch_serial_end = $params['card_batch_serial_end']; // 卡批次序号结束
            $model->card_batch_amount = $params['card_batch_amount']; // 卡批次面额
            $model->card_batch_validtimes = $params['card_batch_validtimes']; // 卡批次有效期 0=永久 天
            $model->card_batch_json = $params['card_batch_json'] ?? "{}"; // 卡JSON {}
            $model->card_batch_remark = $params['card_batch_remark'] ?? ""; // 备注
            $model->card_batch_extend_json = $params['card_batch_extend_json'] ?? "{}"; // 扩展 {}

            if ($model->save()) {
                $join_card_batch_id = $model->card_batch_id;
                // 添加卡信息
//                CardService::insert($join_card_batch_id, $params);

                $cardModel = new Card();
                // 生成包含序号数组
                $card_sort = range($params['card_batch_serial_begin'], $params['card_batch_serial_end']);
                $insertData = [];
                if ($params['card_batch_validtimes'] != 0) { // 卡批次有效期 0=永久 天
                    $params['card_batch_validtimes'] = (strtotime(date('Y-m-d 00:00:00')) + $params['card_batch_validtimes'] * 86400) - 1;
                }
                foreach ($card_sort as $value) {
                    $info['join_card_batch_id'] = $join_card_batch_id;
                    $info['join_card_category_id'] = $params['join_card_batch_category_id'];
                    $info['card_status'] = "INIT";
                    $info['card_category'] = $params['card_batch_category'] ?? "NORMAL"; // 批次类型 NORMAL
                    $info['card_name'] = $params['card_batch_name'];
                    $info['card_prefix'] = $params['card_batch_prefix'];
                    $info['card_suffix'] = $params['card_batch_suffix'];
                    $info['card_pass'] = mt_rand(100000, 999999);// 卡密
                    $info['card_amount'] = $params['card_batch_amount'];
                    $info['card_validtimes'] = $params['card_batch_validtimes']; // 卡批次有效期 0=永久 天
                    $info['card_json'] = "{}";
                    $info['card_assign_json'] = "{}";
                    $info['card_process_json'] = "{}";
                    $info['card_sort'] = $value;
                    $info['card_remark'] = $params['card_batch_remark'] ?? ""; // 备注
                    $info['card_extend_json'] = "{}";
                    $info['card_addtimes'] = time();
                    $insertData[] = $info;
                }
                $cardModel->insert($insertData);
            }

            Db::commit();
        } catch (\PDOException $e) {
            Db::rollBack();
            dump($e->getFile() . '(' . $e->getLine() . '):' . $e->getMessage());
            return json_fail('数据写入失败~');
        } catch (BusinessException $e) {
            Db::rollBack();
            dump($e->getFile() . '(' . $e->getLine() . '):' . $e->getMessage());
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            Db::rollBack();
            dump($e->getTrace());
            return json_fail('数据写入失败~');
        }
        _syslog("添加储值卡批次", "卡批次名称【" . $params['card_batch_name'] . "】");
        return json_success('success');
    }


    /**
     * Notes: 修改卡批次
     * User: ZhouBenXu
     * DateTime: 2024/6/27 下午4:32
     * @param $params
     * @return Response
     */
    public static function save($params)
    {
        Db::beginTransaction();
        try {
            $cardBatchModel = new CardBatch();
            $model = $cardBatchModel::find($params['card_batch_id']);
            $model->card_batch_name = $params['card_batch_name'];
            $model->card_batch_remark = $params['card_batch_remark'] ?? "";
            $params['card_batch_status'] && $model->card_batch_status = $params['card_batch_status']; // 批次状态
            // 是否有激活的卡片
            if (Card::where('join_card_batch_id', $params['card_batch_id'])->where('card_status', 'ACTIVED')->exists()) {
                return json_fail('存在已激活卡片不可以修改状态');
            }
            if ($params['validtimes_status'] == 0) {
                $model->card_batch_validtimes = 0; // 卡批次有效期 0=永久 天
            } elseif ($params['validtimes_status'] == 1) {
                $model->card_batch_validtimes = bcadd($model->card_batch_validtimes, $params['card_batch_validtimes']); // 卡批次有效期 0=永久 天
            } elseif ($params['validtimes_status'] == 2) {
                $end_date = (string)bcadd(strtotime($model->card_batch_addtimes), (bcsub($model->card_batch_validtimes, $params['card_batch_validtimes']) * 86400));
                if ($end_date <= time()) {
                    return json_fail('卡批次有效期必须大于当前时间~');
                }
                $model->card_batch_validtimes = bcsub($model->card_batch_validtimes, $params['card_batch_validtimes']); // 卡批次有效期 0=永久 天
            }
            if ($model->save()) {
                // 修改卡批次下面的卡信息
                // CardService::saveCardByCardBatchId($params['card_batch_id'], $params);
                // 修改卡批次下面的卡信息
                $model = new Card();
//                $data['card_name'] = $params['card_batch_name'];

                $card_status = array_keys($model::CARD_STATUS);
                if (in_array($params['card_batch_status'], $card_status)) {
                    $data['card_status'] = $params['card_batch_status']; // 卡批次状态
                }
                if ($params['validtimes_status'] == 0) { // 卡批次有效期 0 永久天  1 增加 2减少
                    $data['card_validtimes'] = 0;
                } elseif ($params['validtimes_status'] == 1) {
                    $data['card_validtimes'] = Db::raw('card_validtimes+' . $params['card_batch_validtimes'] * 86400);
                } elseif ($params['validtimes_status'] == 2) {
                    $data['card_validtimes'] = Db::raw('card_validtimes-' . $params['card_batch_validtimes'] * 86400);;
                }
                $model->where('join_card_batch_id', $params['card_batch_id'])->update($data);
            }
            Db::commit();
        } catch (\PDOException $e) {
            Db::rollBack();
            dump($e->getFile() . '(' . $e->getLine() . '):' . $e->getMessage());
            return json_fail('数据写入失败~');
        } catch (BusinessException $e) {
            Db::rollBack();
            dump($e->getFile() . '(' . $e->getLine() . '):' . $e->getMessage());
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            Db::rollBack();
            dump($e->getTrace());
            return json_fail('数据写入失败~');
        }
        _syslog("修改储值卡批次", "卡批次名称【" . $params['card_batch_name'] . "】");
        return json_success('success');
    }


    /**
     * Notes: 删除卡批次
     * User: ZhouBenXu
     * DateTime: 2024/6/27 下午5:53
     * @param $card_batch_ids
     * @return Response
     */
    public static function delete($card_batch_ids)
    {
        if (!is_array($card_batch_ids)) {
            $card_batch_ids = [$card_batch_ids];
        }
        $cardBatch = CardBatch::whereIn('card_batch_id', $card_batch_ids)->get()->toArray();
        if (!$cardBatch) {
            return json_fail("数据错误~");
        }
        // 是否有激活的卡片
        if (Card::whereIn('join_card_batch_id', $card_batch_ids)->where('card_status', 'ACTIVED')->exists()) {
            return json_fail('存在已激活卡片不可以删除');
        }
        Db::beginTransaction();
        try {
            CardBatch::whereIn('card_batch_id', $card_batch_ids)->delete();
            Card::whereIn('join_card_batch_id', $card_batch_ids)->delete();
            Db::commit();
            _syslog("删除储值卡批次", "删除的卡批次ID【" . implode(',', $card_batch_ids) . '】');
            return json_success("卡批次删除成功");
        } catch (\Exception $e) {
            Db::rollBack();
            return json_fail("卡批次删除失败~");
        }
    }


    /**
     * Notes: 卡批次列表
     * User: ZhouBenXu
     * DateTime: 2024/6/28 上午9:43
     * @param $params
     * @return Response
     */
    public static function getList($params)
    {
        $cardBatchModel = new CardBatch();
        $page = $params['page'];
        $page_size = $params['pageSize'];
        $card_batch_name = $params['card_batch_name'] ?? "";
        $card_batch_status = !empty($params['card_batch_status']) ? $cardBatchModel::CARD_BATCH_STATUS[$params['card_batch_status']] : "";
        $join_card_batch_category_id = $params['join_card_batch_category_id'] ?? "";
        $rows = $cardBatchModel::select('*')
            ->when(!empty($card_batch_name) && $card_batch_name != '', function ($query) use ($card_batch_name) {
                $query->where('card_batch_name', 'like', '%' . $card_batch_name . '%');
            })->when(!empty($card_batch_status), function ($query) use ($card_batch_status) {
                $query->where('card_batch_status', $card_batch_status);
            })->when(!empty($join_card_batch_category_id), function ($query) use ($join_card_batch_category_id) {
                $query->where('join_card_batch_category_id', $join_card_batch_category_id);
            })
            ->orderBy('card_batch_id', 'DESC')
            ->forPage($page, $page_size)
            ->get()
            ->toArray();

        $total = $cardBatchModel::select('*')
            ->when(!empty($card_batch_name) && $card_batch_name != '', function ($query) use ($card_batch_name) {
                $query->where('card_batch_name', 'like', '%' . $card_batch_name . '%');
            })->when(!empty($card_batch_status), function ($query) use ($card_batch_status) {
                $query->where('card_batch_status', $card_batch_status);
            })->when(!empty($join_card_batch_category_id), function ($query) use ($join_card_batch_category_id) {
                $query->where('join_card_batch_category_id', $join_card_batch_category_id);
            })->count();


        if (!empty($rows)) {

            // 查询所有分类信息
            $category = array_column($rows, 'join_card_batch_category_id');
            $categoryInfos = CategoryService::getCategoryInfos($category) ?? [];
            $categoryInfos && $categoryInfos = array_column($categoryInfos, null, 'category_id');

            // 查询求和数据信息
            $card_batch_id_string = implode(',', array_column($rows, 'card_batch_id'));
            $sql = "select join_card_batch_id,
                    -- INIT
                    IFNULL(SUM(CASE WHEN card_status = 'INIT' THEN counts ELSE 0 END),0) as status_INIT_counts,
                    IFNULL(SUM(CASE WHEN card_status = 'INIT' THEN amounts ELSE 0 END),0) as status_INIT_amounts,
                    -- PRODUCTED
                    IFNULL(SUM(CASE WHEN card_status = 'PRODUCTED' THEN counts ELSE 0 END),0) as status_PRODUCTED_counts,
                    IFNULL(SUM(CASE WHEN card_status = 'PRODUCTED' THEN amounts ELSE 0 END),0) as status_PRODUCTED_amounts,
                    -- ENABLED
                    IFNULL(SUM(CASE WHEN card_status = 'ENABLED' THEN counts ELSE 0 END),0) as status_ENABLED_counts,
                    IFNULL(SUM(CASE WHEN card_status = 'ENABLED' THEN amounts ELSE 0 END),0) as status_ENABLED_amounts,
                    -- WAITING
                    IFNULL(SUM(CASE WHEN card_status = 'WAITING' THEN counts ELSE 0 END),0) as status_WAITING_counts,
                    IFNULL(SUM(CASE WHEN card_status = 'WAITING' THEN amounts ELSE 0 END),0) as status_WAITING_amounts,
                    -- PENDING
                    IFNULL(SUM(CASE WHEN card_status = 'PENDING' THEN counts ELSE 0 END),0) as status_PENDING_counts,
                    IFNULL(SUM(CASE WHEN card_status = 'PENDING' THEN amounts ELSE 0 END),0) as status_PENDING_amounts,
                    -- ACTIVED
                    IFNULL(SUM(CASE WHEN card_status = 'ACTIVED' THEN counts ELSE 0 END),0) as status_ACTIVED_counts,
                    IFNULL(SUM(CASE WHEN card_status = 'ACTIVED' THEN amounts ELSE 0 END),0) as status_ACTIVED_amounts,
                    -- DISABLED
                    IFNULL(SUM(CASE WHEN card_status = 'DISABLED' THEN counts ELSE 0 END),0) as status_DISABLED_counts,
                    IFNULL(SUM(CASE WHEN card_status = 'DISABLED' THEN amounts ELSE 0 END),0) as status_DISABLED_amounts,
                    -- EXPIRED
                    IFNULL(SUM(CASE WHEN card_status = 'EXPIRED' THEN counts ELSE 0 END),0) as status_EXPIRED_counts,
                    IFNULL(SUM(CASE WHEN card_status = 'EXPIRED' THEN amounts ELSE 0 END),0) as status_EXPIRED_amounts,
                    -- PAUSED
                    IFNULL(SUM(CASE WHEN card_status = 'PAUSED' THEN counts ELSE 0 END),0) as status_PAUSED_counts,
                    IFNULL(SUM(CASE WHEN card_status = 'PAUSED' THEN amounts ELSE 0 END),0) as status_PAUSED_amounts 
                    from (select join_card_batch_id, card_status, COUNT(*) as counts, SUM(card_amount) as amounts, SUM(card_added) as addeds from app_card where join_card_batch_id in (" . $card_batch_id_string . ") group by join_card_batch_id, card_status) group_data
                    group by join_card_batch_id";

            $card_status_total = Db::select($sql);
            $card_status_total = array_column($card_status_total, null, 'join_card_batch_id');
            foreach ($rows as $key => &$value) {
                $value['card_batch_status_value'] = $cardBatchModel::CARD_BATCH_STATUS[$value['card_batch_status']];
                $value['category_name'] = $categoryInfos[$value['join_card_batch_category_id']]['category_name'] ?? "";
                if ($value['card_batch_validtimes'] == 0) {
                    $value['card_batch_validtimes_value'] = "永久";
                } else {
                    $value['card_batch_validtimes_value'] = $value['card_batch_validtimes'];
                }

                !empty($value['card_batch_json']) && $value['card_batch_json'] = json_decode($value['card_batch_json'], true);
                !empty($value['card_batch_extend_json']) && $value['card_batch_extend_json'] = json_decode($value['card_batch_extend_json'], true);
                // 合并储值卡面值以及状态数量
                if (!empty($card_status_total[$value['card_batch_id']])) {
                    if (is_array($card_status_total[$value['card_batch_id']])) {
                        $value = array_merge($value, $card_status_total[$value['card_batch_id']]);
                    } else {
                        $value = array_merge($value, json_decode(json_encode($card_status_total[$value['card_batch_id']]), true));
                    }
                }
            }
        }
        return json_success('', compact('rows', 'page', 'page_size', 'total'));
    }


    /**
     * Notes: 卡批次详情
     * User: ZhouBenXu
     * DateTime: 2024/6/28 上午10:50
     * @param $card_batch_id
     * @return Response
     */
    public static function getInfo($card_batch_id)
    {
        $cardBatch = CardBatch::where('card_batch_id', $card_batch_id)->first() ?? [];
        if (!empty($cardBatch)) {
            $cardBatch['card_batch_status_value'] = array_flip(CardBatch::CARD_BATCH_STATUS)[$cardBatch['card_batch_status']];
            !empty($cardBatch['card_batch_json']) && $cardBatch['card_batch_json'] = json_decode($cardBatch['card_batch_json'], true);
            !empty($cardBatch['card_batch_extend_json']) && $cardBatch['card_batch_extend_json'] = json_decode($cardBatch['card_batch_extend_json'], true);
        }
        return json_success('', $cardBatch);
    }

    /**
     * Notes: 卡状态下拉列表
     * User: ZhouBenXu
     * DateTime: 2024/7/1 上午9:27
     * @return Response
     */
    public static function getStatusList()
    {
        $data = [];
        $statusList = CardBatch::CARD_BATCH_STATUS;
        foreach ($statusList as $key => $value) {
            $info = [];
            $info['status'] = $key;
            $info['status_value'] = $value;
            $data[] = $info;
        }
        return json_success('', $data);
    }

}