<?php

namespace app\admin\controller\member;

use app\admin\service\goods\GoodsService;
use app\admin\service\order\OrderService;
use app\controller\Curd;
use app\model\Card;
use app\model\Goods;
use app\model\Member;
use app\model\MemberAccount;
use app\model\MemberAccountList;
use app\model\MemberBenefit;
use app\model\Order;
use app\model\OrderSheet;
use app\model\PayDetail;
use app\model\SysCategory;
use support\Db;
use support\exception\BusinessException;
use support\Log;
use support\Redis;
use support\Request;
use Tinywan\Jwt\JwtToken;

class AccountController extends Curd
{
    public function __construct()
    {
        $this->model = new MemberAccount();
    }

    public function my($id)
    {
        $account = MemberAccount::where('join_account_member_id', $id)->get()->toArray();
        if (!$account) {
            // 账户表
            $accountData = [
                'join_account_member_id' => $id,
                'member_account_classify' => 'POINTS',
                'member_account_status' => 'ACTIVED',
                'member_account_category' => 'NORMAL',
                'member_account_nbr' => $id . '-POINTS',
                'member_account_name' => '积分账户',
                'member_account_addtimes' => time()
            ];
            // 积分账户
            MemberAccount::insert($accountData);
            $accountData['member_account_classify'] = 'CASH';
            $accountData['member_account_nbr'] = $id . '-CASH';
            $accountData['member_account_name'] = '余额账户';
            // 现金/余额账户
            MemberAccount::insert($accountData);

            $account = MemberAccount::where('join_account_member_id', $id)->get()->toArray();
        }
        if ($account[0]['member_account_classify'] == 'POINTS') {
            $account = array_reverse($account);
        }

        foreach ($account as &$item) {
            $item['member_account_duedate'] = !empty($item['member_account_duedate']) ? date('Y-m-d H:i:s', $item['member_account_duedate']) : '长期有效';
            $item['member_account_surplus'] = round($item['member_account_surplus'] + $item['member_account_added'], 2);
        }

        return json_success('', $account);

    }

    public function incomeExpend(Request $request)
    {
        $params = $request->post();
        $account = MemberAccount::where('member_account_id', $params['member_account_id'])->first();
        if (!$account) {
            return json_fail('账户不存在');
        }
        try {
            if (!empty($params['type']) && $params['type'] == 'income') {
                $account->member_account_income = $account->member_account_income + $params['income'];
                $account->member_account_surplus = $account->member_account_surplus + $params['income'];
                $account->member_account_update_user_id = JwtToken::getCurrentId();
                $account->member_account_updatetimes = time();
                $account->save();
            } elseif (!empty($params['type']) && $params['type'] == 'expend') {
                $account->member_account_expend = $account->member_account_expend + $params['expend'];
                $account->member_account_surplus = $account->member_account_surplus - $params['expend'];
                $account->member_account_update_user_id = JwtToken::getCurrentId();
                $account->member_account_updatetimes = time();
                $account->save();
            }

            _syslog("账户出入账", $params['type'] == 'income' ? '入账' : '出账');

            return json_success("操作成功");
        } catch (\Exception $e) {
            return json_fail('操作失败');
        }
    }

    /**
     * 用户的账户
     */
    public function selectMemberAccount(Request $request)
    {
        $memberId = $request->get('member_id', '');
        if (!$memberId) {
            return json_fail('参数异常');
        }

        $account = MemberAccount::where('join_account_member_id', $memberId)->get()->toArray();

        $data = [];
        foreach ($account as $item) {
            $item['member_account_duedate'] = !empty($item['member_account_duedate']) ? date('Y-m-d H:i:s', $item['member_account_duedate']) : '长期有效';

            if ($item['member_account_classify'] == 'POINTS') {
                $data['points'] = $item;
            } elseif ($item['member_account_classify'] == 'CASH') {
                $data['cash'] = $item;
            } elseif ($item['member_account_classify'] == 'CARD') {
                if (intval($item['member_account_surplus']) == 0 && intval($item['member_account_added']) == 0) {
                    continue;
                }
                $data['card'][] = $item;
            } elseif ($item['member_account_classify'] == 'WELFARE') {
                $data['welfare'] = $item;
            } elseif ($item['member_account_classify'] == 'VIP') {
                $data['vip'] = $item;
            }
        }

        return json_success('', $data);
    }

