<?php

namespace App\Http\Services;

use App\Lib\SmsCode as SmsCodeService;
use App\Models\AccountRecord;
use App\Models\Category;
use App\Models\Config;
use App\Models\DealRecord;
use App\Models\DealRecordGoods;
use App\Models\DealRecordUser;
use App\Models\FrontUserModel;
use App\Models\RechargeApply;
use App\Models\SmsCode;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Illuminate\Support\Facades\DB;

class AccountService extends BaseService
{
    protected $userIDCardPattern = '/^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/';

    public function getAccountOpenInfoHandle() {
        $result = [
            'res' => true,
            'msg' => '获取成功',
            'data' => [
                'is_open' => 0,
            ],
        ];

        // 获取充值转账协议
        $protocolInfo = (new Config())->findDataWithField(['config_key' => 'account_is_open'], ['*']);
        $result['data']['is_open'] = $protocolInfo['config_value'] ?? 0;

        return $result;
    }

    public function getServiceOpenInfoHandle() {
        $result = [
            'res' => true,
            'msg' => '获取成功',
            'data' => [
                'is_open' => 0,
            ],
        ];

        // 获取充值转账协议
        $serviceInfo = (new Config())->findDataWithField(['config_key' => 'service_is_open'], ['*']);
        $result['data']['is_open'] = $serviceInfo['config_value'] ?? 0;

        return $result;
    }

    public function updateServiceOpenStatusHandle($isOpen) {
        $result = [
            'res' => false,
            'msg' => '客服开启',
            'data' => [],
        ];

        $isOpen = intval($isOpen);
        if ($isOpen !== 0 && $isOpen !== 1) {
            $result['msg'] = '不支持的操作';
            return $result;
        }

        if ($isOpen === 0) {
            $result['msg'] = '客服关闭';
        }

        // 更新
        $updateRes = (new Config())->updateData(['config_key' => 'service_is_open'], ['config_value' => $isOpen]);
        if (false === $updateRes) {
            $result['msg'] = '操作失败';
            return $result;
        }

        $result['res'] = true;
        return $result;
    }

    public function updateOrderServiceOpenStatusHandle($isOpen) {
        $result = [
            'res' => false,
            'msg' => '订单开启',
            'data' => [],
        ];

        $isOpen = intval($isOpen);
        if ($isOpen !== 0 && $isOpen !== 1) {
            $result['msg'] = '不支持的操作';
            return $result;
        }

        if ($isOpen === 0) {
            $result['msg'] = '订单关闭';
        }

        // 更新
        $updateRes = (new Config())->updateData(['config_key' => 'order_is_open'], ['config_value' => $isOpen]);
        if (false === $updateRes) {
            $result['msg'] = '操作失败';
            return $result;
        }

        $result['res'] = true;
        return $result;
    }

    public function getAccountInfoHandle($userInfo) {
        $result = [
            'res' => true,
            'msg' => '获取成功',
            'data' => [
                'account_money' => floatval($userInfo['account_money'] ?? 0),
                'is_allow_apply' => 1,
                'status' => 0,
                'check_remark' => '',
            ],
        ];

        // 获取充值转账协议
        $protocolInfo = (new Config())->findDataWithField(['config_key' => 'account_protocol'], ['*']);
        $result['data']['account_protocol'] = $protocolInfo['config_value'] ?? '';

        $rechargeApplyModel = new RechargeApply();
        $rechargeApplyInfo = $rechargeApplyModel->findDataWithField(['user_id' => $userInfo['id']], ['status', 'check_remark'], 'id', 'desc');
        if (!empty($rechargeApplyInfo)) {
            if ($rechargeApplyInfo['status'] == 1) {
                $result['data']['is_allow_apply'] = 0;
            }
            $result['data']['status'] = $rechargeApplyInfo['status'];
            $result['data']['check_remark'] = ($rechargeApplyInfo['status'] == 2) ? $rechargeApplyInfo['check_remark'] : '';
        }

        return $result;
    }

