<?php

namespace app\admin\service\coupon;

use app\model\Card;
use app\model\CardMain;
use app\model\Goods;
use app\model\MemberAccount;
use app\model\MemberAccountList;
use app\model\SysCategory;
use support\Db;
use support\Log;
use support\exception\BusinessException;

class CardService
{
    /**
     * @Desc 生成卡ID
     * @Author Gorden
     * @Date 2024/11/25 13:46
     *
     * @param $params
     * @param $i
     * @return false|string
     */
    public static function generateCardId($params, $i)
    {
        $prefixLength = strlen($params['card_issue_serial_prefix']);
        $suffixLength = strlen($params['card_issue_serial_suffix']);
        $cardId = $params['card_issue_serial_prefix'] . str_pad($params['card_issue_serial_begin'] + $i, $params['card_issue_serial_length'] - $prefixLength - $suffixLength, $params['card_issue_serial_fill'], STR_PAD_LEFT) . $params['card_issue_serial_suffix'];
        if (!empty($params['card_issue_not_contain'])) {
            $notContains = explode(',', $params['card_issue_not_contain']);
            foreach ($notContains as $notContain) {
                if (strpos($cardId, $notContain) !== false) {
                    return false;
                }
            }
        }

        return $cardId;
    }

    /**
     * @Desc 生成按需卡号
     * @Author Gorden
     * @Date 2024/12/9 15:02
     *
     * @param $demandConfig
     * @param $lastCard
     * @return string
     */
    public static function generateDemandCardId($demandConfig, $lastCard)
    {
        $prefixLength = strlen($demandConfig['prefix']);
        $suffixLength = strlen($demandConfig['suffix']);
        $rand = $demandConfig['rand'] ?? 0;
        $begin = $demandConfig['begin'] ?? 1;
        if (!empty($lastCard)) {
            $oldCardId = $lastCard->card_id;
            $oldCardId = substr($oldCardId, strripos($oldCardId, $demandConfig['prefix']) + $prefixLength);
            if (strrpos($oldCardId, $demandConfig['suffix']) !== false){
                $oldCardId = substr($oldCardId, 0, strrpos($oldCardId, $demandConfig['suffix']));
            }

            $number = intval($oldCardId) + 1;
        } else {
            $number = $begin;
        }

        return $demandConfig['prefix'] . str_pad($number, $demandConfig['length'] - $prefixLength - $suffixLength, $rand, STR_PAD_LEFT) . $demandConfig['suffix'];
    }

    /**
     * @Desc 储值卡过期
     * @Author Gorden
     * @Date 2024/12/6 14:38
     *
     * @return void
     */
    public static function checkExpired()
    {
        $unixTime = time();
        $cards = Card::whereRaw("CAST(UNIX_TIMESTAMP(card_deadline_datetime) as SIGNED) <= {$unixTime}")
            ->whereRaw("CAST(UNIX_TIMESTAMP(card_deadline_datetime) as SIGNED) > 0")
            ->whereIn('card_status', ['INIT', 'WAITING', 'PENDING', 'USED'])
            ->select('card_id')
            ->get()
            ->toArray();
        foreach ($cards as $card) {
            // 检查是否关联会员账户
            $account = MemberAccount::where('member_account_nbr', $card['card_id'])->first();
            if (!empty($account) && $account->member_account_status == 'ACTIVED') {
                $account->member_account_status = 'EXPIRED';
                $account->save();
            }
            $cardNow = Card::where('card_id', $card['card_id'])->first();
            $cardNow->card_status = 'EXPIRED';
            $cardExtendJson = [];
            if (!empty($cardNow->card_extend_json)) {
                $cardExtendJson = json_decode($cardNow->card_extend_json, true);
            }
            $cardExtendJson['expired_datetime'] = date('Y-m-d H:i:s');
            $cardNow->card_extend_json = json_encode($cardExtendJson);
            $cardNow->save();

            _syslog('储值卡', "【" . $card['card_id'] . '】已过期', false, ['card_id' => $card['card_id']], 1001);

            Log::info("储值卡：【" . $card['card_id'] . '】已过期');
        }
    }

    /**
     * @Desc 按需发卡
     * @Author Gorden
     * @Date 2024/12/9 16:02
     *
     * @param $memberId
     * @param $good
     * @param $params
     * @return string
     * @throws BusinessException
     */
    public static function sendDemandCard($memberId, $good, $params)
    {
        try {
            $goodsModel = Goods::where('goods_id', $good['goods_id'])->select('goods_attribute_json')->first();
            $goodsAttributeJson = json_decode($goodsModel->goods_attribute_json, true);
            if (!empty($goodsAttributeJson['card_main_id'])) {
                $cardMain = CardMain::where('card_main_id', $goodsAttributeJson['card_main_id'])->first();
                $cardMainJson = json_decode($cardMain->card_main_json, true);
                if ($cardMainJson['issue'] == 'DEMAND') {
                    return self::issueDemandCard($memberId, $goodsAttributeJson['card_main_id'], $params, $good);;
                }
            }

            return false;
        } catch (\Exception $e) {
            throw new BusinessException("储值卡发行失败");
        }
    }