    /**
     * @Desc 修改账户状态
     * @Author Gorden
     * @Date 2024/9/12 16:28
     *
     * @param Request $request
     * @return \support\Response
     */
    public function updateStatus(Request $request)
    {
        $accountId = $request->post('account_id');
        $status = $request->post('status');
        if (!$accountId || !$status || !in_array($status, ['DISABLED', 'ACTIVED', 'EXPIRED'])) {
            return json_fail('参数异常');
        }
        try {
            $account = MemberAccount::where('member_account_id', $accountId)->first();
            $account->member_account_status = $status;
            $account->save();
            // 储值卡账户，把卡冻结掉
            if ($account->member_account_classify == 'CARD') {
                $card = Card::where('card_id', $account->member_account_nbr)->first();
                $cardExtendJson = [];
                if (!empty($card->card_extend_json)) {
                    $cardExtendJson = json_decode($card->card_extend_json, true);
                }
                if ($status == 'DISABLED') {
                    $card->card_status = 'PAUSED';
                    $cardExtendJson['paused_datetime'] = date('Y-m-d H:i:s');
                    $cardExtendJson['paused_user_id'] = JwtToken::getCurrentId();
                    $card->card_extend_json = json_encode($cardExtendJson);
                } elseif ($status == 'ACTIVED') {
                    $card->card_status = 'USED';
                }
                $card->save();
            }

            _syslog("修改账户状态", '修改账户状态成功');
            return json_success('账户状态修改成功');
        } catch (\Exception $e) {
            _syslog("修改账户状态", '账户状态修改失败');
            return json_fail('账户状态修改失败');
        }
    }