    public function applyRechargeHandle($userInfo, $applyInfo) {
        $result = [
            'res' => false,
            'msg' => '申请成功',
            'data' => [],
        ];

        // 姓名
        if (!isset($applyInfo['user_name']) || mb_strlen($applyInfo['user_name']) == 0 || mb_strlen($applyInfo['user_name']) > 16) {
            $result['msg'] = '姓名异常';
            return $result;
        }

        // 报班电话
        if (!isset($applyInfo['phone']) || !checkPhone($applyInfo['phone'])) {
            $result['msg'] = '报班电话异常';
            return $result;
        }

        // 报班身份证号
        if (!isset($applyInfo['id_card']) || !preg_match($this->userIDCardPattern, $applyInfo['id_card'])) {
            $result['msg'] = '身份证号异常';
            return $result;
        }

        // 充值金额
        if (!isset($applyInfo['money']) || !is_numeric($applyInfo['money']) || $applyInfo['money'] <= 0 || $applyInfo['money'] > 999999) {
            $result['msg'] = '充值金额异常';
            return $result;
        }

        if (!checkPhone($userInfo['phone'])) {
            $result['msg'] = '充值账号异常';
            return $result;
        }

        // 特殊说明
        if (isset($applyInfo['remark']) && mb_strlen($applyInfo['remark']) > 256) {
            $result['msg'] = '特殊说明异常';
            return $result;
        }

        // 协议地址
        if (!isset($applyInfo['protocol_url']) || mb_strlen($applyInfo['protocol_url']) > 256) {
            $result['msg'] = '协议异常';
            return $result;
        }

        DB::beginTransaction();

//        // 申请仍在审核中,不允许再次申请
//
//        $rechargeApplyInfo = $rechargeApplyModel->selectDataByWhereFieldAndIds(['user_id' => $userInfo['id']], 'status', [1], ['id']);
//        if (!empty($rechargeApplyInfo)) {
//            $result['msg'] = '申请仍在审核中,不允许再次申请';
//            return $result;
//        }

        // 获取最近一次的申请
        $rechargeApplyModel = new RechargeApply();
        $latestApplyInfo = $rechargeApplyModel->findDataWithField(['user_id' => $userInfo['id']], ['*'], 'id', 'DESC');
        // 如果没有最近一次的申请, 直接写入
        // 如果是申请通过的, 直接写入
        if (empty($latestApplyInfo) || $latestApplyInfo['status'] == 3) {
            $insertRecharge = [
                'user_id' => $userInfo['id'],
                'name' => $applyInfo['user_name'],
                'phone' => $applyInfo['phone'],
                'id_card' => $applyInfo['id_card'],
                'money' => round($applyInfo['money'], 2),
                'remark' => $applyInfo['remark'] ?? '',
                'user_protocol' => $applyInfo['protocol_url'] ?? '',
            ];
            $insertRes = $rechargeApplyModel->insertData($insertRecharge);
            if (false === $insertRes) {
                DB::rollBack();
                $result['msg'] = '申请失败';
                return $result;
            }
        } else if ($latestApplyInfo['status'] == 1) {// 如果是申请中, 不允许申请
            DB::rollBack();
            $result['msg'] = '申请仍在审核中,不允许再次申请';
            return $result;
        } else if ($latestApplyInfo['status'] == 2) {// 如果是驳回的申请, 更新申请
            $updateData = [
                'name' => $applyInfo['user_name'],
                'phone' => $applyInfo['phone'],
                'id_card' => $applyInfo['id_card'],
                'money' => round($applyInfo['money'], 2),
                'remark' => $applyInfo['remark'] ?? '',
                'status' => 1,// 状态更新为申请中
                'user_protocol' => $applyInfo['protocol_url'] ?? '',
            ];
            $updateRes = $rechargeApplyModel->updateData(['id' => $latestApplyInfo['id']], $updateData);
            if (false === $updateRes) {
                DB::rollBack();
                $result['msg'] = '申请失败';
                return $result;
            }
        }

        DB::commit();
        $result['res'] = true;
        return $result;
    }