    /**
     * @Desc 发行按需卡
     * @Author Gorden
     * @Date 2024/12/9 15:27
     *
     * @param $memberId
     * @param $cardMainId
     * @param $params
     * @param $good
     */
    public static function issueDemandCard($memberId, $cardMainId, $params, $good)
    {
        try {
            $lastCard = Card::where('join_card_main_id', $cardMainId)->orderByDesc('card_addtimes')->first();
            $cardMain = CardMain::where('card_main_id', $cardMainId)->first();
            $cardMainJson = json_decode($cardMain->card_main_json, true);
            $demandConfig = $cardMainJson['demand_config'];

            $cardId = self::generateDemandCardId($demandConfig, $lastCard);
            // 开卡账户
            $accountDuedate = '';
            if ($cardMain->card_main_valid_mode == 'LONG') {
                $accountDuedate = 0;
            } elseif ($cardMain->card_main_valid_mode == 'DAYS') {
                $accountDuedate = date('Y-m-d 23:59:59', strtotime("+ " . ($cardMain->card_main_valid_days - 1) . 'day'));
            } elseif ($cardMain->card_main_valid_mode == 'DATE') {
                $accountDuedate = $cardMain->card_main_valid_end;
            }
            $accountId = MemberAccount::insertGetId([
                'join_account_member_id' => $memberId,
                'member_account_classify' => 'CARD',
                'member_account_status' => 'ACTIVED',
                'member_account_category' => 'NORMAL',
                'member_account_nbr' => $cardId,
                'member_account_name' => $cardMain->card_main_name,
                'member_account_income' => $cardMain->card_main_amount,
                'member_account_surplus' => $cardMain->card_main_amount,
                'member_account_duedate' => $accountDuedate,
                'member_account_addtimes' => time()
            ]);

            // member_account_list 加卡充值记录
            MemberAccountList::insert([
                'join_list_member_account_nbr' => $cardId,
                'join_member_account_list_member_id' => $memberId,
                'member_account_list_status' => 'ACTIVED',
                'member_account_list_attr' => 'IN',
                'member_account_list_classify' => 'CARD',
                'member_account_list_category' => '绑卡',
                'member_account_list_datetime' => date('Y-m-d H:i:s'),
                'member_account_list_amount' => $cardMain->card_main_amount,
                'member_account_list_addtimes' => time()
            ]);

            // 存卡数据
            $cardModel = new Card();
            $cardModel->card_id = $cardId;
            $cardModel->join_card_member_id = $memberId;
            $cardModel->join_card_member_account_id = $accountId;
            $cardModel->join_card_main_id = $cardMainId;
            $cardModel->card_assign_datetime = date('Y-m-d H:i:s');
            $cardModel->card_status = 'USED';
            $cardModel->card_json = json_encode([
                'order_id' => $params['orderId'],
                'goods_id' => $good['goods_id'],
                'order_amount_pay' => $params['order_amount_pay']
            ]);
            $cardModel->is_issue = 'Y';
            $cardModel->card_extend_json = json_encode([
                'buy_member' => $memberId,
                'buy_datetime' => date('Y-m-d H:i:s'),
                'buy_order_id' => $params['orderId'],
                'used_datetime' => date('Y-m-d H:i:s')
            ]);
            $cardModel->card_addtimes = time();
            $cardModel->save();

            return $cardId;
        } catch (\Exception $e) {
            Log::error("生成卡号失败", ['msg' => $e->getMessage()]);
            throw new BusinessException("生成卡号失败");
        }
    }

    /**
     * @Desc 卡包含的所哟商品
     * @Author Gorden
     * @Date 2024/12/9 17:03
     *
     * @param $goodsId
     * @param $goodsCategory
     * @return array
     */
    public static function getCardGoods($goodsId, $goodsCategory)
    {
        $categoryId = [];
        foreach ($goodsCategory as $item) {
            array_push($categoryId, $item);
            $categoryIds = SysCategory::where('category_super_path', 'like', '#' . $item . '#')->pluck('category_id')->toArray();
            $categoryId = array_merge($categoryId, $categoryIds);
        }

        $goodsIds = Goods::whereIn('join_goods_category_id', $categoryId)->pluck('goods_id')->toArray();

        return array_unique(array_merge($goodsId, $goodsIds));
    }

    public static $status = [
        'INIT' => '待分配',
        'WAITING' => '已分配，待售',
        'PENDING' => '已售，待激活',
        'USED' => '已激活',
        'DONE' => '使用完成',
        'EXPIRED' => '已过期',
        'PAUSED' => '冻结'
    ];
}