    /**
     * @Desc 会员绑定储值卡
     * @Author Gorden
     * @Date 2024/11/19 11:12
     *
     * @param Request $request
     * @return \support\Response
     */
    public function bindCard(Request $request)
    {
        $cardId = $request->post('card_id');
        $cardKey = $request->post('card_cdkey');
        $memberId = $request->post('member_id');
        if (!Member::where('member_id', $memberId)->where('member_status', 'ACTIVED')->exists()) {
            return json_fail('会员不存在');
        }
        // 防刷
        $redisKey = $memberId . '_' . $cardId;
        $num = 0;
        if (Redis::exists($redisKey)) {
            $num = Redis::get($redisKey);
        }
        if ($num >= 3) {
            return json_fail("请30分钟后重试");
        }
        Redis::set($redisKey, $num + 1, 'EX', 1800);

        $card = Card::with([
            'main' => function ($query) {
                $query->select('card_main_id', 'card_main_name', 'card_main_amount', 'card_main_added');
            }
        ])->where('card_id', $cardId)
            ->first();
        if (!$card || empty($card->main)) {
            return json_fail("卡号不存在");
        }
        if ($card->card_cdkey != $cardKey) {
            return json_fail("秘钥错误，请重新输入");
        }
        if ($card->is_issue == 'N') {
            return json_fail("卡号未发行");
        }
        if (!in_array($card->card_status, ['INIT', 'WAITING', 'PENDING'])) {
            return json_fail("卡号不是可绑定状态");
        }
        // 清除防刷
        Redis::del($redisKey);

        Db::beginTransaction();
        try {
            $duedate = 0;
            if ($card->main->card_main_valid_mode == 'DAYS') {
                $duedate = date('Y-m-d H:i:s', strtotime("+ " . $card->main->card_main_valid_days . "days") - 1);
            } elseif ($card->main->card_main_valid_mode == 'DATE') {
                $duedate = $card->main->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' => $card->card_id,
                'member_account_name' => $card->main->card_main_name,
                'member_account_income' => $card->main->card_main_amount,
                'member_account_surplus' => $card->main->card_main_amount,
                'member_account_added' => $card->main->card_main_added,
                'member_account_duedate' => $duedate,
                'member_account_addtimes' => time(),
                'member_account_update_user_id' => JwtToken::getCurrentId(),
                'member_account_updatetimes' => time()
            ]);

            // 会员绑定卡
            $card->join_card_member_id = $memberId;
            $card->join_card_member_account_id = $accountId;
//            $card->card_assign_datetime = date('Y-m-d H:i:s');
            $card->card_deadline_datetime = $duedate;
            $card->card_status = 'USED';
            // 激活时间
            $cardExtendJson = [];
            if (!empty($card->card_extend_json)) {
                $cardExtendJson = json_decode($card->card_extend_json, true);
            }
            $cardExtendJson['used_datetime'] = date('Y-m-d H:i:s');
            $cardExtendJson['used_user_id'] = JwtToken::getCurrentId();
            $card->card_extend_json = json_encode($cardExtendJson);
            $card->save();

            // 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' => $card->main->card_main_amount,
                'member_account_list_addtimes' => time()
            ]);

            Db::commit();

            return json_success('success');
        } catch (\Exception $e) {
            Db::rollBack();
            Log::error("储值卡绑定失败", ['msg' => $e->getMessage()]);
            return json_fail("绑定失败");
        }
    }

    /**
     * @Desc 导出储值卡账户消费记录
     * @Author Gorden
     * @Date 2024/12/3 10:07
     *
     * @param Request $request
     * @return \support\Response
     */
    public function exportCardConsumeList(Request $request)
    {
        $memberId = $request->get('member_id', '');
        $accountNbr = $request->get('account_nbr', '');

        $account = MemberAccount::where('join_account_member_id', $memberId)
            ->where('member_account_nbr', $accountNbr)
            ->where('member_account_classify', 'CARD')
            ->first();
        if (!$account) {
            return json_fail('暂无数据');
        }
        $balance = $account->member_account_surplus + $account->member_account_added;

        $info = PayDetail::where('pay_prepayid', $accountNbr)
            ->where('pay_status', 'SUCCESS')
            ->orderByDesc('pay_addtimes')
            ->get()
            ->toArray();
        $data = [];
        foreach ($info as $key => $item) {
            unset($item['pay_json_request']);
            $categoryIds = [];
            if (!empty($item['join_pay_order_id'])) {
                $orderIds = Order::where('order_groupby', $item['join_pay_order_id'])->pluck('order_id')->toArray();
                $goodsIds = OrderSheet::whereIn('join_sheet_order_id', $orderIds)->pluck('join_sheet_goods_id')->toArray();
                $categoryIds = Goods::whereIn('goods_id', $goodsIds)->pluck('join_goods_category_id')->toArray();
            }

            $categoryName = [];
            foreach ($categoryIds as $id) {
                $category = SysCategory::where('category_id', $id)->first();
                if (!empty($category->category_super_path)) {
                    $path = explode('#', $category->category_super_path);
                    $ids = array_filter($path);
                    $categoryName[] = SysCategory::where('category_id', current($ids))->value('category_name');
                } else {
                    $categoryName[] = $category->category_name;
                }
            }
            $item['goods_category'] = implode(',', array_unique($categoryName));
            if (in_array($item['pay_category'], ['RECHARGE', 'REFUND'])) {
                $item['balance_type'] = 'add';
            } else {
                $item['balance_type'] = 'cut';
            }
            $balance = $balance + $item['pay_amount'];
            $payCategory = '消费';
            if ($item['pay_category'] == 'REFUND') {
                $payCategory = '退款';
            }
            $data[] = [
                'goods_category' => $item['goods_category'],
                'join_pay_order_id' => $item['join_pay_order_id'],
                'balance' => number_format($balance, 2, '.', ''),
                'balance_type' => $item['balance_type'],
                'pay_amount' => ($item['balance_type'] == 'add' ? '+' : '-') . $item['pay_amount'],
                'pay_category' => $payCategory,
                'pay_addtimes' => $item['pay_addtimes']
            ];
        }

        // 绑定记录
        $memberAccountLists = MemberAccountList::where('join_list_member_account_nbr', $accountNbr)
            ->where('member_account_list_attr', 'IN')
            ->select('member_account_list_amount', 'member_account_list_datetime', 'member_account_list_attr', 'join_list_member_account_nbr', 'member_account_list_addtimes')
            ->get()
            ->toArray();
        foreach ($memberAccountLists as $item) {
            $data[] = [
                'goods_category' => '--',
                'join_pay_order_id' => '--',
                'balance' => $item['member_account_list_amount'],
                'pay_amount' => '+' . $item['member_account_list_amount'],
                'pay_category' => '绑定',
                'pay_addtimes' => $item['member_account_list_addtimes'],
            ];
        }

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