    public function checkAccountListSearchHandle($searchParam) {
        $result = [
            'res' => true,
            'msg' => '校验成功',
            'data' => [],
        ];

        if ($searchParam['status'] !== '' && is_numeric($searchParam['status']) && $searchParam['status'] >= 1 && $searchParam['status'] <= 3) {
            $result['data']['status'] = intval($searchParam['status']);
        }

        if ($searchParam['is_recharge'] !== '' && is_numeric($searchParam['is_recharge']) && ($searchParam['is_recharge'] == 0 || $searchParam['is_recharge'] == 1)) {
            $result['data']['is_recharge'] = intval($searchParam['is_recharge']);
        }

        if ($searchParam['class_phone'] !== '') {
            $result['data']['class_phone'] = mb_substr($searchParam['class_phone'], 0, 16);
        }

        if ($searchParam['user_phone'] !== '') {
            $result['data']['user_phone'] = mb_substr($searchParam['user_phone'], 0, 16);
        }

        $result['data']['page'] = intval($searchParam['page'] ?? 1);
        if ($result['data']['page'] <= 0) {
            $result['data']['page'] = 1;
        }

        $result['data']['page_size'] = intval($searchParam['page_size'] ?? 20);
        if ($result['data']['page_size'] <= 0 || $result['data']['page_size'] > 100) {
            $result['data']['page_size'] = 20;
        }

        return $result;
    }

    public function getAccountListHandle($userInfo, $searchParam) {
        $result = [
            'res' => true,
            'msg' => '获取成功',
            'data' => [
                'page' => $searchParam['page'],
                'page_size' => $searchParam['page_size'],
                'total' => 0,
                'list' => [],
            ],
        ];

        $frontUserModel = new FrontUserModel();

        $where = [];
        if (isset($searchParam['status'])) {
            $where['status'] = $searchParam['status'];
        }
        if (isset($searchParam['is_recharge'])) {
            $where['is_recharge'] = $searchParam['is_recharge'];
        }
        if (isset($searchParam['class_phone'])) {
            $where['phone'] = $searchParam['class_phone'];
        }
        if (isset($searchParam['user_phone'])) {
            // 获取学员电话对应的学员id
            if (checkPhone($searchParam['user_phone'])) {
                $frontUserInfo = $frontUserModel->findDataWithField(['phone' => $searchParam['user_phone']], ['id']);
                if (empty($frontUserInfo)) {
                    return $result;
                }

                $where['user_id'] = $frontUserInfo['id'];
            } else {
                return $result;
            }
        }

        $rechargeApplyModel = new RechargeApply();
        $applyList = $rechargeApplyModel->selectDataWithPage($where, ['id', 'user_id', 'name', 'phone as class_phone', 'id_card', 'money', 'remark', 'status', 'check_remark', 'user_protocol', 'is_recharge', 'recharge_money'], $searchParam['page_size'], 'id', 'desc');

        // 获取所有的用户id, 去获取
        $allUserIds = array_filter(array_unique(array_column($applyList['data'], 'user_id')));
        $userIdRelatedInfo = [];
        if (!empty($allUserIds)) {
            $frontUsers = $frontUserModel->selectDataByIds($allUserIds, ['id', 'phone', 'account_money']);
            $userIdRelatedInfo = array_column($frontUsers, null, 'id');
        }

        foreach ($applyList['data'] as $index => $value) {
            $applyList['data'][$index]['user_phone'] = $userIdRelatedInfo[$value['user_id']]['phone'] ?? '';
            $applyList['data'][$index]['account_money'] = $userIdRelatedInfo[$value['user_id']]['account_money'] ?? 0;
        }

        $result['data']['page'] = $searchParam['page'];
        $result['data']['page_size'] = $searchParam['page_size'];
        $result['data']['total'] = $applyList['total'];
        $result['data']['list'] = $applyList['data'];
        return $result;
    }

