<?php
/**
 * CardService.php
 * User: ZhouBenXu
 * Date: 2024/6/27
 * Time: 上午9:46
 * Notes: 卡管理
 */

namespace app\admin\service\card;

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

class CardService
{

    /**
     * Notes: 添加卡信息
     * User: ZhouBenXu
     * DateTime: 2024/6/27 下午2:58
     * @param $join_card_batch_id 卡批次id
     * @param $card_info 卡信息
     * @return \support\Response
     */
    public static function insert($join_card_batch_id, $card_info)
    {
        Db::beginTransaction();
        try {
            $model = new Card();
            // 生成包含100到200的数组
            $card_sort = range($card_info['card_batch_serial_begin'], $card_info['card_batch_serial_end']);
            $insertData = [];
            if ($card_info['card_batch_validtimes'] != 0) { // 卡批次有效期 0=永久 天
                $card_info['card_batch_validtimes'] = (strtotime(date('Y-m-d 00:00:00')) + $card_info['card_batch_validtimes'] * 86400) - 1;
            }
            foreach ($card_sort as $value) {
                $info['join_card_batch_id'] = $join_card_batch_id;
                $info['join_card_category_id'] = $card_info['join_card_batch_category_id'];
                $info['card_status'] = $model::CARD_STATUS[1];
                $info['card_category'] = $card_info['card_batch_category'];
                $info['card_name'] = $card_info['card_batch_name'];
                $info['card_prefix'] = $card_info['card_batch_prefix'];
                $info['card_suffix'] = $card_info['card_batch_suffix'];
                $info['card_pass'] = mt_rand(10000000, 99999999);// 卡密
                $info['card_amount'] = $card_info['card_batch_amount'];
                $info['card_validtimes'] = $card_info['card_batch_validtimes']; // 卡批次有效期 0=永久 天
                $info['card_json'] = "{}";
                $info['card_assign_json'] = "{}";
                $info['card_process_json'] = "{}";
                $info['card_sort'] = $value;
                $info['card_remark'] = "";
                $info['card_extend_json'] = "{}";
                $info['card_addtimes'] = time();
                $insertData[] = $info;
            }
            $model->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("添加储值卡", "卡批次名称【" . $card_info['card_batch_name'] . "】", $insertData);
        return json_success('success');
    }


    /**
     * Notes: 根据卡批次修改卡信息
     * User: ZhouBenXu
     * DateTime: 2024/6/27 下午5:03
     * @param $join_card_batch_id
     * @param $save
     * @return string|\support\Response|true
     */
    public static function saveCardByCardBatchId($join_card_batch_id, $save)
    {

        Db::beginTransaction();
        try {
            $model = new Card();
            $data['card_name'] = $save['card_batch_name'];

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


    /**
     * Notes: 储值卡列表
     * User: ZhouBenXu
     * DateTime: 2024/6/28 上午11:36
     * @param $params
     * @return \support\Response
     */
    public static function getList($params)
    {

        $cardModel = new Card();
        $page = $params['page'];
        $page_size = $params['pageSize'];
        $join_card_batch_id = $params['join_card_batch_id'] ?? "";
        $join_card_category_id = $params['join_card_category_id'] ?? "";
        $join_card_member_id = $params['join_card_member_id'] ?? "";
        $card_status = !empty($params['card_status']) ? $params['card_status'] : "";
        $card_category = $params['card_category'] ?? "";
        $card_name = $params['card_name'] ?? "";

        $rows = $cardModel::select('*')
            ->when(!empty($card_name) && $card_name != '', function ($query) use ($card_name) {
                $query->where('card_name', 'like', '%' . $card_name . '%');
            })->when(!empty($card_status), function ($query) use ($card_status) {
                $query->where('card_status', $card_status);
            })->when(!empty($join_card_batch_id), function ($query) use ($join_card_batch_id) {
                $query->where('join_card_batch_id', $join_card_batch_id);
            })->when(!empty($join_card_category_id), function ($query) use ($join_card_category_id) {
                $query->where('join_card_category_id', $join_card_category_id);
            })->when(!empty($join_card_member_id), function ($query) use ($join_card_member_id) {
                $query->where('join_card_member_id', $join_card_member_id);
            })->when(!empty($card_category), function ($query) use ($card_category) {
                $query->where('card_category', $card_category);
            })
            ->orderBy('card_id', 'DESC')
            ->forPage($page, $page_size)
            ->get()
            ->toArray();

        $total = $cardModel::select('card_id')
            ->when(!empty($card_name) && $card_name != '', function ($query) use ($card_name) {
                $query->where('card_name', 'like', '%' . $card_name . '%');
            })->when(!empty($card_status), function ($query) use ($card_status) {
                $query->where('card_status', $card_status);
            })->when(!empty($join_card_batch_id), function ($query) use ($join_card_batch_id) {
                $query->where('join_card_batch_id', $join_card_batch_id);
            })->when(!empty($join_card_category_id), function ($query) use ($join_card_category_id) {
                $query->where('join_card_category_id', $join_card_category_id);
            })->when(!empty($join_card_member_id), function ($query) use ($join_card_member_id) {
                $query->where('join_card_member_id', $join_card_member_id);
            })->when(!empty($card_category), function ($query) use ($card_category) {
                $query->where('card_category', $card_category);
            })
            ->count();
        if (!empty($rows)) {
            // 查询所有分类信息
            $category = array_column($rows, 'join_card_category_id');
            $categoryInfos = CategoryService::getCategoryInfos($category) ?? [];
            $categoryInfos && $categoryInfos = array_column($categoryInfos, null, 'category_id');
            // 查询会员信息


            foreach ($rows as $key => &$value) {
                $value['category_name'] = $categoryInfos[$value['join_card_category_id']]['category_name'] ?? "";
                $value['card_status_value'] = Card::CARD_STATUS[$value['card_status']];
                !empty($value['card_json']) && $value['card_json'] = json_decode($value['card_json'], true);
                !empty($value['card_assign_json']) && $value['card_assign_json'] = json_decode($value['card_assign_json'], true);
                !empty($value['card_process_json']) && $value['card_process_json'] = json_decode($value['card_process_json'], true);
                !empty($value['card_extend_json']) && $value['card_extend_json'] = json_decode($value['card_extend_json'], true);
                $value['card_no'] = $value['card_prefix'] . $value['card_sort'] . $value['card_suffix'];
                if ($value['card_validtimes'] == 0) {
                    $value['card_validtimes'] = "永久";
                } else {
                    $value['card_validtimes'] = date("Y-m-d H:i:s", $value['card_validtimes']);
                }

            }

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


    /**
     * Notes: 储值卡详情
     * User: ZhouBenXu
     * DateTime: 2024/6/28 上午11:41
     * @param $card_id
     * @return \support\Response
     */
    public static function getInfo($card_id)
    {
        $cardInfo = Card::where('card_id', $card_id)->first() ?? [];
        if (!empty($cardInfo)) {
            $cardInfo['card_status_value'] = $cardInfo['card_status'];
            $cardInfo['card_status'] = array_flip(Card::CARD_STATUS)[$cardInfo['card_status']];
            !empty($cardInfo['card_json']) && $cardInfo['card_json'] = json_decode($cardInfo['card_json'], true);
            !empty($cardInfo['card_assign_json']) && $cardInfo['card_assign_json'] = json_decode($cardInfo['card_assign_json'], true);
            !empty($cardInfo['card_process_json']) && $cardInfo['card_process_json'] = json_decode($cardInfo['card_process_json'], true);
            !empty($cardInfo['card_extend_json']) && $cardInfo['card_extend_json'] = json_decode($cardInfo['card_extend_json'], true);
        }
        return json_success('', $cardInfo);
    }

    /**
     * Notes: 储值卡导出数据
     * User: ZhouBenXu
     * DateTime: 2024/6/28 下午2:44
     * @param Request $request
     * @return \support\Response
     */
    public static function exportCard(Request $request)
    {
        $params = $request->get();

        $join_card_batch_id = $params['join_card_batch_id'] ?? "";
        $join_card_category_id = $params['join_card_category_id'] ?? "";
        $join_card_member_id = $params['join_card_member_id'] ?? "";
        $card_status = !empty($params['card_status']) ? $params['card_status'] : "";
        $card_category = $params['card_category'] ?? "";
        $card_name = $params['card_name'] ?? "";
        $card_ids = $params['card_id'] ?? "";

        $cardModel = new Card();
        $list = $cardModel::select('*')
            ->when(!empty($card_name) && $card_name != '', function ($query) use ($card_name) {
                $query->where('card_name', 'like', '%' . $card_name . '%');
            })->when(!empty($card_status), function ($query) use ($card_status) {
                $query->where('card_status', $card_status);
            })->when(!empty($join_card_batch_id), function ($query) use ($join_card_batch_id) {
                $query->where('join_card_batch_id', $join_card_batch_id);
            })->when(!empty($join_card_category_id), function ($query) use ($join_card_category_id) {
                $query->where('join_card_category_id', $join_card_category_id);
            })->when(!empty($join_card_member_id), function ($query) use ($join_card_member_id) {
                $query->where('join_card_member_id', $join_card_member_id);
            })->when(!empty($card_category), function ($query) use ($card_category) {
                $query->where('card_category', $card_category);
            })
            ->whereIn('card_id', $card_ids)
            ->get()
            ->toArray();
        $exportData = [];
        // 增加签名
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                $info['card_name'] = $value['card_name'];
                $info['card_pass'] = $value['card_pass'];
                $info['card_prefix'] = $value['card_prefix'];
                $info['card_suffix'] = $value['card_suffix'];
                $info['card_sort'] = $value['card_sort'];
                if ($value['card_validtimes'] == 0) {
                    $info['card_validtimes'] = "永久";
                } else {
                    $info['card_validtimes'] = date("Y-m-d H:i:s", $value['card_validtimes']);
                }
                // 生成签名
                $card_no = $value['card_prefix'] . $value['card_sort'] . $value['card_suffix'];
                $card_sign = self::generateSignature($info, $info['card_pass']);
                $card_extend_json['action'] = "bind-card";
                $card_extend_json['data'] = ["card_id" => $card_no, "card_sign" => $card_sign];
                $info['card_no'] = $card_no;
                $info['card_extend_json'] = json_encode($card_extend_json);
                $exportData[] = $info;
            }
        }
        return json_success('', $exportData);
    }

    /**
     * Notes: 生成签名
     * User: ZhouBenXu
     * DateTime: 2024/6/28 下午2:32
     * @param $data
     * @param $secret
     * @return string
     */
    public static function generateSignature($data, $secret)
    {
        // 将数组转换为字符串，并按照字母排序
        $dataString = http_build_query($data, '', '&', PHP_QUERY_RFC3986);
        // 使用HMAC-SHA256算法生成签名
        $signature = hash_hmac('sha256', $dataString, $secret);
        return $signature;
    }


    /**
     * Notes: 验证签名
     * User: ZhouBenXu
     * DateTime: 2024/6/28 下午2:33
     * @param $data
     * @param $providedSignature
     * @param $secret
     * @return bool
     */
    public static function verifySignature($data, $providedSignature, $secret)
    {
        // 生成数据的签名
        $generatedSignature = self::generateSignature($data, $secret);
        // 比较生成的签名与提供的签名是否一致
        return hash_equals($generatedSignature, $providedSignature);
    }


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


    /**
     * Notes: 储值卡修改
     * User: ZhouBenXu
     * DateTime: 2024/6/28 下午3:17
     * @param $params
     * @return \support\Response
     */
    public static function save($params)
    {
        Db::beginTransaction();
        try {
            $cardBatchModel = new Card();
            $model = $cardBatchModel::find($params['card_id']);
            $model->card_name = $params['card_name'];
            $model->card_remark = $params['card_remark'] ?? "";

            if ($model->card_status == "ACTIVED") {
                return json_fail('已激活卡片不可以修改状态');
            }

            $params['join_card_member_id'] && $model->join_card_member_id = $params['join_card_member_id'] ?? "";
            $params['card_status'] && $model->card_status = $params['card_status']; // 储值卡状态
            if ($params['validtimes_status'] == 0) { // 卡批次有效期 0 永久天  1 增加 2减少
                $model->card_validtimes = 0;
            } elseif ($params['validtimes_status'] == 1) {
                $model->card_validtimes = bcadd($model->card_validtimes, $params['card_validtimes'] * 86400);
            } elseif ($params['validtimes_status'] == 2) {
                $card_validtimes = bcsub($model->card_validtimes, $params['card_validtimes'] * 86400);
                // 修改后的有效期不允许小于当前时间
                if ($card_validtimes <= time()) {
                    return json_fail('储值卡有效期必须大于当前时间~');
                }
                $model->card_validtimes = $card_validtimes;
            }
            $model->save();
            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("修改储值卡", "储值卡id【" . $params['card_id'] . "】");
        return json_success('success');
    }

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


    /**
     * Notes: 储值卡绑定
     * User: ZhouBenXu
     * DateTime: 2024/7/2 下午6:08
     * @param $params
     * @return Response
     */
    public static function binding($params)
    {
        Db::beginTransaction();
        try {
            $card_ids = $params['card_id'];
            if (!is_array($card_ids)) {
                $card_ids = [$card_ids];
            }
            Card::whereIn('card_id', $card_ids)->update(['join_card_member_id'=>$params['join_card_member_id']]);
            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("绑定储值卡", "储值卡ID【" . implode(',', $card_ids) . '】');
        return json_success('success');
    }


}