    public function applyCheckHandle($userInfo, $checkInfo) {
        $result = [
            'res' => false,
            'msg' => '操作成功',
            'data' => [],
        ];

        if (!isset($checkInfo['apply_id']) || !is_numeric($checkInfo['apply_id']) || $checkInfo['apply_id'] <= 0) {
            $result['msg'] = 'apply_id异常';
            return $result;
        }
        $checkInfo['apply_id'] = intval($checkInfo['apply_id']);

        if (!isset($checkInfo['status']) || !is_numeric($checkInfo['status']) || ($checkInfo['status'] != 0 && $checkInfo['status'] != 1)) {
            $result['msg'] = 'status异常';
            return $result;
        }
        $checkInfo['status'] = intval($checkInfo['status']);

        // 审核不通过, 校验审核不通过的原因
        if ($checkInfo['status'] == 0) {
            if (!isset($checkInfo['check_remark']) || mb_strlen($checkInfo['check_remark']) == 0 || mb_strlen($checkInfo['check_remark']) > 128) {
                $result['msg'] = '驳回原因异常';
                return $result;
            }
        }

        // 校验申请是否存在
        $rechargeApplyModelModel = new RechargeApply();
        $existedApplyInfo = $rechargeApplyModelModel->findDataWithField(['id' => $checkInfo['apply_id']], ['id']);
        if (empty($existedApplyInfo)) {
            $result['msg'] = '申请不存在';
            return $result;
        }

        $updateData = [
            'status' => ($checkInfo['status'] == 0) ? 2 : 3,
            'check_remark' => ($checkInfo['status'] == 0) ? $checkInfo['check_remark'] : '',
        ];

        $updateApplyRes = $rechargeApplyModelModel->updateData(['id' => $checkInfo['apply_id']], $updateData);
        if (false === $updateApplyRes) {
            $result['msg'] = '操作失败';
            return $result;
        }

        $result['res'] = true;
        return $result;
    }

    public function accountRechargeHandle($handleUserInfo, $rechargeInfo) {
        $result = [
            'res' => false,
            'msg' => '操作成功',
            'data' => [],
        ];

        if (!isset($rechargeInfo['apply_id']) || !is_numeric($rechargeInfo['apply_id']) || $rechargeInfo['apply_id'] <= 0) {
            $result['msg'] = 'apply_id异常';
            return $result;
        }
        $rechargeInfo['apply_id'] = intval($rechargeInfo['apply_id']);

        if (!isset($rechargeInfo['money']) || !is_numeric($rechargeInfo['money']) || $rechargeInfo['money'] <= 0 || $rechargeInfo['money'] > 999999.99) {
            $result['msg'] = '充值金额异常';
            return $result;
        }
        $rechargeInfo['money'] = round($rechargeInfo['money'], 2);

        DB::beginTransaction();

        // 校验申请是否存在
        $rechargeApplyModelModel = new RechargeApply();
        $existedApplyInfo = $rechargeApplyModelModel->findDataWithField(['id' => $rechargeInfo['apply_id']], ['id', 'user_id', 'status', 'recharge_money']);
        if (empty($existedApplyInfo)) {
            DB::rollBack();
            $result['msg'] = '申请不存在';
            return $result;
        }
        if ($existedApplyInfo['status'] != 3) {
            DB::rollBack();
            $result['msg'] = '还未审核通过,不允许充值';
            return $result;
        }

        // 获取用户信息
        $userFrontModel = new FrontUserModel();
        $frontUserInfo = $userFrontModel->findDataWithField(['id' => $existedApplyInfo['user_id']]);
        if (empty($frontUserInfo)) {
            DB::rollBack();
            $result['msg'] = '学员信息不存在';
            return $result;
        }

        // 充值涉及的表
        // 1: 申请记录里的累计充值金额更新
        $updateRechargeApplyData = [
            'is_recharge' => 1,
            'recharge_money' => $existedApplyInfo['recharge_money'] + $rechargeInfo['money'],
        ];
        $updateRechargeApplyRes = $rechargeApplyModelModel->updateData(['id' => $rechargeInfo['apply_id']], $updateRechargeApplyData);
        if (false === $updateRechargeApplyRes) {
            DB::rollBack();
            $result['msg'] = '充值失败';
            return $result;
        }

        // 2: 用户的余额更新
        $updateUserInfo = [
            'account_money' => $frontUserInfo['account_money'] + $rechargeInfo['money'],
        ];
        $updateUserInfoRes = $userFrontModel->updateData(['id' => $existedApplyInfo['user_id']], $updateUserInfo);
        if (false === $updateUserInfoRes) {
            DB::rollBack();
            $result['msg'] = '充值失败';
            return $result;
        }

        // 3: 余额变更记录表
        $accountRecordModel = new AccountRecord();
        $insertAccountRecord = [
            'user_id' => $existedApplyInfo['user_id'],
            'apply_id' => $rechargeInfo['apply_id'],
            'type' => 1,
            'money' => $rechargeInfo['money'],
            'created_by' => $handleUserInfo['id'],
        ];
        $insertAccountRecordRes = $accountRecordModel->insertData($insertAccountRecord);
        if (false === $insertAccountRecordRes) {
            DB::rollBack();
            $result['msg'] = '操作失败';
            return $result;
        }

        DB::commit();
        $result['res'] = true;
        return $result;
    }

    public function getAccountRecordHandle($platform, $userInfo, $applyId) {
        $result = [
            'res' => false,
            'msg' => '获取成功',
            'data' => [],
        ];

        $userId = 0;
        if ($platform == 'web') {
            $rechargeApplyModel = new RechargeApply();
            $rechargeApplyInfo = $rechargeApplyModel->findDataWithField(['id' => $applyId], ['user_id']);
            if (empty($rechargeApplyInfo)) {
                $result['msg'] = '申请不存在';
                return $result;
            }

            // 获取用户信息
            $userFrontModel = new FrontUserModel();
            $frontUserInfo = $userFrontModel->findDataWithField(['id' => $rechargeApplyInfo['user_id']]);
            if (empty($frontUserInfo)) {
                $result['msg'] = '学员信息不存在';
                return $result;
            }

            $userId = $rechargeApplyInfo['user_id'];
        } else if ($platform == 'applet') {
            $userId = $userInfo['id'];
        }

        // 获取学员的转账记录
        $accountRecordModel = new AccountRecord();
        $accountRecordList = $accountRecordModel->selectDataWithField(['user_id' => $userId], ['type', 'money', 'transfer_from', 'transfer_to', 'created_at'], 'id', 'ASC');
        $returnList = [];
        foreach ($accountRecordList as $record) {
            // 账户余额变动类型, 1: 充值, 2: 消费, 3: 撤回订单, 4: 驳回订单, 5: 转账转入, 6: 转账转出
            switch ($record['type']) {
                case 1:
                    $returnList[] = $record['created_at'] . ' 充值' . $record['money'] . '元';
                    break;
                case 2:
                    $returnList[] = $record['created_at'] . ' 消费' . $record['money'] . '元';
                    break;
                case 3:
                    $returnList[] = $record['created_at'] . ' 撤回订单返回' . $record['money'] . '元';
                    break;
                case 4:
                    $returnList[] = $record['created_at'] . ' 驳回订单返回' . $record['money'] . '元';
                    break;
                case 5:
                    $returnList[] = $record['created_at'] . ' 账户 ' . $record['transfer_from'] . ' 转入' . $record['money'] . '元';
                    break;
                case 6:
                    $returnList[] = $record['created_at'] . ' 转出到 ' . $record['transfer_to'] . ' 账户' . $record['money'] . '元';
                    break;
                default:
                    break;
            }
        }

        $result['res'] = true;
        $result['data']['list'] = $returnList;
        return $result;
    }

    public function smsCodeSendHandle($userInfo) {
        $result = [
            'res' => false,
            'msg' => '发送成功',
            'data' => [],
        ];

        $smsCode = new SmsCode();
        // 获取当前手机号过去一小时内已获取的验证码数量(数量统计暂不区分平台)
        $codeCount = $smsCode->getCountByWhere(['phone' => $userInfo['phone'], ['created_at', '>=', date('Y-m-d H:i:s', time() - 3600)], 'deleted_at' => null]);
        if ($codeCount > 4) {
            $result['msg'] = '发送验证码已达上限,请稍后再试';
            return $result;
        }

        $randCode = mt_rand(100000, 999999);

        $content = '验证码: ' . $randCode . '，仅用于中公易课，5分钟内有效，工作人员不会向您索要，请勿向任何人泄露。';
        $sendRes = (new SmsCodeService())->sendSms($userInfo['phone'], $content);
        if (empty($sendRes['res'])) {
            $result['msg'] = $sendRes['msg'] ?? '发送失败';
            return $result;
        }

        // 写入数据库
        $insertData = [
            'phone' => $userInfo['phone'],
            'code' => $randCode,
            'request_id' => $sendRes['data']['msgid'] ?? '',
        ];
        $insertRes = $smsCode->insertData($insertData);
        if (false === $insertRes) {
            $result['msg'] = '发送验证码已达上限,请稍后再试';
            return $result;
        }

        $result['res'] = true;
        return $result;
    }

    public function accountTransferHandle($userInfo, $transferInfo) {
        $result = [
            'res' => false,
            'msg' => '操作成功',
            'data' => [],
        ];

        if (!checkPhone($userInfo['phone'])) {
            $result['msg'] = '转出账号异常';
            return $result;
        }

        if (!preg_match('/^\d{6}$/', $transferInfo['code'] ?? '')) {
            $result['msg'] = '验证码不正确';
            return $result;
        }

        if (!isset($transferInfo['transfer_to']) || !checkPhone($transferInfo['transfer_to'])) {
            $result['msg'] = '转入账号异常';
            return $result;
        }

        if (!isset($transferInfo['repeat_transfer_to']) || !checkPhone($transferInfo['repeat_transfer_to'])) {
            $result['msg'] = '账号确认异常';
            return $result;
        }

        if ($transferInfo['transfer_to'] != $transferInfo['repeat_transfer_to']) {
            $result['msg'] = '两次输入的账号不一致';
            return $result;
        }

        if ($userInfo['phone'] == $transferInfo['transfer_to']) {
            $result['msg'] = '转入转出账号不能相同';
            return $result;
        }

        if (!isset($transferInfo['transfer_money']) || !is_numeric($transferInfo['transfer_money']) || $transferInfo['transfer_money'] <= 0 || $transferInfo['transfer_money'] > 999999.99) {
            $result['msg'] = '转账金额异常';
            return $result;
        }
        $transferInfo['transfer_money'] = round($transferInfo['transfer_money'], 2);

        if ($userInfo['account_money'] < $transferInfo['transfer_money']) {
            $result['msg'] = '转账金额不足';
            return $result;
        }

        DB::beginTransaction();

        // 校验验证码
        $smsCode = new SmsCode();
        $smsCodeInfo = $smsCode->findDataWithField(['phone' => $userInfo['phone']], ['id', 'code', 'is_check', 'created_at'], 'id', 'DESC');
        if (empty($smsCodeInfo) || $smsCodeInfo['is_check'] == 1 || (time() - strtotime($smsCodeInfo['created_at']) > 300)) {
            DB::rollBack();
            $result['msg'] = '验证码不存在或已失效,请重新获取';
            return $result;
        }

        if ($smsCodeInfo['code'] != $transferInfo['code']) {
            DB::rollBack();
            $result['msg'] = '验证码不正确,请重新获取';
            return $result;
        }

        // 至此短信验证码校验通过, 不论下面是否登录成功, 都将验证码置为已校验
        $updateCodeRes = $smsCode->updateData(['id' => $smsCodeInfo['id']], ['is_check' => 1]);
        if (false === $updateCodeRes) {
            DB::rollBack();
            $result['msg'] = '验证码异常,请重新获取';
            return $result;
        }

        // 校验转入账号是否存在
        $userFrontModel = new FrontUserModel();
        $transferToUserInfo = $userFrontModel->findDataWithField(['phone' => $transferInfo['repeat_transfer_to']]);
        if (empty($transferToUserInfo)) {
            DB::rollBack();
            $result['msg'] = '转入账号不存在';
            return $result;
        }

        // 转账涉及的表
        // 1: 转出账号的余额更新
        $updateCurrentUserInfo = [
            'account_money' => $userInfo['account_money'] - $transferInfo['transfer_money'],
        ];
        $updateCurrentUserInfoRes = $userFrontModel->updateData(['id' => $userInfo['id']], $updateCurrentUserInfo);
        if (false === $updateCurrentUserInfoRes) {
            DB::rollBack();
            $result['msg'] = '转账失败';
            return $result;
        }

        // 2: 转出账号的余额变更记录表
        $accountRecordModel = new AccountRecord();
        $insertCurrentAccountRecord = [
            'user_id' => $userInfo['id'],
            'type' => 6,
            'money' => $transferInfo['transfer_money'],
            'transfer_from' => $userInfo['phone'],
            'transfer_to' => $transferInfo['transfer_to'],
            'created_by' => $userInfo['id'],
        ];
        $insertCurrentAccountRecordRes = $accountRecordModel->insertData($insertCurrentAccountRecord);
        if (false === $insertCurrentAccountRecordRes) {
            DB::rollBack();
            $result['msg'] = '转账失败';
            return $result;
        }

        // 3: 转入账号的余额更新
        $updateTransferToUserInfo = [
            'account_money' => $transferToUserInfo['account_money'] + $transferInfo['transfer_money'],
        ];
        $updateUserInfoRes = $userFrontModel->updateData(['id' => $transferToUserInfo['id']], $updateTransferToUserInfo);
        if (false === $updateUserInfoRes) {
            DB::rollBack();
            $result['msg'] = '转账失败';
            return $result;
        }

        // 4: 转入账号的余额变更记录表
        $insertTransferToAccountRecord = [
            'user_id' => $transferToUserInfo['id'],
            'type' => 5,
            'money' => $transferInfo['transfer_money'],
            'transfer_from' => $userInfo['phone'],
            'transfer_to' => $transferInfo['transfer_to'],
            'created_by' => $userInfo['id'],
        ];
        $insertTransferToAccountRecordRes = $accountRecordModel->insertData($insertTransferToAccountRecord);
        if (false === $insertTransferToAccountRecordRes) {
            DB::rollBack();
            $result['msg'] = '转账失败';
            return $result;
        }

        DB::commit();
        $result['res'] = true;
        return $result;
    }

    public function dealRecordAccountCheckHandle($searchParam) {
        $result = [
            'res' => false,
            'msg' => '获取成功',
            'data' => [
                'list' => [],
                '总差额' => 0,
            ],
        ];

        if ($searchParam['date_start'] == '' || $searchParam['date_end'] == '') {
            $result['msg'] = '请填写开始和结束日期';
            return $result;
        }

        $startTimestamp = strtotime($searchParam['date_start']);
        $endTimestamp = strtotime($searchParam['date_end']);
        if (false === $startTimestamp || false === $endTimestamp || $startTimestamp > $endTimestamp) {
            $result['msg'] = '开始和结束日期不合法';
            return $result;
        }

        $dealRecordWhere = [];
        $dealRecordWhere[] = ['deal_date', '>=', $searchParam['date_start']];
        $dealRecordWhere[] = ['deal_date', '<', date('Y-m-d', strtotime($searchParam['date_end']) + 86400)];

        if ($searchParam['reception_name'] == '') {
            $result['msg'] = '请填写接待人姓名';
            return $result;
        }
        $dealRecordWhere[] = ['reception_name', 'like', '%' . $searchParam['reception_name'] . '%'];

        $dealRecordModel = new DealRecord();
        $dealRecordGoodsModel = new DealRecordGoods();

        // 获取交易记录
        // 必须是有效的
        $dealRecordWhere['status'] = 1;
        // 必须待审核+审核通过的, 驳回的不算
        $checkStatus = [1, 2];
        $dealRecordList = $dealRecordModel->selectDataByWhereFieldAndIds($dealRecordWhere, 'check_status', $checkStatus, ['*']);

        // 拿到所有的交易记录对应的抵扣信息
        $allDealRecordIds = array_column($dealRecordList, 'id');
        if (!empty($allDealRecordIds)) {
            $dealRecordGoodsList = $dealRecordGoodsModel->selectDataByWhereFieldAndIds([], 'deal_record_id', $allDealRecordIds, ['*']);
            $realRecordIdRelatedGoodsInfo = [];
            foreach ($dealRecordGoodsList as $info) {
                if (!isset($realRecordIdRelatedGoodsInfo[$info['deal_record_id']])) {
                    $realRecordIdRelatedGoodsInfo[$info['deal_record_id']] = [];
                }

                $realRecordIdRelatedGoodsInfo[$info['deal_record_id']][] = $info;
            }

            foreach ($dealRecordList as $dealRecordInfo) {
                $currentDealRecordGoodsList = $realRecordIdRelatedGoodsInfo[$dealRecordInfo['id']] ?? [];
                $goodsDeductionMoney = array_sum(array_column($currentDealRecordGoodsList, 'deduction_money'));

                // 差额
                $diffMoney = $dealRecordInfo['deduction_money'] - $goodsDeductionMoney;
                $result['data']['总差额'] += $diffMoney;

                if ($diffMoney != 0) {
                    $result['data']['list'][] = sprintf("抵扣日期: %s, 学员姓名: %s, 报班电话: %s, 抵扣总金额: %s, 商品抵扣金额之和: %s, 差额: %s元", $dealRecordInfo['deal_date'], $dealRecordInfo['user_name'], $dealRecordInfo['class_phone'], $dealRecordInfo['deduction_money'], $goodsDeductionMoney, $diffMoney);
                }
            }
        }

        $result['data']['总差额'] = round($result['data']['总差额'], 2);

        $result['res'] = true;
        return $result;
    }

    public function getExpressListHandle($userInfo, $searchParam)
    {
        $result = [
            'res' => false,
            'msg' => '获取成功',
            'data' => [
                'list' => [],
            ],
        ];

        if (!checkPhone($searchParam['class_phone'])) {
            $result['msg'] = '请填写正确的手机号';
            return $result;
        }

        $dealRecordWhere = [];
        $dealRecordWhere['status'] = 1;
        $dealRecordWhere['check_status'] = 2;
        $dealRecordWhere['deleted_at'] = null;
        $dealRecordWhere[] = ['class_phone', 'like', '%' . $searchParam['class_phone'] . '%'];
        $dealRecordList = (new DealRecord())->selectDataWithField($dealRecordWhere, ['id']);
        if (empty(!$dealRecordList)) {
            $dealRecordIds = array_column($dealRecordList, 'id');
            $dealRecordGoodsWhere = [];
            $dealRecordGoodsWhere[] = ['deliver_status', '<>', 2];
            $result['data']['list'] = (new DealRecordGoods())->selectDataByWhereFieldAndIds($dealRecordGoodsWhere, 'deal_record_id', $dealRecordIds, ['goods_name', 'deliver_status', 'express_no']);
        }

        $result['res'] = true;
        return $result;
    }

    public function getDSChatCompletionsHandle($userInfo, $textInfo) {
        $result = [
            'res' => true,
            'msg' => '成功',
            'data' => null,
        ];

        (new DeepSeekService())->chatCompletionsByAlphaChain($textInfo);
    }

}
