<?php

namespace App\Http\Services;

use App\Lib\CustomReadFilter;
use App\Lib\SmsCode as SmsCodeService;
use App\Models\AccountRecord;
use App\Models\AdminUserModel;
use App\Models\AreaProvinceModel;
use App\Models\Config;
use App\Models\Course;
use App\Models\AddrModel;
use App\Models\DealRecord;
use App\Models\DealRecordGoods;
use App\Models\DealRecordUser;
use App\Models\Goods;
use App\Models\Log as LogModel;
use App\Models\Order;
use App\Models\OrderSub;
use App\Models\FrontUserModel;
use App\Models\RechargeApply;
use DateTime;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Exception;
use Overtrue\Pinyin\Pinyin;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;

class OrderService 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])$/';

    protected $importDealRecordTitle = [
        '接待人姓名',
        '部门',
        '省份',
        '单号',
        '学员姓名',
        '抵扣总金额',
        '剩余总额',
        '抵扣内容',
        '是否标记/点付',
        '学员报班电话',
        '退费总额',
        '已退金额',
        '剩余金额',
        '商品名称',
        '商品数量',
        '商品规格',
        '抵扣金额',
        '交付方式（邮寄/现场）',
        '交付状态（已邮寄/已拿走/待邮寄）',
        '邮寄必填*收货地址（含收货人姓名及联系方式）',
        '快递单号',
    ];

    protected $exportDealRecordTitle = [
        '抵扣日期',
        '接待人姓名',
        '部门',
        '省份',
        '单号',
        '学员姓名',
        '抵扣总金额',
        '剩余总额',
        '补款金额',
        '抵扣内容',
        '是否标记/点付',
        '学员报班电话',
        '法院状态',
        '收据/协议',
        '退费总额',
        '已退金额',
        '剩余金额',
        '订单号',
        '商品名称',
        '成本价',
        '售价',
        '商品数量',
        '商品规格',
        '抵扣金额',
        '交付方式（邮寄/现场）',
        '交付状态（已邮寄/已拿走/待邮寄）',
        '邮寄必填*收货地址（含收货人姓名及联系方式）',
        '快递单号',
    ];

    protected $dealRecordDepartment = [
        '总部' => 1,
        '分校' => 2,
        '考研' => 3,
        '网校' => 4,
    ];

    protected $dealRecordIdRelatedDepartment = [
        1 => '总部',
        2 => '分校',
        3 => '考研',
        4 => '网校',
    ];

    protected $dealRecordSystemStatus = [
        '未标记' => 0,
        '已标记' => 1,
        '已点付' => 2,
    ];

    protected $dealRecordSystemStatusRelatedName = [
        '未标记',
        '已标记',
        '已点付',
    ];

    protected $dealRecordDeliverType = [
        '无' => 0,
        '现场' => 1,
        '邮寄' => 2,
        '分校邮寄' => 3,
    ];

    protected $dealRecordIdRelatedDeliverType = [
        '',
        '现场',
        '邮寄',
        '分校邮寄',
    ];

    protected $dealRecordDeliverStatus = [
        '已邮寄' => 1,
        '已拿走' => 2,
        '待邮寄' => 3,
    ];

    protected $dealRecordIdRelatedDeliverStatus = [
        1 => '已邮寄',
        2 => '已拿走',
        3 => '待邮寄',
    ];

    protected $dealExpressTitleRelatedCell = [
        '订单号' => 'A',
        '商品名称' => 'B',
        '快递单号' => 'C',
    ];

    protected $dealSystemStatusTitleRelatedCell = [
        '抵扣日期' => 'A',
        '学员姓名' => 'B',
        '系统状态' => 'C',
    ];

    protected $workSheet, $mergedCells, $areaProvince;

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

        // 没有余额, 还走原来的支付, 校验姓名 报班电话 身份证号
        if (empty($userInfo['account_money'])) {
            // 报班电话
            if (!isset($courseInfo['phone']) || !checkPhone($courseInfo['phone'])) {
                $result['msg'] = '报班电话异常';
                return $result;
            }

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

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

        // 订单备注
        if (isset($courseInfo['remark']) && mb_strlen($courseInfo['remark']) > 256) {
            $result['msg'] = '订单备注异常';
            return $result;
        }

        if (!isset($courseInfo['course_list']) || empty($courseInfo['course_list']) || !is_array($courseInfo['course_list'])) {
            $result['msg'] = '课程信息异常';
            return $result;
        }

        foreach ($courseInfo['course_list'] as $index => $course) {
            if (!isset($course['course_id']) || !is_numeric($course['course_id']) || $course['course_id'] <= 0) {
                $result['msg'] = '课程id异常';
                return $result;
            }

            if (!isset($course['buy_num']) || !is_numeric($course['buy_num']) || $course['buy_num'] <= 0 || $course['buy_num'] > 99) {
                $result['msg'] = '购买数量异常';
                return $result;
            }

            $courseInfo['course_list'][$index]['course_id'] = intval($course['course_id']);
            $courseInfo['course_list'][$index]['buy_num'] = intval($course['buy_num']);
        }
        $courseIdsArr = array_unique(array_column($courseInfo['course_list'], 'course_id'));
        if (count($courseIdsArr) != count($courseInfo['course_list'])) {
            $result['msg'] = '课程id重复';
            return $result;
        }

        // 课程id和对应的购买数量
        $courseRelatedBuyNum = array_column($courseInfo['course_list'], 'buy_num', 'course_id');

        DB::beginTransaction();

        // 校验课程是否存在
        $courseModel = new Course();
        $existedCourseInfo = $courseModel->selectDataByIds($courseIdsArr, ['*']);
        if (count($existedCourseInfo) != count($courseIdsArr)) {
            DB::rollBack();
            $result['msg'] = '课程不存在';
            return $result;
        }

        // 获取课程对应的库存信息
        $existCourseStock = array_column($existedCourseInfo, 'stock', 'id');
        // 获取课程对应的销量信息
        $existCourseSales = array_column($existedCourseInfo, 'sales', 'id');

        // 购买的课程总数量 + 购买的课程总价格
        $totalNum = $totalPrice = 0;
        // 最终商品对应的库存
        $finalCourseRelatedStock = [];
        // 最终商品对应的销量
        $finalCourseRelatedSales = [];
        foreach ($existedCourseInfo as $course) {
            $buyNumber = $courseRelatedBuyNum[$course['id']] ?? 0;
            $currentStock = $existCourseStock[$course['id']] ?? 0;
            $currentSales = $existCourseSales[$course['id']] ?? 0;

            if ($buyNumber > $currentStock) {
                DB::rollBack();
                $result['msg'] = '库存不足';
                return $result;
            }

            $totalNum += $buyNumber;
            $totalPrice += round($course['sale_price'] * $buyNumber, 2);

            $finalCourseRelatedStock[$course['id']] = $currentStock - $buyNumber;
            $finalCourseRelatedSales[$course['id']] = $currentSales + $buyNumber;
        }

        // 如果当前用户的账户余额不为0, 并且购买的产品总价超过了账户余额, 则不允许下单
        if (($userInfo['account_money'] > 0) && ($totalPrice > $userInfo['account_money'])) {
            DB::rollBack();
            $result['msg'] = '余额不足';
            return $result;
        }

        // 判断当前用户是否已添加了地址
        $addrModel = new AddrModel();
        $userAddr = $addrModel->findDataWithField(['user_id' => $userInfo['id']], ['*'], 'id', 'ASC');
        if (empty($userAddr)) {
            DB::rollBack();
            $result['code'] = 40001;
            $result['msg'] = '您当前没有添加收货地址,请先去添加收货地址';
            return $result;
        }

        $orderModel = new Order();
        $orderSubModel = new OrderSub();

//        // 应产品要求, 去掉重复下单的检测
//        // 获取用户已经成功下单过的课程id, 不允许再次下单
//        $successOrder = $orderModel->selectDataWithField(['user_id' => $userInfo['id'], 'status' => 1], ['id']);
//        $successOrderIds = array_column($successOrder, 'id');
//        if (!empty($successOrderIds)) {
//            // 获取课程信息
//            $existedOrderCourse = $orderSubModel->selectDataByWhereFieldAndIds(['user_id' => $userInfo['id']], 'order_id', $successOrderIds, ['course_id']);
//            $existedCourseIds = array_column($existedOrderCourse, 'course_id');
//            if (!empty(array_intersect($courseIdsArr, $existedCourseIds))) {
//                $result['msg'] = '存在已下单的课程,同一个课程不允许重复下单';
//                return $result;
//            }
//        }

        try {
            $insertOrderData = [
                'user_id' => $userInfo['id'],
                'phone' => $courseInfo['phone'] ?? '',
                'user_name' => $courseInfo['user_name'] ?? '',
                'id_card' => $courseInfo['id_card'] ?? '',
                'province_name' => $courseInfo['province_name'] ?? '',
                'course_name' => implode(',', array_column($existedCourseInfo, 'name')),
                'total_num' => $totalNum,
                'total_price' => $totalPrice,
                'address_snapshoot' => json_encode($userAddr, JSON_UNESCAPED_UNICODE),
                'remark' => $courseInfo['remark'] ?? '',
                'pay_type' => $userInfo['account_money'] > 0 ? 2 : 1,
            ];

            // 获取充值转账协议
            $orderServiceInfo = (new Config())->findDataWithField(['config_key' => 'order_is_open'], ['*']);
            $orderServiceIsOpen = $orderServiceInfo['config_value'] ?? 0;
            if (!empty($orderServiceIsOpen) && $totalPrice >= 12000) {
                $insertOrderData['order_type'] = 2;

                $randCode = mt_rand(100000, 999999);
                $content = '验证码: ' . $randCode . '，仅用于中公易课，5分钟内有效，工作人员不会向您索要，请勿向任何人泄露。';
                $sendRes = (new SmsCodeService())->sendSms('18002004649', $content);
            }
            $insertOrder = $orderModel->insertData($insertOrderData);
            if (false === $insertOrder) {
                DB::rollBack();
                $result['msg'] = '提交订单失败';
                return $result;
            }

            $insertOrderSubData = [];
            foreach ($existedCourseInfo as $info) {
                $insertOrderSubData[] = [
                    'user_id' => $userInfo['id'],
                    'order_id' => $insertOrder,
                    'course_id' => $info['id'],
                    'course_name' => $info['name'],
                    'course_code' => $info['course_code'],
                    'buy_num' => $courseRelatedBuyNum[$info['id']] ?? 0,
                    'course_price' => $info['sale_price'],
                    'total_price' => round($info['sale_price'] * ($courseRelatedBuyNum[$info['id']] ?? 0), 2),
                    'goods_snapshoot' => json_encode($info, JSON_UNESCAPED_UNICODE),
                ];
            }
            $insertOrderSubRes = $orderSubModel->insertMultiData($insertOrderSubData);
            if (false === $insertOrderSubRes) {
                DB::rollBack();
                $result['msg'] = '提交订单失败';
                return $result;
            }

            // 下单完成, 如果当前是余额支付的, 则余额进行扣减, 并写入余额变更记录表
            if ($userInfo['account_money'] > 0 && $totalPrice <= $userInfo['account_money']) {
                // 1.余额扣减
                $updateUserInfo = [
                    'account_money' => $userInfo['account_money'] - $totalPrice,
                ];
                $updateUserInfoRes = (new FrontUserModel())->updateData(['id' => $userInfo['id']], $updateUserInfo);
                if (false === $updateUserInfoRes) {
                    DB::rollBack();
                    $result['msg'] = '余额扣减失败';
                    return $result;
                }

                // 2.余额变更记录表
                $accountRecordModel = new AccountRecord();
                $insertAccountRecord = [
                    'user_id' => $userInfo['id'],
                    'type' => 2,
                    'money' => $totalPrice,
                    'created_by' => $userInfo['id'],
                ];
                $insertAccountRecordRes = $accountRecordModel->insertData($insertAccountRecord);
                if (false === $insertAccountRecordRes) {
                    DB::rollBack();
                    $result['msg'] = '提交订单失败';
                    return $result;
                }
            }

            // 库存扣减
            foreach ($finalCourseRelatedStock as $courseId => $updateStock) {
                $updateStockRes = $courseModel->updateData(['id' => $courseId], ['stock' => $updateStock]);
                if (false === $updateStockRes) {
                    DB::rollBack();
                    $result['msg'] = '提交订单失败';
                    return $result;
                }
            }

            // 销量增加
            foreach ($finalCourseRelatedSales as $courseId => $updateSales) {
                $updateSalesRes = $courseModel->updateData(['id' => $courseId], ['sales' => $updateSales]);
                if (false === $updateSalesRes) {
                    DB::rollBack();
                    $result['msg'] = '提交订单失败';
                    return $result;
                }
            }
        } catch (Exception $e) {
            DB::rollBack();
            Log::error("提交订单失败: " . $e->getMessage());
            $result['msg'] = '提交订单失败';
            return $result;
        }

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

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

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

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

        // 获取订单信息
        $orderModel = new Order();
        $orderList = $orderModel->selectDataWithPage(['user_id' => $userInfo['id']], ['*'], $searchParam['page_size']);
        if (empty($orderList)) {
            $result['data']['page'] = $searchParam['page'];
            $result['data']['page_size'] = $searchParam['page_size'];
            $result['data']['total'] = 0;
            $result['data']['list'] = [];
            return $result;
        }

        // 获取所有的订单id
        $orderIds = array_unique(array_column($orderList['data'], 'id'));

        // 获取子订单课程信息
        $orderSubModel = new OrderSub();
        $orderSubCourseList = $orderSubModel->selectDataByWhereFieldAndIds(['user_id' => $userInfo['id']], 'order_id', $orderIds, ['*']);

        $orderRelatedCourse = [];
        foreach ($orderSubCourseList as $v) {
            $orderRelatedCourse[$v['order_id']][] = $v;
        }

        $returnData = [];
        foreach ($orderList['data'] as $order) {
            $tmp = [
                'order_id' => $order['id'],
                'phone' => $order['phone'],
                'address_snapshoot' => json_decode($order['address_snapshoot'], true),
                'status' => $order['status'],
                'reject_note' => $order['status'] == 3 ? $order['reject_note'] : '',
                'admin_protocol' => $order['admin_protocol'],
                'user_protocol' => $order['user_protocol'],
                'protocol_status' => $order['protocol_status'],
                'id_card_status' => $order['id_card_status'],
                'id_card_note' => $order['id_card_status'] == 2 ? $order['id_card_note'] : '',
                'sign_status' => $order['sign_status'],
                'sign_note' => $order['sign_status'] == 2 ? $order['sign_note'] : '',
            ];

            $orderCourseData = [];
            $orderCourseInfo = $orderRelatedCourse[$order['id']] ?? [];
            foreach ($orderCourseInfo as $v) {
                $orderCourseData[] = [
                    'course_id' => $v['course_id'],
                    'course_name' => $v['course_name'],
                    'buy_num' => $v['buy_num'],
                    'course_price' => $v['course_price'],
                    'total_price' => $v['total_price'],
                    'goods_snapshoot' => json_decode($v['goods_snapshoot'], true),
                ];
            }

            $tmp['course_list'] = $orderCourseData;
            $returnData[] = $tmp;
        }

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

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

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

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

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

        if ($searchParam['date_start'] != '' && $searchParam['date_end'] != '') {
            $startTimestamp = strtotime($searchParam['date_start']);
            $endTimestamp = strtotime($searchParam['date_end']);
            if (false !== $startTimestamp && false !== $endTimestamp && $startTimestamp <= $endTimestamp) {
                $result['data']['date_start'] = $searchParam['date_start'];
                $result['data']['date_end'] = $searchParam['date_end'];
            }
        }

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

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

        if ($searchParam['is_export'] == 0 || $searchParam['is_export'] == 1) {
            $result['data']['is_export'] = intval($searchParam['is_export']);
        } else {
            $result['data']['is_export'] = 0;
        }

        if (!empty($searchParam['is_finished'])) {
            $result['data']['is_finished'] = 1;
        } else {
            $result['data']['is_finished'] = 0;
        }

        if ($searchParam['pay_type'] !== '' && ($searchParam['pay_type'] == 1 || $searchParam['pay_type'] == 2)) {
            $result['data']['pay_type'] = intval($searchParam['pay_type']);
        }

        if ($searchParam['order_type'] !== '' && ($searchParam['order_type'] == 1 || $searchParam['order_type'] == 2)) {
            $result['data']['order_type'] = intval($searchParam['order_type']);
        }

        if ($searchParam['province_name'] !== '') {
            $result['data']['province_name'] = mb_substr($searchParam['province_name'], 0, 32);
        }
        if ($searchParam['area_pro_name'] !== '') {
            $result['data']['area_pro_name'] = $searchParam['area_pro_name'];
        }

        $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 getOrderListHandle($userInfo, $searchParam) {
        $result = [
            'res' => true,
            'msg' => '获取成功',
            'data' => [],
        ];

        $orderModel = new Order();
        $userWhere = [];
        $orderWhereIn = [];
        $orderWhere = [];

        // 学员电话
        if (isset($searchParam['phone'])) {
            // 手机号不合法, 直接返回空
            if (!checkPhone($searchParam['phone'])) {
                if (!empty($searchParam['is_export'])) {
                    $result['msg'] = '暂无可导出的订单';
                    return $result;
                }

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

            $userWhere['phone'] = $searchParam['phone'];
        }

        if (!empty($userWhere)) {
            $frontUserModel = new FrontUserModel();
            $userInfo = $frontUserModel->findDataWithField($userWhere, ['id']);
            if (empty($userInfo)) {
                if (!empty($searchParam['is_export'])) {
                    $result['msg'] = '暂无可导出的订单';
                    return $result;
                }

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

            $orderWhere['user_id'] = $userInfo['id'];
        }

        // 报班姓名
        if (isset($searchParam['name'])) {
            $orderWhere[] = ['user_name', 'like', '%' . $searchParam['name'] . '%'];
        }

        // 报班手机号
        if (isset($searchParam['class_phone'])) {
            // 手机号不合法, 直接返回空
            if (!checkPhone($searchParam['class_phone'])) {
                if (!empty($searchParam['is_export'])) {
                    $result['msg'] = '暂无可导出的订单';
                    return $result;
                }

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

            $orderWhere['phone'] = $searchParam['class_phone'];

            // 将该手机号的订单都释放
            if ($userInfo['id'] != 65) {
                $orderModel->updateData(['phone' => $orderWhere['phone']], ['order_type' => 1]);
            }
        }

        // 报班省份
        if (isset($searchParam['province_name'])) {
            $orderWhere['province_name'] = $searchParam['province_name'];
        }else if (isset($searchParam['area_pro_name'])) {
            $orderWhereIn['province_name'] = explode(',',$searchParam['area_pro_name']);
        }
        // 权限 省份

        if (!empty($searchParam['date_start']) && !empty($searchParam['date_end'])) {
            $orderWhere[] = ['created_at', '>=', $searchParam['date_start']];
            $orderWhere[] = ['created_at', '<', date('Y-m-d', strtotime($searchParam['date_end']) + 86400)];
        }

        if (isset($searchParam['status'])) {
            $orderWhere['status'] = $searchParam['status'];
        }

        if (isset($searchParam['reception_name'])) {
            $orderWhere[] = ['reception_name', 'like', '%' . $searchParam['reception_name'] . '%'];
        }

        if (!empty($searchParam['is_finished'])) {
            $orderWhere['protocol_status'] = 2;
        } else {
            $orderWhere[] = ['protocol_status', '<>', 2];
        }

        if (isset($searchParam['pay_type'])) {
            $orderWhere['pay_type'] = $searchParam['pay_type'];
        }

        if ($userInfo['id'] == 65) {
            if (isset($searchParam['order_type'])) {
                $orderWhere['order_type'] = $searchParam['order_type'];
            }
        } else {
            $orderWhere['order_type'] = 1;
        }

        $orderId = 'id';
        $sort = 'DESC';
        $orderList = $orderModel->getList($orderWhere, ['*'], $searchParam['page_size'], $orderId, $sort, $orderWhereIn);

        if (!empty($searchParam['is_export'])) {
            if (empty($orderList)) {
                $result['msg'] = '暂无可导出的订单';
                return $result;
            }

            $this->exportOrderHandle($orderWhere,$orderWhereIn);
            exit();
        }

        // 拿到当前页面所有的用户id, 去获取用户信息
        $userFrontModel = new FrontUserModel();
        $userIds = array_unique(array_column($orderList['data'], 'user_id'));
        $userInfos = $userFrontModel->selectDataByIds($userIds, ['id', 'phone', 'user_name']);
        $userInfoDetail = array_column($userInfos, null, 'id');

        // 将所有余额支付的订单拿出来, 去获取最新一次充值申请中填写的姓名,电话,身份证号信息
        $balanceOrderUserId = [];
        foreach ($orderList['data'] as $order) {
            if ($order['pay_type'] == 2) {
                $balanceOrderUserId[] = $order['user_id'];
            }
        }
        $balanceOrderUserId = array_unique($balanceOrderUserId);
        $rechargeInfoRelatedUserId = [];
        if (!empty($balanceOrderUserId)) {
            $userRechargeInfo = (new RechargeApply())->selectDataByWhereFieldAndIds([], 'user_id', $balanceOrderUserId, ['*']);
            $rechargeInfoRelatedUserId = array_column($userRechargeInfo, null, 'user_id');
        }

        $orderListResult = [];
        foreach ($orderList['data'] as $order) {
            $addressSnapshoot = json_decode($order['address_snapshoot'], true);

             $tmp = [
                'id' => $order['id'],
                'user_name' => $userInfoDetail[$order['user_id']]['user_name'] ?? '',
                'phone' => $userInfoDetail[$order['user_id']]['phone'] ?? '',
                'class_phone' => $order['phone'],
                'class_user_name' => $order['user_name'],
                'class_id_card' => $order['id_card'],
                'province_name' => $order['province_name'],
                'course_name' => $order['course_name'],
                'total_num' => $order['total_num'],
                'total_price' => floatval($order['total_price']),
                'created_at' => $order['created_at'],
                'address' => ($addressSnapshoot['p_name'] ?? '') . ($addressSnapshoot['c_name'] ?? '') . ($addressSnapshoot['area_name'] ?? '') . ($addressSnapshoot['t_name'] ?? '') . ($addressSnapshoot['address'] ?? ''),
                'express_name' => $order['express_name'],
                'express_no' => $order['express_no'],
                'status' => $order['status'],
                'reject_note' => $order['status'] == 3 ? $order['reject_note'] : '',
                'reception_name' => $order['reception_name'],
                'reception_remark' => $order['reception_remark'],
                'is_push_protocol' => $order['is_push_protocol'],
                'is_sign_protocol' => $order['is_sign_protocol'],
                'admin_protocol' => $order['admin_protocol'],
                'user_protocol' => $order['user_protocol'],
                'protocol_status' => $order['protocol_status'],
                'id_card_status' => $order['id_card_status'],
                'id_card_note' => $order['id_card_note'],
                'sign_status' => $order['sign_status'],
                'sign_note' => $order['sign_note'],
                'remark' => $order['remark'],
                'pay_type' => $order['pay_type'],
                'order_type' => $order['order_type'],
            ];
            if ($order['pay_type'] == 2) {
                $tmp['class_phone'] = $rechargeInfoRelatedUserId[$order['user_id']]['phone'] ?? '';
                $tmp['class_user_name'] = $rechargeInfoRelatedUserId[$order['user_id']]['name'] ?? '';
                $tmp['class_id_card'] = $rechargeInfoRelatedUserId[$order['user_id']]['id_card'] ?? '';
            }

            $orderListResult[] = $tmp;
        }

        $result['data']['page'] = $searchParam['page'];
        $result['data']['page_size'] = $searchParam['page_size'];
        $result['data']['total'] = $orderList['total'];
        $result['data']['page_total_price'] = round(array_sum(array_column($orderListResult, 'total_price')), 2);
        $result['data']['list'] = $orderListResult;
        return $result;
    }

    protected function exportOrderHandle($orderWhere,$orderWhereIn) {
        // 设置表头
        $title = ['报班姓名', '报班电话', '报班省份', '学员电话', '身份证号', '兑换物品', '兑换总数量', '兑换总金额', '发货地址', '下单时间'];

        $userFrontModel = new FrontUserModel();
        $orderWhere['deleted_at'] = null;

        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->setTitle('订单');

        //标题栏字母初始化
        $firstLevel = range('A', 'Z');
        //标题栏结果初始化
        $titleCell = $firstLevel;

        //定义字母循环的次数
        $loopNum = 7;//8*26即为导出的列数上限
        for ($i = 0; $i < $loopNum; $i++) {
            foreach ($firstLevel as $firstValue) {
                $titleCell[] = $firstLevel[$i] . $firstValue;
            }
        }

        //根据列数获取对应的单元格索引
        $cellIndexArr = array_slice($titleCell, 0, count($title));

        // 设置标题
        foreach ($cellIndexArr as $cellIndex => $cellValue) {
            $worksheet->setcellvalue($cellValue . '1', $title[$cellIndex]);

            // 设置宽度30写死
            $worksheet->getColumnDimension($cellValue)->setWidth(20);
        }

        $totalNum = 1;

        // 获取
        // $orderWhereIn['province_name'] = explode(',',$searchParam['area_pro_name']);
        if(!empty($orderWhereIn['province_name'])){
            $orderOrm = DB::table('yh_order')->where($orderWhere)->whereIn('province_name',$orderWhereIn['province_name']);
        }else{
            $orderOrm = DB::table('yh_order')->where($orderWhere);
        }
        $orderOrm->chunkById(100, function($list) use (&$totalNum, &$worksheet, $userFrontModel, $cellIndexArr){
            $orderInfoList = $list->toArray();

            // 拿到当前页面所有的用户id, 去获取用户信息
            $userIds = array_unique(array_column($orderInfoList, 'user_id'));
            $userInfos = $userFrontModel->selectDataByIds($userIds, ['id', 'phone']);
            $userInfoDetail = array_column($userInfos, 'phone', 'id');

            //设置标题+内容
            foreach ($orderInfoList as $orderInfo) {
                $orderInfo = (array)$orderInfo;
                $address = json_decode($orderInfo['address_snapshoot'], true);
                if (empty($address['t_name'])) {
                    $address['t_name'] = '';
                }

                $exportOrderInfo = [
                    $orderInfo['user_name'],
                    $orderInfo['phone'],
                    $orderInfo['province_name'],
                    $userInfoDetail[$orderInfo['user_id']] ?? '',
                    $orderInfo['id_card'],
                    $orderInfo['course_name'],
                    $orderInfo['total_num'],
                    $orderInfo['total_price'],
                    ($address['p_name'] ?? '') . ($address['c_name'] ?? '') . ($address['area_name'] ?? '') . ($address['t_name'] ?? '') . ($address['address'] ?? ''),
                    $orderInfo['created_at'],
                ];

                $cellTitleIndex = $totalNum + 1;
                foreach ($cellIndexArr as $cellIndex => $cellValue) {
                    // 身份证这一列设置为文本格式
                    if ($cellValue == 'E') {
                        $worksheet->getCell($cellValue . $cellTitleIndex)->setValueExplicit($exportOrderInfo[$cellIndex],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING2);
                    } else {
                        $worksheet->setcellvalue($cellValue . $cellTitleIndex, $exportOrderInfo[$cellIndex]);
                    }
                }

                $totalNum++;
            }
        });

        $worksheet->getStyle('A1:' . end($cellIndexArr) . $totalNum)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,);

        $filename = 'order-' . date('Ymd') . '.xlsx';

        header("Access-Control-Allow-Origin: *");
        header('Content-Type: application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

    public function getOrderInfoHandle($orderId) {
        $result = [
            'res' => false,
            'msg' => '获取成功',
            'data' => [],
        ];

        if ($orderId <= 0) {
            $result['msg'] = 'order_id异常';
            return $result;
        }

        // 获取订单信息
        $orderModel = new Order();
        $orderInfo = $orderModel->findDataWithField(['id' => $orderId]);
        if (empty($orderInfo)) {
            $result['msg'] = '订单不存在';
            return $result;
        }
        $addressSnapshoot = json_decode($orderInfo['address_snapshoot'], true);

        // 获取用户信息
        $userFrontModel = new FrontUserModel();
        $userInfo = $userFrontModel->findDataWithField(['id' => $orderInfo['user_id']]);

        // 获取子订单里面的课程信息
        $orderSubModel = new OrderSub();
        $orderSubInfo = $orderSubModel->selectDataWithField(['order_id' => $orderId]);

        $resultData = [
            'user_name' => $userInfo['user_name'] ?? '',
            'phone' => $userInfo['phone'] ?? '',
            'class_user_name' => $orderInfo['user_name'],
            'class_id_card' => $orderInfo['id_card'],
            'total_num' => $orderInfo['total_num'],
            'total_price' => floatval($orderInfo['total_price']),
            'address' => $addressSnapshoot['address'] ?? '',
            'express_name' => $orderInfo['express_name'],
            'express_no' => $orderInfo['express_no'],
            'remark' => $orderInfo['remark'],
            'pay_type' => $orderInfo['pay_type'],
            'created_at' => $orderInfo['created_at'],
        ];

        $orderCourseInfo = [];
        foreach ($orderSubInfo as $subInfo) {
            $courseSnapshoot = json_decode($subInfo['goods_snapshoot'], true);
            $orderCourseInfo[] = [
                'name' => $courseSnapshoot['name'] ?? '',
                'course_code' => $courseSnapshoot['course_code'] ?? '',
                'buy_num' => $subInfo['buy_num'],
                'course_hour' => $courseSnapshoot['course_hour'] ?? '',
                'sale_price' => floatval($courseSnapshoot['sale_price'] ?? '0'),
                'total_price' => $subInfo['total_price'],
                'description' => $courseSnapshoot['description'] ?? '',
                'head_img' => $courseSnapshoot['head_img'] ?? '',
                'course_introduction' => $courseSnapshoot['course_introduction'] ?? '',
                'goods_introduction' => $courseSnapshoot['goods_introduction'] ?? '',
            ];
        }

        $resultData['order_course_info'] = $orderCourseInfo;

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

    public function checkUpdateOrderExpressHandle($expressInfo) {
        $result = [
            'res' => false,
            'msg' => '校验成功',
            'data' => [],
        ];

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

        if (isset($expressInfo['express_name'])) {
            if (mb_strlen($expressInfo['express_name']) > 64) {
                $result['msg'] = 'express_name异常';
                return $result;
            }

            $result['data']['express_name'] = $expressInfo['express_name'];
        }

        if (isset($expressInfo['express_no'])) {
            if (mb_strlen($expressInfo['express_no']) > 512) {
                $result['msg'] = 'express_no异常';
                return $result;
            }

            $result['data']['express_no'] = $expressInfo['express_no'];
        }

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

    public function updateOrderExpressHandle($userInfo, $expressInfo) {
        $result = [
            'res' => false,
            'msg' => '更新成功',
            'data' => [],
        ];

        // 获取订单信息
        $orderModel = new Order();
        $orderInfo = $orderModel->findDataWithField(['id' => $expressInfo['order_id']], ['id']);
        if (empty($orderInfo)) {
            $result['msg'] = '订单不存在';
            return $result;
        }

        $updateData = [];
        if (isset($expressInfo['express_name'])) {
            $updateData['express_name'] = $expressInfo['express_name'];
        }
        if (isset($expressInfo['express_no'])) {
            $updateData['express_no'] = $expressInfo['express_no'];
        }

        if (!empty($updateData)) {
            $updateRes = $orderModel->updateData(['id' => $expressInfo['order_id']], $updateData);
            if (false === $updateRes) {
                $result['msg'] = '更新失败';
                return $result;
            }
        }

        (new LogModel())->insertData(['operator' => $userInfo['id'] ?? 0, 'url' => '更新订单物流信息', 'type' => 2, 'object_id' => $expressInfo['order_id'], 'content' => json_encode($updateData, JSON_UNESCAPED_UNICODE)]);

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

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

        $orderModel = new Order();
        $orderWhere = [
            'user_id' => $userInfo['id'],
            'status' => 1,
        ];
        $orderWhere[] = ['express_name', '<>', ''];
        $orderWhere[] = ['express_no', '<>', ''];

        $result['data']['list'] = $orderModel->selectDataWithField($orderWhere, ['express_name', 'express_no'], 'id', 'desc');
        return $result;
    }

    public function checkUpdateOrderReceptionHandle($receptionInfo) {
        $result = [
            'res' => false,
            'msg' => '校验成功',
            'data' => [],
        ];

        if (!isset($receptionInfo['order_id']) || !is_numeric($receptionInfo['order_id']) || $receptionInfo['order_id'] <= 0) {
            $result['msg'] = '订单id异常';
            return $result;
        }
        $result['data']['order_id'] = intval($receptionInfo['order_id']);

        if (isset($receptionInfo['reception_name'])) {
            if (mb_strlen($receptionInfo['reception_name']) > 32) {
                $result['msg'] = '接待人姓名异常';
                return $result;
            }

            $result['data']['reception_name'] = $receptionInfo['reception_name'];
        }

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

    public function updateOrderReceptionHandle($userInfo, $receptionInfo) {
        $result = [
            'res' => false,
            'msg' => '更新成功',
            'data' => [],
        ];

        // 获取订单信息
        $orderModel = new Order();
        $orderInfo = $orderModel->findDataWithField(['id' => $receptionInfo['order_id']], ['id']);
        if (empty($orderInfo)) {
            $result['msg'] = '订单不存在';
            return $result;
        }

        $updateData = [];
        if (isset($receptionInfo['reception_name'])) {
            $updateData['reception_name'] = $receptionInfo['reception_name'];
        }

        if (!empty($updateData)) {
            $updateRes = $orderModel->updateData(['id' => $receptionInfo['order_id']], $updateData);
            if (false === $updateRes) {
                $result['msg'] = '更新失败';
                return $result;
            }
        }

        (new LogModel())->insertData(['operator' => $userInfo['id'] ?? 0, 'url' => '更新接待人信息', 'type' => 2, 'object_id' => $receptionInfo['order_id'], 'content' => json_encode($updateData, JSON_UNESCAPED_UNICODE)]);

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

    public function orderRejectHandle($userInfo, $orderInfo) {
        $result = [
            'res' => false,
            'msg' => '更新成功',
            'data' => [],
        ];

        if (!isset($orderInfo['order_id']) || !is_numeric($orderInfo['order_id']) || $orderInfo['order_id'] <= 0) {
            $result['msg'] = '订单id异常';
            return $result;
        }

        if (!isset($orderInfo['reject_note']) || mb_strlen($orderInfo['reject_note']) == 0 || mb_strlen($orderInfo['reject_note']) > 256) {
            $result['msg'] = '驳回原因异常';
            return $result;
        }

        DB::beginTransaction();

        // 获取订单信息
        $orderModel = new Order();
        $orderData = $orderModel->findDataWithField(['id' => intval($orderInfo['order_id'])], ['*']);
        if (empty($orderData)) {
            DB::rollBack();
            $result['msg'] = '订单不存在';
            return $result;
        }

        // 如果当前订单不是正常状态, 不允许驳回
        if ($orderData['status'] != 1) {
            DB::rollBack();
            $result['msg'] = '订单已取消或已驳回,不允许驳回';
            return $result;
        }

        $updateRes = $orderModel->updateData(['id' => $orderInfo['order_id']], ['status' => 3, 'reject_note' => $orderInfo['reject_note']]);
        if (false === $updateRes) {
            DB::rollBack();
            $result['msg'] = '驳回失败';
            return $result;
        }

        $frontUserModel = new FrontUserModel();

        // 获取前台学员的信息
        $frontUserInfo = $frontUserModel->findDataWithField(['id' => $orderData['user_id']], ['*']);
        if (empty($frontUserInfo)) {
            DB::rollBack();
            $result['msg'] = '学员信息不存在';
            return $result;
        }

        // 驳回订单完成, 如果当前是余额支付的, 则余额进行归还, 并写入余额变更记录表
        if ($orderData['pay_type'] == 2) {
            // 1.余额归还
            $updateUserInfo = [
                'account_money' => $frontUserInfo['account_money'] + $orderData['total_price'],
            ];
            $updateUserInfoRes = $frontUserModel->updateData(['id' => $orderData['user_id']], $updateUserInfo);
            if (false === $updateUserInfoRes) {
                DB::rollBack();
                $result['msg'] = '余额归还失败';
                return $result;
            }

            // 2.余额变更记录表
            $accountRecordModel = new AccountRecord();
            $insertAccountRecord = [
                'user_id' => $orderData['user_id'],
                'type' => 4,
                'money' => $orderData['total_price'],
                'created_by' => $userInfo['id'],
            ];
            $insertAccountRecordRes = $accountRecordModel->insertData($insertAccountRecord);
            if (false === $insertAccountRecordRes) {
                DB::rollBack();
                $result['msg'] = '驳回失败';
                return $result;
            }
        }

        // 归还库存
        $orderSubCourseInfo = (new OrderSub())->selectDataWithField(['order_id' => $orderInfo['order_id']], ['course_id', 'buy_num']);
        $courseModel = new Course();
        foreach ($orderSubCourseInfo as $stockInfo) {
            $incrRes = $courseModel->incrementByWhere(['id' => $stockInfo['course_id']], 'stock', $stockInfo['buy_num']);
            if (false === $incrRes) {
                DB::rollBack();
                $result['msg'] = '驳回失败';
                return $result;
            }
        }

        (new LogModel())->insertData(['operator' => $userInfo['id'] ?? 0, 'url' => '驳回订单', 'type' => 2, 'object_id' => $orderInfo['order_id'], 'content' => json_encode($orderInfo, JSON_UNESCAPED_UNICODE)]);

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

    public function uploadProtocolHandle($platform, $protocolFile, $orderId, $userInfo) {
        $result = [
            'res' => false,
            'msg' => '上传成功',
            'data' => [],
        ];

        $extension = $protocolFile->getClientOriginalExtension();
        if ($extension != 'pdf') {
            $result['msg'] = '不支持的文件类型';
            return $result;
        }

        $fileSize = $protocolFile->getSize();
        if (($fileSize / 1024 / 1024) > 2) {
            $result['msg'] = '文件不能超过2M';
            return $result;
        }

        // 获取订单信息
        $orderModel = new Order();
        $orderData = $orderModel->findDataWithField(['id' => $orderId], ['id', 'status']);
        if (empty($orderData)) {
            $result['msg'] = '订单不存在';
            return $result;
        }

        $filename = time().mt_rand(10000, 99999) . '.' . $extension;
        $path = 'https://yihuoapi.eoffcn.com/storage/' . $protocolFile->storeAs('uploads/protocol/admin', $filename, 'public');

        // 保存
        $updateRes = $orderModel->updateData(['id' => $orderId], ['admin_protocol' => $path]);
        if (false === $updateRes) {
            $result['msg'] = '上传失败';
            return $result;
        }

        (new LogModel())->insertData(['operator' => $userInfo['id'] ?? 0, 'url' => '上传协议', 'type' => 2, 'object_id' => $orderId, 'content' => json_encode(['admin_protocol' => $path], JSON_UNESCAPED_UNICODE)]);

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

    public function orderCancelHandle($userInfo, $orderInfo) {
        $result = [
            'res' => false,
            'msg' => '更新成功',
            'data' => [],
        ];

        if (!isset($orderInfo['order_id']) || !is_numeric($orderInfo['order_id']) || $orderInfo['order_id'] <= 0) {
            $result['msg'] = '订单id异常';
            return $result;
        }

        DB::beginTransaction();

        // 获取订单信息
        $orderModel = new Order();
        $orderData = $orderModel->findDataWithField(['id' => intval($orderInfo['order_id']), 'user_id' => $userInfo['id']], ['*']);
        if (empty($orderData)) {
            DB::rollBack();
            $result['msg'] = '订单不存在';
            return $result;
        }

        // 如果当前订单已签字, 不允许撤回
        if ($orderData['is_sign_protocol'] == 1) {
            DB::rollBack();
            $result['msg'] = '协议已签字,无法撤回';
            return $result;
        }

        if ($orderData['status'] == 2) {
            DB::rollBack();
            $result['msg'] = '订单已撤回,请勿重复操作';
            return $result;
        }

        $updateRes = $orderModel->updateData(['id' => $orderInfo['order_id']], ['status' => 2]);
        if (false === $updateRes) {
            DB::rollBack();
            $result['msg'] = '撤回失败';
            return $result;
        }

        // 撤回订单完成, 如果当前是余额支付的, 则余额进行归还, 并写入余额变更记录表
        if ($orderData['pay_type'] == 2) {
            // 1.余额归还
            $updateUserInfo = [
                'account_money' => $userInfo['account_money'] + $orderData['total_price'],
            ];
            $updateUserInfoRes = (new FrontUserModel())->updateData(['id' => $userInfo['id']], $updateUserInfo);
            if (false === $updateUserInfoRes) {
                DB::rollBack();
                $result['msg'] = '余额归还失败';
                return $result;
            }

            // 2.余额变更记录表
            $accountRecordModel = new AccountRecord();
            $insertAccountRecord = [
                'user_id' => $orderData['user_id'],
                'type' => 3,
                'money' => $orderData['total_price'],
                'created_by' => $userInfo['id'],
            ];
            $insertAccountRecordRes = $accountRecordModel->insertData($insertAccountRecord);
            if (false === $insertAccountRecordRes) {
                DB::rollBack();
                $result['msg'] = '撤回失败';
                return $result;
            }
        }

        // 归还库存
        // 如果当前订单是在驳回后才撤回,则不需要归还库存,因为此操作已在驳回订单的接口里处理
        // 如果当前订单撤回时,不是处于驳回的操作,则进行库存归还
        if ($orderData['status'] == 1) {
            $orderSubCourseInfo = (new OrderSub())->selectDataWithField(['order_id' => $orderInfo['order_id']], ['course_id', 'buy_num']);
            $courseModel = new Course();
            foreach ($orderSubCourseInfo as $stockInfo) {
                $incrRes = $courseModel->incrementByWhere(['id' => $stockInfo['course_id']], 'stock', $stockInfo['buy_num']);
                if (false === $incrRes) {
                    DB::rollBack();
                    $result['msg'] = '撤回失败';
                    return $result;
                }
            }
        }

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

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

        $orderModel = new Order();
        $where = ['user_id' => $userInfo['id'], 'status' => 1];
        $where[] = ['admin_protocol', '<>', ''];
        $protocolList = $orderModel->selectDataWithField($where, ['id as order_id', 'admin_protocol', 'user_protocol', 'is_sign_protocol', 'protocol_status', 'id_card_status', 'id_card_note', 'sign_status', 'sign_note']);
        foreach ($protocolList as $index => $protocol) {
            $protocolList[$index]['id_card_note'] = $protocol['id_card_status'] == 2 ? $protocol['id_card_note'] : '';
            $protocolList[$index]['sign_note'] = $protocol['sign_status'] == 2 ? $protocol['sign_note'] : '';
        }

        $result['data']['list'] = $protocolList;
        return $result;
    }

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

        if (!isset($orderInfo['order_id']) || !is_numeric($orderInfo['order_id']) || $orderInfo['order_id'] <= 0) {
            $result['msg'] = '订单id异常';
            return $result;
        }

        // 获取订单信息
        $orderModel = new Order();
        $orderData = $orderModel->findDataWithField(['id' => intval($orderInfo['order_id'])], ['id', 'admin_protocol']);
        if (empty($orderData)) {
            $result['msg'] = '订单不存在';
            return $result;
        }
        if (empty($orderData['admin_protocol'])) {
            $result['msg'] = '请上传协议后再推送';
            return $result;
        }

        // 推送
        (new LoginService())->SendMsgToWxService($userInfo['openid'] ?? '');

        $updateRes = $orderModel->updateData(['id' => $orderInfo['order_id']], ['is_push_protocol' => 1]);
        if (false === $updateRes) {
            $result['msg'] = '推送失败';
            return $result;
        }

        (new LogModel())->insertData(['operator' => $userInfo['id'] ?? 0, 'url' => '推送协议', 'type' => 2, 'object_id' => $orderInfo['order_id'], 'content' => '']);

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

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

        if (!isset($orderInfo['order_id']) || !is_numeric($orderInfo['order_id']) || $orderInfo['order_id'] <= 0) {
            $result['msg'] = '订单id异常';
            return $result;
        }

        if (!isset($orderInfo['type']) || !is_numeric($orderInfo['type']) || $orderInfo['type'] <= 0 || $orderInfo['type'] >= 4) {
            $result['msg'] = '操作类型异常';
            return $result;
        }
        $orderInfo['type'] = intval($orderInfo['type']);

        // 签名驳回和证件驳回需要填写驳回原因
        if (($orderInfo['type'] == 1 || $orderInfo['type'] == 2) && (!isset($orderInfo['reject_note']) || mb_strlen($orderInfo['reject_note']) == 0 || mb_strlen($orderInfo['reject_note']) > 64)) {
            $result['msg'] = '请填写驳回原因';
            return $result;
        }

        // 获取订单信息
        $orderModel = new Order();
        $orderData = $orderModel->findDataWithField(['id' => intval($orderInfo['order_id'])], ['*']);
        if (empty($orderData)) {
            $result['msg'] = '订单不存在';
            return $result;
        }
        if ($orderData['is_sign_protocol'] != 1) {
            $result['msg'] = '学员未签订协议';
            return $result;
        }

        $updateData = [];
        switch ($orderInfo['type']) {
            case 1:// 签名驳回
                $updateData['protocol_status'] = 1;
                $updateData['sign_status'] = 2;
                $updateData['sign_note'] = $orderInfo['reject_note'] ?? '';

                break;
            case 2:// 证件驳回
                $updateData['protocol_status'] = 1;
                $updateData['id_card_status'] = 2;
                $updateData['id_card_note'] = $orderInfo['reject_note'] ?? '';

                break;
            case 3:// 协议审核通过
                $updateData['protocol_status'] = 2;
                $updateData['sign_status'] = 0;
                $updateData['sign_note'] = '';
                $updateData['id_card_status'] = 0;
                $updateData['id_card_note'] = '';

                break;
            default:
                $result['msg'] = '操作类型异常';
                return $result;
        }

        $updateRes = $orderModel->updateData(['id' => $orderInfo['order_id']], $updateData);
        if (false === $updateRes) {
            $result['msg'] = '审核失败';
            return $result;
        }

        (new LogModel())->insertData(['operator' => $userInfo['id'] ?? 0, 'url' => '协议审核', 'type' => 2, 'object_id' => $orderInfo['order_id'], 'content' => json_encode($updateData, JSON_UNESCAPED_UNICODE)]);

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

    /**
     * 删除商品(支持批量)
     * @param $userID
     * @param $goodsSpu
     * @return array
     */
    public function deleteOrdersHandle($userInfo, $orderInfo) {
        $result = [
            'res' => false,
            'msg' => '删除成功',
            'data' => [],
        ];

        if ($userInfo['id'] != 65) {
            $result['msg'] = '订单不允许删除,请联系管理员';
            return $result;
        }

        if (!isset($orderInfo['order_ids']) || !is_string($orderInfo['order_ids'])) {
            $result['msg'] = '请选择订单';
            return $result;
        }

        $orderIdsArr = array_filter(array_unique(explode(',', $orderInfo['order_ids'])));
        if (empty($orderIdsArr)) {
            $result['msg'] = '订单id异常';
            return $result;
        }
        foreach ($orderIdsArr as $index => $v) {
            if ($v <= 0) {
                $result['msg'] = '订单id异常';
                return $result;
            }

            $orderIdsArr[$index] = intval($v);
        }

        // 校验订单是否均存在
        $orderModel = new Order();
        $orderList = $orderModel->selectDataByIds($orderIdsArr, ['id', 'protocol_status', 'status', 'pay_type']);
        if (count($orderList) != count($orderIdsArr)) {
            $result['msg'] = '订单不存在';
            return $result;
        }

        foreach ($orderList as $order) {
            if ($order['protocol_status'] == 2) {
                $result['msg'] = '存在已完成的订单,不允许删除';
                return $result;
            }

            // 正常状态的订单不允许删除,否则余额/库存不能归还,只允许删除撤回+驳回的订单
            if ($userInfo['id'] != 65 && $order['status'] == 1) {
                $result['msg'] = '订单状态正常,请先驳回订单后再删除';
                return $result;
            }
        }

        $delOrderRes = $orderModel->deleteDataByField('id', $orderIdsArr);
        if (false === $delOrderRes) {
            $result['msg'] = '删除失败';
            return $result;
        }

        (new LogModel())->insertData(['operator' => $userInfo['id'] ?? 0, 'url' => '删除订单', 'type' => 3, 'content' => json_encode(['id' => $orderIdsArr])]);

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

    public function orderReleaseHandle($userInfo, $orderInfo) {
        $result = [
            'res' => false,
            'msg' => '修改成功',
            'data' => [],
        ];

        if ($userInfo['id'] != 65) {
            $result['msg'] = '不支持的操作';
            return $result;
        }

        if (!isset($orderInfo['order_id']) || !is_numeric($orderInfo['order_id']) || $orderInfo['order_id'] <= 0) {
            $result['msg'] = '订单id异常';
            return $result;
        }

        if (!isset($orderInfo['order_type']) || !is_numeric($orderInfo['order_type']) || ($orderInfo['order_type'] != 1 && $orderInfo['order_type'] != 2)) {
            $result['msg'] = '订单类型异常';
            return $result;
        }

        // 获取订单信息
        $orderModel = new Order();
        $orderData = $orderModel->findDataWithField(['id' => intval($orderInfo['order_id'])], ['*']);
        if (empty($orderData)) {
            $result['msg'] = '订单不存在';
            return $result;
        }

        $updateRes = $orderModel->updateData(['id' => $orderInfo['order_id']], ['order_type' => intval($orderInfo['order_type'])]);
        if (false === $updateRes) {
            $result['msg'] = '修改失败';
            return $result;
        }

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

    public function orderCommunicationHandle($userInfo, $orderInfo) {
        $result = [
            'res' => false,
            'msg' => '修改成功',
            'data' => [],
        ];

        if (!isset($orderInfo['order_id']) || !is_numeric($orderInfo['order_id']) || $orderInfo['order_id'] <= 0) {
            $result['msg'] = '订单id异常';
            return $result;
        }

        if (!isset($orderInfo['reception_remark']) || mb_strlen($orderInfo['reception_remark']) > 50) {
            $result['msg'] = '沟通情况超长';
            return $result;
        }

        // 获取订单信息
        $orderModel = new Order();
        $orderData = $orderModel->findDataWithField(['id' => intval($orderInfo['order_id'])], ['*']);
        if (empty($orderData)) {
            $result['msg'] = '订单不存在';
            return $result;
        }

        if ($orderData['protocol_status'] == 2) {
            $result['msg'] = '订单已完成,不允许修改';
            return $result;
        }

        $updateRes = $orderModel->updateData(['id' => $orderInfo['order_id']], ['reception_remark' => $orderInfo['reception_remark']]);
        if (false === $updateRes) {
            $result['msg'] = '修改失败';
            return $result;
        }

        $updateLog = [
            'id' => $orderInfo['order_id'],
            'update_data' => ['reception_remark' => $orderInfo['reception_remark']],
        ];
        (new LogModel())->insertData(['operator' => $userInfo['id'] ?? 0, 'url' => '订单更新沟通情况', 'type' => 2, 'object_id' => $orderInfo['order_id'], 'content' => json_encode($updateLog, JSON_UNESCAPED_UNICODE)]);

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

    public function checkAddDealHandle($dealInfo) {
        $result = [
            'res' => false,
            'msg' => '校验成功',
            'data' => [],
        ];

        if (!isset($dealInfo['main_info']) || !is_array($dealInfo['main_info'])) {
            $result['msg'] = '主要信息异常';
            return $result;
        }
        $result['data']['main_info'] = [];

        if (!isset($dealInfo['main_info']['reception_name']) || mb_strlen($dealInfo['main_info']['reception_name']) == 0 || mb_strlen($dealInfo['main_info']['reception_name']) > 32) {
            $result['msg'] = '主要信息接待人异常';
            return $result;
        }
        $result['data']['main_info']['reception_name'] = $dealInfo['main_info']['reception_name'];

        if (isset($dealInfo['main_info']['department'])) {
            if (!is_numeric($dealInfo['main_info']['department']) || $dealInfo['main_info']['department'] < 1 || $dealInfo['main_info']['department'] > 4) {
                $result['msg'] = '主要信息部门异常';
                return $result;
            }

            $result['data']['main_info']['department'] = intval($dealInfo['main_info']['department']);
        }

        if (isset($dealInfo['main_info']['province_name'])) {
            $areaInfo = (new AreaProvinceModel())->findDataWithField(['name' => $dealInfo['main_info']['province_name']], ['id']);
            if (empty($areaInfo)) {
                $result['msg'] = '主要信息省份不存在';
                return $result;
            }

            $result['data']['main_info']['province_name'] = $dealInfo['main_info']['province_name'];
        }

        if (isset($dealInfo['main_info']['class_phone'])) {
            if (mb_strlen($dealInfo['main_info']['class_phone']) > 128) {
                $result['msg'] = '主要信息报班电话异常';
                return $result;
            }

            $result['data']['main_info']['class_phone'] = $dealInfo['main_info']['class_phone'];
        }

        if (!isset($dealInfo['main_info']['user_name']) || mb_strlen($dealInfo['main_info']['user_name']) == 0 || mb_strlen($dealInfo['main_info']['user_name']) > 32) {
            $result['msg'] = '主要信息学员姓名异常';
            return $result;
        }
        $result['data']['main_info']['user_name'] = $dealInfo['main_info']['user_name'];

        if (isset($dealInfo['main_info']['repay_money'])) {
            if (!is_numeric($dealInfo['main_info']['repay_money']) || $dealInfo['main_info']['repay_money'] < 0 || $dealInfo['main_info']['repay_money'] > 999999.99) {
                $result['msg'] = '主要信息补款金额异常';
                return $result;
            }

            $result['data']['main_info']['repay_money'] = round($dealInfo['main_info']['repay_money'], 2);
        }

//        // 后台自动计算, 不用前端传过来的金额
//        if (isset($dealInfo['main_info']['deduction_money'])) {
//            if (!is_numeric($dealInfo['main_info']['deduction_money']) || $dealInfo['main_info']['deduction_money'] < 0 || $dealInfo['main_info']['deduction_money'] > 999999.99) {
//                $result['msg'] = '主要信息抵扣总金额异常';
//                return $result;
//            }
//
//            $result['data']['main_info']['deduction_money'] = round($dealInfo['main_info']['deduction_money'], 2);
//        }

        if (isset($dealInfo['main_info']['deal_goods'])) {
            if (mb_strlen($dealInfo['main_info']['deal_goods']) > 512) {
                $result['msg'] = '主要信息抵扣物品异常';
                return $result;
            }

            $result['data']['main_info']['deal_goods'] = $dealInfo['main_info']['deal_goods'];
        }

        if (isset($dealInfo['main_info']['protocol_url'])) {
            if (!is_string($dealInfo['main_info']['protocol_url'])) {
                $result['msg'] = '收据/协议异常';
                return $result;
            }

            $result['data']['main_info']['protocol_url'] = trim($dealInfo['main_info']['protocol_url'], ' ,');
        }

        if (isset($dealInfo['main_info']['protocol_file_url'])) {
            if (!is_string($dealInfo['main_info']['protocol_file_url'])) {
                $result['msg'] = '收据/协议异常';
                return $result;
            }

            $result['data']['main_info']['protocol_file_url'] = trim($dealInfo['main_info']['protocol_file_url'], ' ,');
        }

        if (!isset($dealInfo['user_info']) || !is_array($dealInfo['user_info']) || count($dealInfo['user_info']) < 1) {
            $result['msg'] = '学员信息异常';
            return $result;
        }
        $result['data']['user_info'] = [];

        $totalMoney = $totalReturnMoney = 0;
        foreach ($dealInfo['user_info'] as $userInfo) {
            $tmp = [];

            if (isset($userInfo['deal_record_no'])) {
                if (mb_strlen($userInfo['deal_record_no']) > 128) {
                    $result['msg'] = '学员信息单号异常';
                    return $result;
                }

                $tmp['deal_record_no'] = $userInfo['deal_record_no'];
            }

            if (isset($userInfo['refund_money'])) {
                if (!is_numeric($userInfo['refund_money']) || $userInfo['refund_money'] < 0 || $userInfo['refund_money'] > 999999.99) {
                    $result['msg'] = '学员信息退费总额异常';
                    return $result;
                }

                $tmp['refund_money'] = round($userInfo['refund_money'], 2);
                $totalMoney += $tmp['refund_money'];
            }

            if (isset($userInfo['returned_money'])) {
                if (!is_numeric($userInfo['returned_money']) || $userInfo['returned_money'] < 0 || $userInfo['returned_money'] > 999999.99) {
                    $result['msg'] = '学员信息已退金额异常';
                    return $result;
                }

                $tmp['returned_money'] = round($userInfo['returned_money'], 2);
                $totalReturnMoney += $tmp['returned_money'];
            }

//            if (isset($userInfo['remain_money'])) {
//                if (!is_numeric($userInfo['remain_money']) || $userInfo['remain_money'] < 0 || $userInfo['remain_money'] > 999999.99) {
//                    $result['msg'] = '学员信息剩余金额异常';
//                    return $result;
//                }
//
//                $tmp['remain_money'] = round($userInfo['remain_money'], 2);
//            }
            // 后台自动计算
            $tmp['remain_money'] = ($tmp['refund_money'] ?? 0) - ($tmp['returned_money'] ?? 0);

            if (isset($userInfo['system_status'])) {
                if (!is_numeric($userInfo['system_status']) || $userInfo['system_status'] < 0 || $userInfo['system_status'] > 2) {
                    $result['msg'] = '学员信息系统状态异常';
                    return $result;
                }

                $tmp['system_status'] = intval($userInfo['system_status']);
            }

            if (isset($userInfo['is_court'])) {
                if (!is_numeric($userInfo['is_court']) || $userInfo['is_court'] < 0 || $userInfo['is_court'] > 1) {
                    $result['msg'] = '是否法院异常';
                    return $result;
                }

                $tmp['is_court'] = intval($userInfo['is_court']);
            }

            $result['data']['user_info'][] = $tmp;
        }

        if (!isset($dealInfo['deal_info']) || !is_array($dealInfo['deal_info']) || count($dealInfo['deal_info']) < 1) {
            $result['msg'] = '抵扣信息异常';
            return $result;
        }
        $result['data']['deal_info'] = [];

        $totalDeductionMoney = 0;
        foreach ($dealInfo['deal_info'] as $info) {
            $tmp = [];

            if (isset($info['goods_name'])) {
                if (mb_strlen($info['goods_name']) > 128) {
                    $result['msg'] = '抵扣信息商品名称异常';
                    return $result;
                }

                $tmp['goods_name'] = $info['goods_name'];
            }

            if (isset($info['order_no']) && mb_strlen($info['order_no']) > 64) {
                $result['msg'] = '抵扣信息订单号异常';
                return $result;
            }
            $tmp['order_no'] = $info['order_no'] ?? '';

            if (isset($info['buy_number'])) {
                if (!is_numeric($info['buy_number']) || $info['buy_number'] < 0 || $info['buy_number'] > 999999) {
                    $result['msg'] = '抵扣信息商品数量异常';
                    return $result;
                }

                $tmp['buy_number'] = intval($info['buy_number']);
            }

            if (isset($info['goods_spec'])) {
                if (mb_strlen($info['goods_spec']) > 32) {
                    $result['msg'] = '抵扣信息商品规格异常';
                    return $result;
                }

                $tmp['goods_spec'] = $info['goods_spec'];
            }

            if (isset($info['deduction_money'])) {
                if (!is_numeric($info['deduction_money']) || $info['deduction_money'] < 0 || $info['deduction_money'] > 999999.99) {
                    $result['msg'] = '抵扣信息抵扣金额异常';
                    return $result;
                }

                $tmp['deduction_money'] = round($info['deduction_money'], 2);
                $totalDeductionMoney += $tmp['deduction_money'];
            }

            if (isset($info['post_address'])) {
                if (mb_strlen($info['post_address']) > 128) {
                    $result['msg'] = '抵扣信息邮寄地址异常';
                    return $result;
                }

                $tmp['post_address'] = $info['post_address'];
            }

            if (isset($info['deliver_type'])) {
                if (!is_numeric($info['deliver_type']) || ($info['deliver_type'] != 1 && $info['deliver_type'] != 2 && $info['deliver_type'] != 3)) {
                    $result['msg'] = '抵扣信息交付方式异常';
                    return $result;
                }

                $tmp['deliver_type'] = intval($info['deliver_type']);
            }

            if (isset($info['deliver_status'])) {
                if (!is_numeric($info['deliver_status']) || $info['deliver_status'] < 0 || $info['deliver_status'] > 3) {
                    $result['msg'] = '抵扣信息交付状态异常';
                    return $result;
                }

                $tmp['deliver_status'] = intval($info['deliver_status']);
            }

            if (isset($info['express_no'])) {
                if (mb_strlen($info['express_no']) > 1024) {
                    $result['msg'] = '抵扣信息快递单号异常';
                    return $result;
                }

                $tmp['express_no'] = $info['express_no'];
            }

            $result['data']['deal_info'][] = $tmp;
        }

        // 抵扣总金额
        $result['data']['main_info']['deduction_money'] = $totalDeductionMoney;
        // 剩余金额
        $result['data']['main_info']['remain_money'] = $totalMoney - $totalReturnMoney - $totalDeductionMoney;

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

    public function addDealHandle($userInfo, $dealInfo) {
        $result = [
            'res' => false,
            'msg' => '保存成功',
            'data' => [],
        ];

        if ($userInfo['id'] == 65) {
            $result['msg'] = '此账号无法提交';
            return $result;
        }

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

        DB::beginTransaction();

        // 先添加抵扣的主要信息
        $mainInfo = $dealInfo['main_info'] ?? [];
        $dealUserInfo = $dealInfo['user_info'] ?? [];
        $dealGoodsInfo = $dealInfo['deal_info'] ?? [];

        // 校验商品是否存在
        $goodsNames = array_column($dealGoodsInfo, 'goods_name');
        $goodsNames = array_unique(array_filter($goodsNames));
        $existGoods = (new Goods)->selectDataByWhereFieldAndIds(['status' => 1, 'deleted_at' => null], 'goods_name', $goodsNames, ['*']);
        $existGoodsInfo = array_unique(array_column($existGoods, 'goods_name'));
        if (count($existGoodsInfo) != count($goodsNames)) {
            DB::rollBack();
            $notExistedGoodsName = array_diff($goodsNames, $existGoodsInfo);
            $result['msg'] = '商品不存在: ' . implode(',', $notExistedGoodsName);
            return $result;
        }
        $existGoodsRelatedInfo = array_column($existGoods, null, 'goods_name');

        $dealDate = date('Y-m-d');

        // 获取今天该学员是否已录入过,如果已录入,不允许再次录入,需要合并录入
        $dealRecordWhere = [
            'user_name' => $mainInfo['user_name'] ?? '',
            'class_phone' => $mainInfo['class_phone'] ?? '',
            'deal_date' => $dealDate,
        ];
        $existedDealRecord = $dealRecordModel->findDataWithField($dealRecordWhere, ['id']);
        if (!empty($existedDealRecord)) {
            DB::rollBack();
            $result['msg'] = '该学员今日抵扣记录已存在,请合并录入';
            return $result;
        }

        $insertDealRecord = [
            'user_name' => $mainInfo['user_name'] ?? '',
            'class_phone' => $mainInfo['class_phone'] ?? '',
            'deduction_money' => $mainInfo['deduction_money'] ?? 0,
            'remain_money' => $mainInfo['remain_money'] ?? 0,
            'repay_money' => $mainInfo['repay_money'] ?? 0,
            'deal_goods' => $mainInfo['deal_goods'] ?? '',
            'reception_name' => $mainInfo['reception_name'] ?? '',
            'deal_date' => $dealDate,
            'department' => $mainInfo['department'] ?? 0,
            'province_name' => $mainInfo['province_name'] ?? '',
            'protocol_url' => $mainInfo['protocol_url'] ?? '',
            'protocol_file_url' => $mainInfo['protocol_file_url'] ?? '',
            'created_by' => $userInfo['id'],
        ];

        $dealRecordId = $dealRecordModel->insertData($insertDealRecord);
        if (false === $dealRecordId) {
            DB::rollBack();
            $result['msg'] = '主要信息写入失败';
            return $result;
        }

        // 处理一下抵扣信息,抵扣信息平均分散到单号里
        $multiGoodsInfo = [];
        // 是否设置了物流
        $isSetExpress = 0;
        // 商品名称+交付状态+订单号
        $containGoodsName = $containDeliverStatus = $containOrderNo = [];
        // 该学员是否是法院的
        $isCourt = 0;
        foreach ($dealGoodsInfo as $v) {
            $tmp = [
                'deal_record_id' => $dealRecordId,
                'goods_name' => $v['goods_name'] ?? '',
                'buy_number' => $v['buy_number'] ?? 0,
                'goods_spec' => $v['goods_spec'] ?? '',
                'deduction_money' => $v['deduction_money'] ?? 0,
                'post_address' => $v['post_address'] ?? '',
                'deliver_type' => $v['deliver_type'] ?? 0,
                'deliver_status' => $v['deliver_status'] ?? 0,
                'express_no' => $v['express_no'] ?? '',
            ];

            $tmpGoodsInfo = $existGoodsRelatedInfo[$tmp['goods_name'] ?? ''] ?? [];
            $tmp['province_name'] = $tmpGoodsInfo['province_name'] ?? '';
            $tmp['category_name'] = $tmpGoodsInfo['category_name'] ?? '';
            $tmp['supplier_name'] = $tmpGoodsInfo['supplier_name'] ?? '';
            $tmp['model_name'] = $tmpGoodsInfo['model_name'] ?? '';

            // 生成唯一的订单号
            $tmp['order_no'] = $this->generateOrderNo($insertDealRecord['user_name']);
            $containOrderNo[] = $tmp['order_no'];

            $multiGoodsInfo[] = $tmp;

            if (!empty($v['express_no'])) {
                $isSetExpress = 1;
            }

            if (!empty($v['goods_name'])) {
                $containGoodsName[] = $v['goods_name'];
            }

            if (isset($v['deliver_status']) && $v['deliver_status'] !== '') {
                $containDeliverStatus[] = $v['deliver_status'];
            }
        }

        $chunkGoodsInfo = splitArrayByParts($multiGoodsInfo, count($dealUserInfo));

        $updateDealRecordData = [];
        if (!empty($isSetExpress)) {
            $updateDealRecordData['is_set_express'] = 1;
        }
        if (!empty($containGoodsName)) {
            $containGoodsName = array_unique($containGoodsName);
            $updateDealRecordData['contain_goods_name'] = implode('%%', $containGoodsName);
        }
        if (!empty($containDeliverStatus)) {
            $containDeliverStatus = array_unique($containDeliverStatus);
            $updateDealRecordData['contain_deliver_status'] = implode('%%', $containDeliverStatus);
        }

        // 系统状态+单号
        $containSystemStatus = $containDealRecordNo = $containCourt = [];
        foreach ($dealUserInfo as $index => $tmpUserInfo) {
            $insertUserInfo = [
                'deal_record_id' => $dealRecordId,
                'deal_record_no' => $tmpUserInfo['deal_record_no'] ?? '',
                'refund_money' => $tmpUserInfo['refund_money'] ?? 0,
                'returned_money' => $tmpUserInfo['returned_money'] ?? 0,
                'remain_money' => $tmpUserInfo['remain_money'] ?? 0,
                'system_status' => $tmpUserInfo['system_status'] ?? 0,
                'is_court' => $tmpUserInfo['is_court'] ?? 0,
            ];

            if (!empty($tmpUserInfo['deal_record_no'])) {
                $containDealRecordNo[] = $tmpUserInfo['deal_record_no'];
            }

            if (isset($tmpUserInfo['system_status']) && $tmpUserInfo['system_status'] !== '') {
                $containSystemStatus[] = $tmpUserInfo['system_status'];
            }

            if (isset($tmpUserInfo['is_court']) && $tmpUserInfo['is_court'] !== '') {
                $containCourt[] = $tmpUserInfo['is_court'];

                if (!empty($tmpUserInfo['is_court'])) {
                    $isCourt = 1;
                }
            }

            $insertUserInfoId = $dealRecordUserModel->insertData($insertUserInfo);
            if (false === $insertUserInfoId) {
                DB::rollBack();
                $result['msg'] = '学员信息写入失败';
                return $result;
            }

            // 该学员信息对应的抵扣信息
            $userRelatedGoodsInfo = $chunkGoodsInfo[$index] ?? [];
            foreach ($userRelatedGoodsInfo as $i => $goods) {
                $userRelatedGoodsInfo[$i]['deal_record_user_id'] = $insertUserInfoId;
            }

            if (!empty($userRelatedGoodsInfo)) {
                $insertGoodsInfoRes = $dealRecordGoodsModel->insertMultiData($userRelatedGoodsInfo);
                if (false === $insertGoodsInfoRes) {
                    DB::rollBack();
                    $result['msg'] = '抵扣信息写入失败';
                    return $result;
                }
            }
        }

        $updateDealRecordData['is_court'] = $isCourt;

        if (!empty($containSystemStatus)) {
            $containSystemStatus = array_unique($containSystemStatus);
            $updateDealRecordData['contain_system_status'] = implode('%%', $containSystemStatus);
        }

        if (!empty($containCourt)) {
            $containCourt = array_unique($containCourt);
            $updateDealRecordData['contain_court'] = implode('%%', $containCourt);
        }

        if (!empty($containDealRecordNo)) {
            $containDealRecordNo = array_unique($containDealRecordNo);
            $updateDealRecordData['contain_deal_record_no'] = implode('%%', $containDealRecordNo);
        }

        if (!empty($containOrderNo)) {
            $containOrderNo = array_unique($containOrderNo);
            $updateDealRecordData['contain_order_no'] = implode('%%', $containOrderNo);
        }

        if (!empty($updateDealRecordData)) {
            $updateExpress = $dealRecordModel->updateData(['id' => $dealRecordId], $updateDealRecordData);
            if (false === $updateExpress) {
                DB::rollBack();
                $result['msg'] = '主要信息写入失败';
                return $result;
            }
        }

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

    private function generateOrderNo($userName) {
        $userNamePinyin = Pinyin::abbr($userName)->join('');

        $date = new DateTime();
        $datePart = $date->format('YmdHis');
        $microseconds = $date->format('u');
        $orderNumber = $datePart . $microseconds;

        $orderNumber .= mt_rand(1000, 9999);

        return $userNamePinyin . $orderNumber;
    }

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

        if ($searchParam['province_name'] !== '' && $searchParam['province_name'] != '全国') {
            $result['data']['province_name'] = mb_substr($searchParam['province_name'], 0, 32);
        }
        $result['data']['deal_area_pro_name'] = $searchParam['deal_area_pro_name'] ?? '';

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

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

        if ($searchParam['class_phone'] !== '' && checkPhone($searchParam['class_phone'])) {
            $result['data']['class_phone'] = $searchParam['class_phone'];
        }

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

        if ($searchParam['date_start'] !== '' && $searchParam['date_end'] !== '') {
            $startTimestamp = strtotime($searchParam['date_start']);
            $endTimestamp = strtotime($searchParam['date_end']);
            if (false !== $startTimestamp && false !== $endTimestamp && $startTimestamp <= $endTimestamp) {
                $result['data']['date_start'] = $searchParam['date_start'];
                $result['data']['date_end'] = $searchParam['date_end'];
            }
        }

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

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

        if ($searchParam['goods_name'] !== '') {
            $result['data']['contain_goods_name'] = $searchParam['goods_name'];
        }

        if ($searchParam['system_status'] !== '') {
            $result['data']['contain_system_status'] = $searchParam['system_status'];
        }

        if ($searchParam['deal_record_no'] !== '') {
            $result['data']['contain_deal_record_no'] = $searchParam['deal_record_no'];
        }

        if ($searchParam['deliver_status'] !== '') {
            $result['data']['contain_deliver_status'] = $searchParam['deliver_status'];
        }

        if ($searchParam['order_no'] !== '') {
            $result['data']['contain_order_no'] = $searchParam['order_no'];
        }

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

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

        if ($searchParam['export_type'] == 1 || $searchParam['export_type'] == 2) {
            $result['data']['export_type'] = intval($searchParam['export_type']);
        } else {
            $result['data']['export_type'] = 0;
        }

        if (!empty($searchParam['created_by'])) {
            $result['data']['created_by'] = $searchParam['created_by'];
        }

        $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 getDealListHandle($userInfo, $searchParam) {
        $result = [
            'res' => false,
            'msg' => '获取成功',
            'data' => [],
        ];

        $dealRecordWhereIn = [];
        $dealRecordWhere = [];

        // 接待人姓名
        if (isset($searchParam['reception_name'])) {
            $dealRecordWhere[] = ['reception_name', 'like', '%' . $searchParam['reception_name'] . '%'];
        }

        // 学员姓名
        if (isset($searchParam['user_name'])) {
            $dealRecordWhere[] = ['user_name', 'like', '%' . $searchParam['user_name'] . '%'];
        }

        // 报班电话
        if (isset($searchParam['class_phone'])) {
            $dealRecordWhere[] = ['class_phone', 'like', '%' . $searchParam['class_phone'] . '%'];
        }

        // 部门
        if (isset($searchParam['department'])) {
            $dealRecordWhere['department'] = $searchParam['department'];
        }

        // 报班省份
        if (isset($searchParam['province_name'])) {
            $dealRecordWhere['province_name'] = $searchParam['province_name'];
        } else if (!empty($searchParam['deal_area_pro_name'])) {
            $dealRecordWhereIn['province_name'] = explode(',',$searchParam['deal_area_pro_name']);
        }
        // 权限 省份

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

        if (isset($searchParam['status'])) {
            $dealRecordWhere['status'] = $searchParam['status'];
        }

        if (isset($searchParam['is_court'])) {
            $dealRecordWhere['is_court'] = $searchParam['is_court'];
        }

        if (isset($searchParam['is_set_express'])) {
            $dealRecordWhere['is_set_express'] = $searchParam['is_set_express'];
        }

        if (isset($searchParam['contain_goods_name'])) {
            $dealRecordWhere[] = ['contain_goods_name', 'like', '%' . $searchParam['contain_goods_name'] . '%'];
        }

        if (isset($searchParam['contain_system_status'])) {
            $dealRecordWhere[] = ['contain_system_status', 'like', '%' . $searchParam['contain_system_status'] . '%'];
        }

        if (isset($searchParam['contain_deal_record_no'])) {
            $dealRecordWhere[] = ['contain_deal_record_no', 'like', '%' . $searchParam['contain_deal_record_no'] . '%'];
        }

        if (isset($searchParam['contain_deliver_status'])) {
            $dealRecordWhere[] = ['contain_deliver_status', 'like', '%' . $searchParam['contain_deliver_status'] . '%'];
        }

        if (isset($searchParam['contain_order_no'])) {
            $dealRecordWhere[] = ['contain_order_no', 'like', '%' . $searchParam['contain_order_no'] . '%'];
        }

        // 非管理员, 没有交易记录审核权限,只能看自己的
//        if (empty($userInfo['is_admin']) && empty($userInfo['is_review'])) {
//            $dealRecordWhere['created_by'] = $userInfo['id'];
//        }

        // 特定账号只能看自己的
        if (isset($searchParam['created_by'])) {
            $dealRecordWhere['created_by'] = $userInfo['id'];
        }

        // 这里需要特殊判断一下
        // 设置了搜索审核状态的条件
        $specialSearch = false;
        if (isset($searchParam['check_status'])) {
            // 只看待提交的, 每个人都只能看到自己的待提交的, 不能看到别人的
            if ($searchParam['check_status'] == 0) {
                $dealRecordWhere['created_by'] = $userInfo['id'];
            }

            $dealRecordWhere['check_status'] = $searchParam['check_status'];
        } else {
            // 没有设置搜索审核状态的条件
            // 能看到 所有已提交 + 自己的待提交
            $specialSearch = true;
        }

        $dealRecordModel = new DealRecord();
        $dealRecordList = $dealRecordModel->getList($dealRecordWhere, ['id', 'user_name', 'class_phone', 'deduction_money', 'remain_money', 'repay_money', 'deal_goods', 'reception_name', 'deal_date', 'department', 'province_name', 'status', 'is_set_express', 'status_remark', 'check_status', 'check_remark', 'is_court'], $searchParam['page_size'], 'id', 'DESC', $dealRecordWhereIn, $userInfo, $specialSearch);

        if (!empty($searchParam['export_type'])) {
//            if (empty($dealRecordList['total'])) {
//                $result['msg'] = '暂无可导出的记录';
//                return $result;
//            }

            switch ($searchParam['export_type']) {
                case 1:// 导出
                    $this->exportAllDealRecordHandle($dealRecordWhere,$dealRecordWhereIn, $userInfo, $specialSearch);
                    exit();
                case 2:// 导出给财务
                    $this->exportDealRecordToFinanceHandle($dealRecordWhere,$dealRecordWhereIn, $userInfo, $specialSearch);
                    exit();
                default:
                    $result['msg'] = '不支持的导出';
                    return $result;
            }
        }

        // 拿到当前页面所有的id, 去获取学员信息
        $dealRecordIds = array_column($dealRecordList['data']['data'] ?? [], 'id');
        $dealRecordUserModel = new DealRecordUser();
        $dealRecordUserInfos = $dealRecordUserModel->selectDataByWhereFieldAndIds([], 'deal_record_id', $dealRecordIds, ['id', 'deal_record_id', 'deal_record_no', 'refund_money', 'returned_money', 'remain_money', 'system_status', 'is_court']);

        // 拿到所有的学员信息id, 去获取抵扣信息
        $dealRecordUserIds = array_column($dealRecordUserInfos, 'id');
        $dealRecordGoodsModel = new DealRecordGoods();
        $dealRecordGoodsInfos = $dealRecordGoodsModel->selectDataByWhereFieldAndIds([], 'deal_record_user_id', $dealRecordUserIds, ['id', 'deal_record_id', 'deal_record_user_id', 'goods_name', 'order_no', 'buy_number', 'goods_spec', 'deduction_money', 'post_address', 'deliver_type', 'deliver_status', 'express_no']);

        $userRelatedGoods = [];
        foreach ($dealRecordGoodsInfos as $dealRecordGoodsInfo) {
            if (!isset($userRelatedGoods[$dealRecordGoodsInfo['deal_record_user_id']])) {
                $userRelatedGoods[$dealRecordGoodsInfo['deal_record_user_id']] = [];
            }

            $userRelatedGoods[$dealRecordGoodsInfo['deal_record_user_id']][] = $dealRecordGoodsInfo;
        }

        $dealRecordRelatedUser = [];
        foreach ($dealRecordUserInfos as $dealRecordUserInfo) {
            if (!isset($dealRecordRelatedUser[$dealRecordUserInfo['deal_record_id']])) {
                $dealRecordRelatedUser[$dealRecordUserInfo['deal_record_id']] = [];
            }

            $dealRecordUserInfo['deal_record_goods'] = $userRelatedGoods[$dealRecordUserInfo['id']] ?? [];
            $dealRecordRelatedUser[$dealRecordUserInfo['deal_record_id']][] = $dealRecordUserInfo;
        }

        if (!empty($dealRecordList['data']['data'])) {
            foreach ($dealRecordList['data']['data'] as $index => $dealRecord) {
                $dealRecordList['data']['data'][$index]['deal_record_user'] = $dealRecordRelatedUser[$dealRecord['id']] ?? [];
            }
        }

        $result['res'] = true;
        $result['data']['page'] = $searchParam['page'];
        $result['data']['page_size'] = $searchParam['page_size'];
        $result['data']['total'] = $dealRecordList['data']['total'] ?? 0;
        $result['data']['list'] = $dealRecordList['data']['data'] ?? [];
        $result['data']['page_total_price'] = round(array_sum(array_column($result['data']['list'] ?? [], 'deduction_money')), 2);
        $result['data']['total_price'] = round($dealRecordList['total'] ?? 0, 2);
        $result['data']['court_total_price'] = round($dealRecordList['court_total'] ?? 0, 2);
        $result['data']['not_court_total_price'] = round(($result['data']['total_price'] - $result['data']['court_total_price']), 2);
        return $result;
    }

    // 导出
    protected function exportAllDealRecordHandle($dealRecordWhere, $dealRecordWhereIn, $userInfo, $specialSearch) {
        // 设置表头
        $title = $this->exportDealRecordTitle;

        $dealRecordUserModel = new DealRecordUser();
        $dealRecordGoodsModel = new DealRecordGoods();
        $goodsModel = new Goods();
        $courseModel = new Course();
        $dealRecordWhere['deleted_at'] = null;
//        $dealRecordWhere['id'] = 74;
//        $dealRecordWhere['created_at'] = '2024-11-05 17:21:48';

        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->setTitle('抵扣记录');

        // 标题栏字母初始化
        $firstLevel = range('A', 'Z');
        // 标题栏结果初始化
        $titleCell = $firstLevel;

        //定义字母循环的次数
        $loopNum = 7;//8*26即为导出的列数上限
        for ($i = 0; $i < $loopNum; $i++) {
            foreach ($firstLevel as $firstValue) {
                $titleCell[] = $firstLevel[$i] . $firstValue;
            }
        }

        //根据列数获取对应的单元格索引
        $cellIndexArr = array_slice($titleCell, 0, count($title));

        // 设置标题
        foreach ($cellIndexArr as $cellIndex => $cellValue) {
            $worksheet->setcellvalue($cellValue . '1', $title[$cellIndex]);

            // 设置宽度30写死
            $worksheet->getColumnDimension($cellValue)->setWidth(20);
        }

        $totalNum = 1;

        // 获取
        $dealRecordOrm = DB::table('yh_deal_record')->where($dealRecordWhere);
        if(!empty($dealRecordWhereIn['province_name'])){
            $dealRecordOrm = $dealRecordOrm->whereIn('province_name', $dealRecordWhereIn['province_name']);
        }

        // 能看到 所有已提交 + 自己的待提交
        if ($specialSearch) {
            $dealRecordOrm = $dealRecordOrm->where(function ($query) use ($userInfo) {
                $query->where('check_status', '>', 0)
                    ->orWhere(function ($query) use ($userInfo) {
                        $query->where('check_status', 0)->where('created_by', $userInfo['id']);
                    });
            });
        }

        $dealRecordOrm->chunkById(100, function($list) use (&$totalNum, &$worksheet, $dealRecordUserModel, $dealRecordGoodsModel, $goodsModel, $courseModel, $cellIndexArr){
            $dealRecordList = $list->toArray();

            // 拿到当前页面所有的主键id, 去获取所有的交易记录学员信息
            $dealRecordIds = array_unique(array_column($dealRecordList, 'id'));
            $dealRecordUserInfos = $dealRecordUserModel->selectDataByWhereFieldAndIds(['deleted_at' => null], 'deal_record_id', $dealRecordIds, ['*']);
            // 以deal_record_id为key,归类
            $dealRecordRelatedUserInfo = [];
            foreach ($dealRecordUserInfos as $info) {
                if (!isset($dealRecordRelatedUserInfo[$info['deal_record_id']])) {
                    $dealRecordRelatedUserInfo[$info['deal_record_id']] = [];
                }

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

            // 拿到所有的交易记录学员id,去获取交易记录商品信息
            $dealRecordUserIds = array_unique(array_column($dealRecordUserInfos, 'id'));
            $dealRecordGoodsInfos = $dealRecordGoodsModel->selectDataByWhereFieldAndIds(['deleted_at' => null], 'deal_record_user_id', $dealRecordUserIds, ['*']);
            // 以deal_record_user_id为key,归类
            $dealRecordUserRelatedGoodsInfo = [];
            foreach ($dealRecordGoodsInfos as $info) {
                if (!isset($dealRecordUserRelatedGoodsInfo[$info['deal_record_user_id']])) {
                    $dealRecordUserRelatedGoodsInfo[$info['deal_record_user_id']] = [];
                }

                $dealRecordUserRelatedGoodsInfo[$info['deal_record_user_id']][] = $info;
            }

            // 拿到所有的商品信息
            $allGoodsNames = array_unique(array_column($dealRecordGoodsInfos, 'goods_name'));
            $allGoodsInfos = [];
            if (!empty($allGoodsNames)) {
                $originGoodsInfos = $goodsModel->selectDataByWhereFieldAndIds(['deleted_at' => null], 'goods_name', $allGoodsNames, ['*']);
                $allGoodsInfos = array_column($originGoodsInfos, null, 'goods_name');

                // 拿到所有的course_id, 去获取关联的产品售价
                $courseIds = array_unique(array_filter(array_column($originGoodsInfos, 'course_id')));
                if (!empty($courseIds)) {
                    $originCourseInfos = $courseModel->selectDataByWhereFieldAndIds(['deleted_at' => null], 'id', $courseIds, ['*']);
                    $courseIdRelatedSalePrice = array_column($originCourseInfos, 'sale_price', 'id');

                    foreach ($allGoodsInfos as $index => $value) {
                        if (!empty($value['course_id'])) {
                            $allGoodsInfos[$index]['sale_price'] = $courseIdRelatedSalePrice[$value['course_id']] ?? 0;
                        }
                    }
                }
            }

            // 设置标题+内容
            foreach ($dealRecordList as $dealRecordInfo) {
                // 交易记录信息
                $dealRecordInfo = (array)$dealRecordInfo;
                // 交易记录用户信息
                $dealRecordUserInfo = $dealRecordRelatedUserInfo[$dealRecordInfo['id']];

                $dealRecordProtocolUrlArr = array_filter(explode(',', trim($dealRecordInfo['protocol_url'], ' ,')));
                $protocolIndex = 0;

                $exportDealRecordInfo = [];
                $exportDealRecordInfo[0] = $dealRecordInfo['deal_date'];
                $exportDealRecordInfo[1] = $dealRecordInfo['reception_name'];
                $exportDealRecordInfo[2] = $this->dealRecordIdRelatedDepartment[$dealRecordInfo['department']] ?? '';
                $exportDealRecordInfo[3] = $dealRecordInfo['province_name'];
                $exportDealRecordInfo[4] = '';
                $exportDealRecordInfo[5] = $dealRecordInfo['user_name'];
                $exportDealRecordInfo[6] = str_replace('.00', '', $dealRecordInfo['deduction_money']);
                $exportDealRecordInfo[7] = str_replace('.00', '', $dealRecordInfo['remain_money']);
                $exportDealRecordInfo[8] = $dealRecordInfo['repay_money'];
                $exportDealRecordInfo[9] = $dealRecordInfo['deal_goods'];
                $exportDealRecordInfo[10] = '';
                $exportDealRecordInfo[11] = $dealRecordInfo['class_phone'];
                $exportDealRecordInfo[12] = ($dealRecordInfo['is_court'] == 0) ? '否' : '是';
                $exportDealRecordInfo[13] = '';
                $exportDealRecordInfo[14] = '';
                $exportDealRecordInfo[15] = '';
                $exportDealRecordInfo[16] = '';
                $exportDealRecordInfo[17] = '';
                $exportDealRecordInfo[18] = '';
                $exportDealRecordInfo[19] = '';
                $exportDealRecordInfo[20] = '';
                $exportDealRecordInfo[21] = '';
                $exportDealRecordInfo[22] = '';
                $exportDealRecordInfo[23] = '';
                $exportDealRecordInfo[24] = '';
                $exportDealRecordInfo[25] = '';
                $exportDealRecordInfo[26] = '';
                $exportDealRecordInfo[27] = '';

                $stepIndex = $totalNum + 1;
                $beginIndex = $stepIndex;

                // 需要合并的单号起始行
                $mergeNoBeginLine = $beginIndex;

                $goodsNumber = 0;
                $systemStatusArr = [];
                $deliverType = [];
                $deliverStatus = [];
                $addressArr = [];
                $expressNoArr = [];
                foreach ($dealRecordUserInfo as $userIndex => $userInfo) {
                    $exportDealRecordInfo[4] = $userInfo['deal_record_no'];
                    $exportDealRecordInfo[10] = $this->dealRecordSystemStatusRelatedName[$userInfo['system_status']] ?? '';
                    $systemStatusArr[] = $exportDealRecordInfo[10];
                    $exportDealRecordInfo[14] = str_replace('.00', '', $userInfo['refund_money']);
                    $exportDealRecordInfo[15] = str_replace('.00', '', $userInfo['returned_money']);
                    $exportDealRecordInfo[16] = str_replace('.00', '', $userInfo['remain_money']);
                    $exportDealRecordInfo[17] = '';
                    $exportDealRecordInfo[18] = '';
                    $exportDealRecordInfo[19] = '';
                    $exportDealRecordInfo[20] = '';
                    $exportDealRecordInfo[21] = '';
                    $exportDealRecordInfo[22] = '';
                    $exportDealRecordInfo[23] = '';
                    $exportDealRecordInfo[24] = '';
                    $exportDealRecordInfo[25] = '';
                    $exportDealRecordInfo[26] = '';
                    $exportDealRecordInfo[27] = '';

                    // 交易记录商品信息
                    $dealRecordGoodsInfo = $dealRecordUserRelatedGoodsInfo[$userInfo['id']] ?? [];
                    $goodsNumber += count($dealRecordGoodsInfo);

                    // 没有商品信息,只填充主信息+学员信息
                    if (empty($dealRecordGoodsInfo)) {
                        $exportDealRecordInfo[13] = $dealRecordProtocolUrlArr[$protocolIndex] ?? '';

                        foreach ($cellIndexArr as $cellIndex => $cellValue) {
                            // 金额设置为文本格式
                            if (in_array($cellValue, ['G', 'H', 'I', 'O', 'P', 'Q', 'AB'])) {
                                $worksheet->getCell($cellValue . $stepIndex)->setValueExplicit(str_replace('.00', '', $exportDealRecordInfo[$cellIndex]),\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING2);
                            } else {
                                $worksheet->setcellvalue($cellValue . $stepIndex, $exportDealRecordInfo[$cellIndex]);

                                // 设置超链接
                                if ($cellValue == 'N' && !empty($exportDealRecordInfo[13])) {
                                    $worksheet->getCell($cellValue . $stepIndex)->getHyperlink()->setUrl($exportDealRecordInfo[13]);
                                    $protocolIndex++;
                                }
                            }
                        }

                        $stepIndex++;
                        $totalNum++;
                    } else {
                        foreach ($dealRecordGoodsInfo as $goodsIndex => $goodsInfo) {
                            $exportDealRecordInfo[13] = $dealRecordProtocolUrlArr[$protocolIndex] ?? '';
                            $exportDealRecordInfo[17] = $goodsInfo['order_no'];
                            $exportDealRecordInfo[18] = $goodsInfo['goods_name'];
                            $exportDealRecordInfo[19] = round($allGoodsInfos[$goodsInfo['goods_name']]['price'] ?? 0, 2);
                            $exportDealRecordInfo[20] = round($allGoodsInfos[$goodsInfo['goods_name']]['sale_price'] ?? 0, 2);
                            $exportDealRecordInfo[21] = $goodsInfo['buy_number'];
                            $exportDealRecordInfo[22] = $goodsInfo['goods_spec'];
                            $exportDealRecordInfo[23] = str_replace('.00', '', $goodsInfo['deduction_money']);
                            $exportDealRecordInfo[24] = $this->dealRecordIdRelatedDeliverType[$goodsInfo['deliver_type']] ?? '';
                            $deliverType[] = $exportDealRecordInfo[24];
                            $exportDealRecordInfo[25] = $this->dealRecordIdRelatedDeliverStatus[$goodsInfo['deliver_status']] ?? '';
                            $deliverStatus[] = $exportDealRecordInfo[25];
                            $exportDealRecordInfo[26] = $goodsInfo['post_address'];
                            $addressArr[] = $exportDealRecordInfo[26];
                            $exportDealRecordInfo[27] = $goodsInfo['express_no'];
                            $expressNoArr[] = $exportDealRecordInfo[27];

                            foreach ($cellIndexArr as $cellIndex => $cellValue) {
                                // 金额设置为文本格式
                                if (in_array($cellValue, ['G', 'H', 'I', 'O', 'P', 'Q', 'AB'])) {
                                    $worksheet->getCell($cellValue . $stepIndex)->setValueExplicit(str_replace('.00', '', $exportDealRecordInfo[$cellIndex]),\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING2);
                                } else {
                                    $worksheet->setcellvalue($cellValue . $stepIndex, $exportDealRecordInfo[$cellIndex]);

                                    // 设置超链接
                                    if ($cellValue == 'N' && !empty($exportDealRecordInfo[13])) {
                                        $worksheet->getCell($cellValue . $stepIndex)->getHyperlink()->setUrl($exportDealRecordInfo[13]);
                                        $worksheet->getStyle($cellValue . $stepIndex)->getFont()->getColor()->setARGB('40b7ff');
                                        $protocolIndex++;
                                    }
                                }
                            }

                            $stepIndex++;
                            $totalNum++;
                        }

                        // 商品多于单号, 合并单号
                        if (count($dealRecordGoodsInfo) > 1) {
                            $mergeNoEndLine = $mergeNoBeginLine + count($dealRecordGoodsInfo) - 1;

                            $worksheet->mergeCells('E' . $mergeNoBeginLine . ':E' . $mergeNoEndLine);
                            $worksheet->mergeCells('O' . $mergeNoBeginLine . ':O' . $mergeNoEndLine);
                            $worksheet->mergeCells('P' . $mergeNoBeginLine . ':P' . $mergeNoEndLine);
                            $worksheet->mergeCells('Q' . $mergeNoBeginLine . ':Q' . $mergeNoEndLine);
                        }
                        $mergeNoBeginLine += count($dealRecordGoodsInfo);
                    }
                }

                // 如果协议数量超过了总行数,继续添加主信息+协议的行
                if ($protocolIndex < count($dealRecordProtocolUrlArr)) {
                    $exportDealRecordInfo = [];
                    $exportDealRecordInfo[0] = $dealRecordInfo['deal_date'];
                    $exportDealRecordInfo[1] = $dealRecordInfo['reception_name'];
                    $exportDealRecordInfo[2] = $this->dealRecordIdRelatedDepartment[$dealRecordInfo['department']] ?? '';
                    $exportDealRecordInfo[3] = $dealRecordInfo['province_name'];
                    $exportDealRecordInfo[4] = '';
                    $exportDealRecordInfo[5] = $dealRecordInfo['user_name'];
                    $exportDealRecordInfo[6] = '';
                    $exportDealRecordInfo[7] = '';
                    $exportDealRecordInfo[8] = '';
                    $exportDealRecordInfo[9] = '';
                    $exportDealRecordInfo[10] = '';
                    $exportDealRecordInfo[11] = $dealRecordInfo['class_phone'];
                    $exportDealRecordInfo[12] = ($dealRecordInfo['is_court'] == 0) ? '否' : '是';

                    for ($i = $protocolIndex; $i < count($dealRecordProtocolUrlArr); $i++) {
                        $exportDealRecordInfo[13] = $dealRecordProtocolUrlArr[$i] ?? '';

                        foreach ($cellIndexArr as $cellIndex => $cellValue) {
                            $worksheet->setcellvalue($cellValue . $stepIndex, $exportDealRecordInfo[$cellIndex] ?? '');

                            // 设置超链接
                            if ($cellValue == 'N' && !empty($exportDealRecordInfo[13])) {
                                $worksheet->getCell($cellValue . $stepIndex)->getHyperlink()->setUrl($exportDealRecordInfo[13]);
                                $worksheet->getStyle($cellValue . $stepIndex)->getFont()->getColor()->setARGB('40b7ff');
                            }
                        }

                        $stepIndex++;
                        $totalNum++;
                    }
                }

                // 合并某些单元格
                if ($stepIndex - $beginIndex > 1) {
                    $worksheet->mergeCells('A' . $beginIndex . ':A' . ($stepIndex - 1));
                    $worksheet->mergeCells('B' . $beginIndex . ':B' . ($stepIndex - 1));
                    $worksheet->mergeCells('C' . $beginIndex . ':C' . ($stepIndex - 1));
                    $worksheet->mergeCells('D' . $beginIndex . ':D' . ($stepIndex - 1));
                    $worksheet->mergeCells('F' . $beginIndex . ':F' . ($stepIndex - 1));
                    $worksheet->mergeCells('G' . $beginIndex . ':G' . ($stepIndex - 1));
                    $worksheet->mergeCells('H' . $beginIndex . ':H' . ($stepIndex - 1));
                    $worksheet->mergeCells('I' . $beginIndex . ':I' . ($stepIndex - 1));
                    $worksheet->mergeCells('J' . $beginIndex . ':J' . ($stepIndex - 1));
                    $worksheet->mergeCells('L' . $beginIndex . ':L' . ($stepIndex - 1));
                    $worksheet->mergeCells('M' . $beginIndex . ':M' . ($stepIndex - 1));

                    // 如果只有一个单号,合并某些行
                    if (count($dealRecordUserInfo) == 1) {
                        $worksheet->mergeCells('E' . $beginIndex . ':E' . ($stepIndex - 1));
                        $worksheet->mergeCells('G' . $beginIndex . ':G' . ($stepIndex - 1));
                        $worksheet->mergeCells('H' . $beginIndex . ':H' . ($stepIndex - 1));
                        $worksheet->mergeCells('I' . $beginIndex . ':I' . ($stepIndex - 1));
                        $worksheet->mergeCells('K' . $beginIndex . ':K' . ($stepIndex - 1));
                        $worksheet->mergeCells('O' . $beginIndex . ':O' . ($stepIndex - 1));
                        $worksheet->mergeCells('P' . $beginIndex . ':P' . ($stepIndex - 1));
                        $worksheet->mergeCells('Q' . $beginIndex . ':Q' . ($stepIndex - 1));
                    }

                    // 如果只有一个商品,合并某些行
                    if ($goodsNumber == 1) {
                        $worksheet->mergeCells('R' . $beginIndex . ':R' . ($stepIndex - 1));
                        $worksheet->mergeCells('S' . $beginIndex . ':S' . ($stepIndex - 1));
                        $worksheet->mergeCells('T' . $beginIndex . ':T' . ($stepIndex - 1));
                        $worksheet->mergeCells('U' . $beginIndex . ':U' . ($stepIndex - 1));
                        $worksheet->mergeCells('V' . $beginIndex . ':U' . ($stepIndex - 1));
                        $worksheet->mergeCells('W' . $beginIndex . ':W' . ($stepIndex - 1));
                        $worksheet->mergeCells('X' . $beginIndex . ':X' . ($stepIndex - 1));
                        $worksheet->mergeCells('Y' . $beginIndex . ':Y' . ($stepIndex - 1));
                        $worksheet->mergeCells('Z' . $beginIndex . ':Z' . ($stepIndex - 1));
                        $worksheet->mergeCells('AA' . $beginIndex . ':AA' . ($stepIndex - 1));
                        $worksheet->mergeCells('AB' . $beginIndex . ':AB' . ($stepIndex - 1));
                    }

                    // 如果只有一个协议,合并某些行
                    if (count($dealRecordProtocolUrlArr) == 1) {
                        $worksheet->mergeCells('N' . $beginIndex . ':N' . ($stepIndex - 1));
                    }

                    // 标记点付超过多个,合并某些行
                    if (count(array_unique($systemStatusArr)) == 1) {
                        $worksheet->mergeCells('K' . $beginIndex . ':K' . ($stepIndex - 1));
                    }

                    // 交付方式
                    if (count(array_unique($deliverType)) == 1) {
                        $worksheet->mergeCells('Y' . $beginIndex . ':Y' . ($stepIndex - 1));
                    }

                    // 交付状态
                    if (count(array_unique($deliverStatus)) == 1) {
                        $worksheet->mergeCells('Z' . $beginIndex . ':Z' . ($stepIndex - 1));
                    }

                    // 地址
                    if (count(array_unique($addressArr)) == 1) {
                        $worksheet->mergeCells('AA' . $beginIndex . ':AA' . ($stepIndex - 1));
                    }

                    // 快递单号
                    if (count(array_unique($expressNoArr)) == 1) {
                        $worksheet->mergeCells('AB' . $beginIndex . ':AB' . ($stepIndex - 1));
                    }
                }
            }
        });

        $worksheet->getStyle('A1:' . end($cellIndexArr) . $totalNum)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,);
        $worksheet->getStyle('A1:' . end($cellIndexArr) . $totalNum)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,);
        $worksheet->getStyle('A1:' . end($cellIndexArr) . $totalNum)->applyFromArray([
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, // 边框样式
                    'color' => ['argb' => \PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLACK], // 边框颜色
                ],
            ],
        ]);

        // 自动换行
        $worksheet->getStyle('J1:J' . $totalNum)->getAlignment()->setWrapText(true);
        $worksheet->getStyle('AA1:AA' . $totalNum)->getAlignment()->setWrapText(true);

        // 设置首行背景色
        $worksheet->getStyle('A1:AB1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('4096ff');

        // 设置首行字体
        $worksheet->getStyle('A1:AB1')->getFont()->setSize(13)->setBold(true);

        $randomFile = getRandomChars('', 10);
        $filename = '交易记录导出-' . date('Ymd') . '-' . $randomFile . '.xlsx';

        header("Access-Control-Allow-Origin: *");
        header('Content-Type: application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

    // 导出给财务
    protected function exportDealRecordToFinanceHandle($dealRecordWhere, $dealRecordWhereIn, $userInfo, $specialSearch) {
        // 设置表头
        $title = ['接待日期', '省份', '单号', '学员姓名', '抵扣总金额', '抵扣内容', '是否标记', '补款金额'];

        $dealRecordUserModel = new DealRecordUser();
        $dealRecordWhere['deleted_at'] = null;

        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->setTitle('抵扣记录');

        // 标题栏字母初始化
        $firstLevel = range('A', 'Z');
        // 标题栏结果初始化
        $titleCell = $firstLevel;

        //定义字母循环的次数
        $loopNum = 7;//8*26即为导出的列数上限
        for ($i = 0; $i < $loopNum; $i++) {
            foreach ($firstLevel as $firstValue) {
                $titleCell[] = $firstLevel[$i] . $firstValue;
            }
        }

        //根据列数获取对应的单元格索引
        $cellIndexArr = array_slice($titleCell, 0, count($title));

        // 设置标题
        foreach ($cellIndexArr as $cellIndex => $cellValue) {
            $worksheet->setcellvalue($cellValue . '1', $title[$cellIndex]);

            // 设置宽度30写死
            $worksheet->getColumnDimension($cellValue)->setWidth(30);
        }

        $totalNum = 1;

        // 获取
        $dealRecordOrm = DB::table('yh_deal_record')->where($dealRecordWhere);
        if(!empty($dealRecordWhereIn['province_name'])){
            $dealRecordOrm = $dealRecordOrm->whereIn('province_name', $dealRecordWhereIn['province_name']);
        }

        // 能看到 所有已提交 + 自己的待提交
        if ($specialSearch) {
            $dealRecordOrm = $dealRecordOrm->where(function ($query) use ($userInfo) {
                $query->where('check_status', '>', 0)
                    ->orWhere(function ($query) use ($userInfo) {
                        $query->where('check_status', 0)->where('created_by', $userInfo['id']);
                    });
            });
        }

        $dealRecordOrm->chunkById(100, function($list) use (&$totalNum, &$worksheet, $dealRecordUserModel, $cellIndexArr){
            $dealRecordList = $list->toArray();

            // 拿到当前页面所有的主键id, 去获取所有的交易记录学员信息
            $dealRecordIds = array_unique(array_column($dealRecordList, 'id'));
            $dealRecordUserInfos = $dealRecordUserModel->selectDataByWhereFieldAndIds(['deleted_at' => null], 'deal_record_id', $dealRecordIds, ['*']);

            // 以deal_record_id为key,归类
            $dealRecordRelatedUserInfo = [];
            foreach ($dealRecordUserInfos as $info) {
                if (!isset($dealRecordRelatedUserInfo[$info['deal_record_id']])) {
                    $dealRecordRelatedUserInfo[$info['deal_record_id']] = [];
                }

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

            // 设置标题+内容
            foreach ($dealRecordList as $dealRecordInfo) {
                // 交易记录信息
                $dealRecordInfo = (array)$dealRecordInfo;
                // 交易记录用户信息
                $dealRecordUserInfo = $dealRecordRelatedUserInfo[$dealRecordInfo['id']];

                $cellTitleIndex = $totalNum + 1;

                foreach ($dealRecordUserInfo as $i => $userInfo) {
                    $setValueIndex = $cellTitleIndex + $i;

                    $exportDealRecordInfo = [
                        $dealRecordInfo['deal_date'],
                        $dealRecordInfo['province_name'],
                        $userInfo['deal_record_no'],
                        $dealRecordInfo['user_name'],
                        $dealRecordInfo['deduction_money'],
                        $dealRecordInfo['deal_goods'],
                        ($userInfo['system_status'] == 1) ? '已标记' : '已点付',
                        $dealRecordInfo['repay_money'],
                    ];

                    foreach ($cellIndexArr as $cellIndex => $cellValue) {
                        // 抵扣总金额这一列设置为文本格式
                        if ($cellValue == 'E' || $cellValue == 'H') {
                            $worksheet->getCell($cellValue . $setValueIndex)->setValueExplicit(str_replace('.00', '', $exportDealRecordInfo[$cellIndex]),\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING2);
                        } else {
                            $worksheet->setcellvalue($cellValue . $setValueIndex, $exportDealRecordInfo[$cellIndex]);
                        }
                    }
                }

                // 需要合并单元格
                if (count($dealRecordUserInfo) > 1) {
                    $worksheet->mergeCells('A' . $cellTitleIndex . ':A' . ($cellTitleIndex + count($dealRecordUserInfo) - 1));
                    $worksheet->mergeCells('B' . $cellTitleIndex . ':B' . ($cellTitleIndex + count($dealRecordUserInfo) - 1));
                    $worksheet->mergeCells('D' . $cellTitleIndex . ':D' . ($cellTitleIndex + count($dealRecordUserInfo) - 1));
                    $worksheet->mergeCells('E' . $cellTitleIndex . ':E' . ($cellTitleIndex + count($dealRecordUserInfo) - 1));
                    $worksheet->mergeCells('F' . $cellTitleIndex . ':F' . ($cellTitleIndex + count($dealRecordUserInfo) - 1));
                    $worksheet->mergeCells('H' . $cellTitleIndex . ':H' . ($cellTitleIndex + count($dealRecordUserInfo) - 1));
                }

                $totalNum += count($dealRecordUserInfo);
            }
        });

        $worksheet->getStyle('A1:' . end($cellIndexArr) . $totalNum)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,);
        $worksheet->getStyle('A1:' . end($cellIndexArr) . $totalNum)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,);
        $worksheet->getStyle('A1:' . end($cellIndexArr) . $totalNum)->applyFromArray([
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, // 边框样式
                    'color' => ['argb' => \PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLACK], // 边框颜色
                ],
            ],
        ]);

        // 设置首行背景色
        $worksheet->getStyle('A1:H1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('4096ff');

        // 设置首行字体
        $worksheet->getStyle('A1:H1')->getFont()->setSize(13)->setBold(true);

        $randomFile = getRandomChars('', 10);
        $filename = '交易记录导出财务-' . date('Ymd') . '-' . $randomFile . '.xlsx';

        header("Access-Control-Allow-Origin: *");
        header('Content-Type: application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

    public function getDealInfoHandle($dealRecordId) {
        $result = [
            'res' => false,
            'msg' => '获取成功',
            'data' => [],
        ];

        if ($dealRecordId <= 0) {
            $result['msg'] = 'deal_record_id异常';
            return $result;
        }

        $resultData = [];

        // 获取交易记录信息
        $dealRecordModel = new DealRecord();
        $dealRecordInfo = $dealRecordModel->findDataWithField(['id' => $dealRecordId], ['id', 'user_name', 'class_phone', 'deduction_money', 'remain_money', 'repay_money', 'deal_goods', 'reception_name', 'deal_date', 'department', 'province_name', 'protocol_url', 'protocol_file_url', 'status', 'status_remark', 'created_by', 'origin', 'created_at']);
        if (empty($dealRecordInfo)) {
            $result['msg'] = '交易记录信息不存在';
            return $result;
        }
        $resultData['main_info'] = $dealRecordInfo;

        // 获取学员信息
        $dealRecordUserModel = new DealRecordUser();
        $dealRecordUserInfos = $dealRecordUserModel->selectDataWithField(['deal_record_id' => $dealRecordId], ['id', 'deal_record_no', 'refund_money', 'returned_money', 'remain_money', 'system_status', 'is_court']);
        $resultData['user_info'] = $dealRecordUserInfos ?? [];

        // 获取抵扣信息
        $dealRecordGoodsModel = new DealRecordGoods();
        $dealRecordGoodsInfos = $dealRecordGoodsModel->selectDataWithField(['deal_record_id' => $dealRecordId], ['id', 'goods_name', 'order_no', 'buy_number', 'goods_spec', 'deduction_money', 'post_address', 'deliver_type', 'deliver_status', 'express_no']);
        $resultData['deal_info'] = $dealRecordGoodsInfos ?? [];

        // 开始获取交易记录的操作信息
        // 日志需要返回的信息包括: 操作时间, 操作人, 操作名称
        $operatorLogs = (new LogModel())->selectDataWithField(['url' => '交易记录', 'object_id' => $dealRecordId], ['*']);
        // 拿到所有的操作人id,去获取操作人的姓名
        $operatorIds = array_unique(array_filter(array_column($operatorLogs, 'operator')));
        $operatorIds[] = $dealRecordInfo['created_by'];
        $allOperatorInfo = (new AdminUserModel())->selectDataByIdsTrashed($operatorIds, ['id', 'user_name']);
        $operatorIdRelatedName = array_column($allOperatorInfo, 'user_name', 'id');

        $logData = [$dealRecordInfo['created_at'] . '-' . ($operatorIdRelatedName[$dealRecordInfo['created_by']] ?? '未知') . '-' . ($dealRecordInfo['origin'] == 1 ? '在线录入' : 'excel导入')];

        foreach ($operatorLogs as $operatorLog) {
            $operatorMsg = $operatorLog['created_at'] . '-' . ($operatorIdRelatedName[$operatorLog['operator']] ?? '未知') . '-' . $operatorLog['operate_name'];

            if ($operatorLog['operate_name'] == '审核/驳回') {
                $operatorContent = json_decode($operatorLog['content'], true);
                if (isset($operatorContent['data']['check_status'])) {
                    if ($operatorContent['data']['check_status'] == 3) {
                        $operatorMsg .= ', 驳回原因: ' . $operatorContent['data']['check_remark'] ?? '未知';
                    } else if ($operatorContent['data']['check_status'] == 2) {
                        $operatorMsg .= ', 审核通过';
                    }
                }
            }

            $logData[] = $operatorMsg;
        }
        $resultData['operate_log'] = $logData;

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

    public function checkUpdateDealHandle($dealInfo) {
        $result = [
            'res' => false,
            'msg' => '校验成功',
            'data' => [],
        ];

        $checkResult = $this->checkAddDealHandle($dealInfo);
        if (empty($checkResult['res'])) {
            $result['msg'] = $checkResult['msg'];
            return $result;
        }

        if (!isset($dealInfo['deal_record_id']) || !is_numeric($dealInfo['deal_record_id']) || $dealInfo['deal_record_id'] <= 0) {
            $result['msg'] = 'deal_record_id异常';
            return $result;
        }
        $checkResult['data']['deal_record_id'] = intval($dealInfo['deal_record_id']);

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

    public function updateDealHandle($userInfo, $dealInfo) {
        $result = [
            'res' => false,
            'msg' => '保存成功',
            'data' => [],
        ];

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

        DB::beginTransaction();

        // 校验当前交易信息是否存在
        $dealRecordInfo = $dealRecordModel->findDataWithField(['id' => $dealInfo['deal_record_id']]);
        if (empty($dealRecordInfo)) {
            DB::rollBack();
            $result['msg'] = '交易信息不存在';
            return $result;
        }

        // 如果审核通过了,没有审核权限的不允许编辑
        if ($dealRecordInfo['check_status'] == 2 && empty($userInfo['is_review'])) {
            DB::rollBack();
            $result['msg'] = '审核已通过,您无编辑权限,请联系管理员';
            return $result;
        }

        // 先添加抵扣的主要信息
        $mainInfo = $dealInfo['main_info'] ?? [];
        $dealUserInfo = $dealInfo['user_info'] ?? [];
        $dealGoodsInfo = $dealInfo['deal_info'] ?? [];

        // 校验商品是否存在
        $goodsNames = array_column($dealGoodsInfo, 'goods_name');
        $goodsNames = array_unique(array_filter($goodsNames));
        $existGoods = (new Goods)->selectDataByWhereFieldAndIds(['status' => 1, 'deleted_at' => null], 'goods_name', $goodsNames, ['*']);
        $existGoodsInfo = array_unique(array_column($existGoods, 'goods_name'));
        if (count($existGoodsInfo) != count($goodsNames)) {
            DB::rollBack();
            $notExistedGoodsName = array_diff($goodsNames, $existGoodsInfo);
            $result['msg'] = '商品不存在: ' . implode(',', $notExistedGoodsName);
            return $result;
        }

        // 查找当前学员当天的交易记录是否已存在,如果存在需要合并录入
        $dealRecordWhere = [
            'user_name' => $mainInfo['user_name'] ?? '',
            'class_phone' => $mainInfo['class_phone'] ?? '',
            'deal_date' => $dealRecordInfo['deal_date'],
        ];
        $existedDealRecord = $dealRecordModel->selectDataWithField($dealRecordWhere, ['id']);
        if (!empty($existedDealRecord)) {
            if (count($existedDealRecord) > 1) {
                DB::rollBack();
                $result['msg'] = '该学员今日抵扣记录已存在,请合并录入';
                return $result;
            }

            $existedDealRecord = current($existedDealRecord);
            if ($existedDealRecord['id'] != $dealInfo['deal_record_id']) {
                $result['msg'] = '该学员今日抵扣记录已存在,请合并录入';
                return $result;
            }
        }

        $existGoodsRelatedInfo = array_column($existGoods, null, 'goods_name');

        $updateDealRecord = [
            'user_name' => $mainInfo['user_name'] ?? '',
            'class_phone' => $mainInfo['class_phone'] ?? '',
            'deduction_money' => $mainInfo['deduction_money'] ?? 0,
            'remain_money' => $mainInfo['remain_money'] ?? 0,
            'repay_money' => $mainInfo['repay_money'] ?? 0,
            'deal_goods' => $mainInfo['deal_goods'] ?? '',
            'reception_name' => $mainInfo['reception_name'] ?? '',
            'department' => $mainInfo['department'] ?? 0,
            'province_name' => $mainInfo['province_name'] ?? '',
            'protocol_url' => $mainInfo['protocol_url'] ?? '',
            'protocol_file_url' => $mainInfo['protocol_file_url'] ?? '',
        ];

        // 如果当前交易记录是驳回的状态, 改成待审核
        if ($dealRecordInfo['check_status'] == 3) {
            $updateDealRecord['check_status'] = 1;
        }
        $updateDealRecordRes = $dealRecordModel->updateData(['id' => $dealInfo['deal_record_id']], $updateDealRecord);
        if (false === $updateDealRecordRes) {
            DB::rollBack();
            $result['msg'] = '主要信息更新失败';
            return $result;
        }

        // 将该交易信息的已存在的学员信息删除,写入新的
        $deleteDealRecordUserRes = $dealRecordUserModel->deleteData(['deal_record_id' => $dealInfo['deal_record_id']]);
        if (false === $deleteDealRecordUserRes) {
            DB::rollBack();
            $result['msg'] = '学员信息删除失败';
            return $result;
        }

        // 将该交易信息的已存在的抵扣信息删除,写入新的
        $deleteDealRecordGoodsRes = $dealRecordGoodsModel->deleteData(['deal_record_id' => $dealInfo['deal_record_id']]);
        if (false === $deleteDealRecordGoodsRes) {
            DB::rollBack();
            $result['msg'] = '抵扣信息删除失败';
            return $result;
        }

        // 处理一下抵扣信息,抵扣信息平均分散到单号里
        $multiGoodsInfo = [];
        // 是否设置了物流
        $isSetExpress = 0;
        // 商品名称+交付状态
        $containGoodsName = $containDeliverStatus = $containOrderNo = [];
        foreach ($dealGoodsInfo as $v) {
            $tmp = [
                'deal_record_id' => $dealInfo['deal_record_id'],
                'goods_name' => $v['goods_name'] ?? '',
                'order_no' => $v['order_no'] ?? '',
                'buy_number' => $v['buy_number'] ?? 0,
                'goods_spec' => $v['goods_spec'] ?? '',
                'deduction_money' => $v['deduction_money'] ?? 0,
                'post_address' => $v['post_address'] ?? '',
                'deliver_type' => $v['deliver_type'] ?? 0,
                'deliver_status' => $v['deliver_status'] ?? 0,
                'express_no' => $v['express_no'] ?? '',
            ];
            if ($tmp['order_no'] === '') {
                $tmp['order_no'] = $this->generateOrderNo($mainInfo['user_name']);
            }
            $containOrderNo[] = $tmp['order_no'];

            $tmpGoodsInfo = $existGoodsRelatedInfo[$tmp['goods_name'] ?? ''] ?? [];
            $tmp['province_name'] = $tmpGoodsInfo['province_name'] ?? '';
            $tmp['category_name'] = $tmpGoodsInfo['category_name'] ?? '';
            $tmp['supplier_name'] = $tmpGoodsInfo['supplier_name'] ?? '';
            $tmp['model_name'] = $tmpGoodsInfo['model_name'] ?? '';

            $multiGoodsInfo[] = $tmp;

            if (!empty($v['express_no'])) {
                $isSetExpress = 1;
            }

            if (!empty($v['goods_name'])) {
                $containGoodsName[] = $v['goods_name'];
            }

            if (isset($v['deliver_status']) && $v['deliver_status'] !== '') {
                $containDeliverStatus[] = $v['deliver_status'];
            }
        }
        $chunkGoodsInfo = splitArrayByParts($multiGoodsInfo, count($dealUserInfo));

        $updateDealRecordData = [];
        $updateDealRecordData['is_court'] = 0;

        if (!empty($isSetExpress)) {
            $updateDealRecordData['is_set_express'] = 1;
        } else {
            $updateDealRecordData['is_set_express'] = 0;
        }

        if (!empty($containGoodsName)) {
            $containGoodsName = array_unique($containGoodsName);
            $updateDealRecordData['contain_goods_name'] = implode('%%', $containGoodsName);
        } else {
            $updateDealRecordData['contain_goods_name'] = '';
        }

        if (!empty($containDeliverStatus)) {
            $containDeliverStatus = array_unique($containDeliverStatus);
            $updateDealRecordData['contain_deliver_status'] = implode('%%', $containDeliverStatus);
        } else {
            $updateDealRecordData['contain_deliver_status'] = '';
        }

        if (!empty($containOrderNo)) {
            $containOrderNo = array_unique($containOrderNo);
            $updateDealRecordData['contain_order_no'] = implode('%%', $containOrderNo);
        } else {
            $updateDealRecordData['contain_order_no'] = '';
        }

        // 系统状态+单号
        $containSystemStatus = $containDealRecordNo = $containCourt = [];
        foreach ($dealUserInfo as $index => $tmpUserInfo) {
            $insertUserInfo = [
                'deal_record_id' => $dealInfo['deal_record_id'],
                'deal_record_no' => $tmpUserInfo['deal_record_no'] ?? '',
                'refund_money' => $tmpUserInfo['refund_money'] ?? 0,
                'returned_money' => $tmpUserInfo['returned_money'] ?? 0,
                'remain_money' => $tmpUserInfo['remain_money'] ?? 0,
                'system_status' => $tmpUserInfo['system_status'] ?? 0,
                'is_court' => $tmpUserInfo['is_court'] ?? 0,
            ];

            if (!empty($tmpUserInfo['deal_record_no'])) {
                $containDealRecordNo[] = $tmpUserInfo['deal_record_no'];
            }

            if (isset($tmpUserInfo['system_status']) && $tmpUserInfo['system_status'] !== '') {
                $containSystemStatus[] = $tmpUserInfo['system_status'];
            }

            if (isset($tmpUserInfo['is_court']) && $tmpUserInfo['is_court'] !== '') {
                $containCourt[] = $tmpUserInfo['is_court'];

                if (!empty($tmpUserInfo['is_court'])) {
                    $updateDealRecordData['is_court'] = 1;
                }
            }

            $insertUserInfoId = $dealRecordUserModel->insertData($insertUserInfo);
            if (false === $insertUserInfoId) {
                DB::rollBack();
                $result['msg'] = '学员信息写入失败';
                return $result;
            }

            // 该学员信息对应的抵扣信息
            $userRelatedGoodsInfo = $chunkGoodsInfo[$index] ?? [];
            foreach ($userRelatedGoodsInfo as $i => $goods) {
                $userRelatedGoodsInfo[$i]['deal_record_user_id'] = $insertUserInfoId;
            }

            if (!empty($userRelatedGoodsInfo)) {
                $insertGoodsInfoRes = $dealRecordGoodsModel->insertMultiData($userRelatedGoodsInfo);
                if (false === $insertGoodsInfoRes) {
                    DB::rollBack();
                    $result['msg'] = '抵扣信息写入失败';
                    return $result;
                }
            }
        }

        if (!empty($containSystemStatus)) {
            $containSystemStatus = array_unique($containSystemStatus);
            $updateDealRecordData['contain_system_status'] = implode('%%', $containSystemStatus);
        } else {
            $updateDealRecordData['contain_system_status'] = '';
        }

        if (!empty($containCourt)) {
            $containCourt = array_unique($containCourt);
            $updateDealRecordData['contain_court'] = implode('%%', $containCourt);
        } else {
            $updateDealRecordData['contain_court'] = '';
        }

        if (!empty($containDealRecordNo)) {
            $containDealRecordNo = array_unique($containDealRecordNo);
            $updateDealRecordData['contain_deal_record_no'] = implode('%%', $containDealRecordNo);
        } else {
            $updateDealRecordData['contain_deal_record_no'] = '';
        }

        $updateDealRecordRes = $dealRecordModel->updateData(['id' => $dealInfo['deal_record_id']], $updateDealRecordData);
        if (false === $updateDealRecordRes) {
            DB::rollBack();
            $result['msg'] = '主要信息更新失败';
            return $result;
        }

        // 写入日志
        $insertLogRes = (new LogModel())->insertData([
            'operator' => $userInfo['id'],
            'type' => 2,
            'url' => '交易记录',
            'operate_name' => '编辑保存',
            'object_id' => $dealInfo['deal_record_id'],
            'content' => json_encode($dealInfo, JSON_UNESCAPED_UNICODE),
        ]);
        if (false === $insertLogRes) {
            DB::rollBack();
            $result['msg'] = '日志记录失败';
            return $result;
        }

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

    public function deleteDealHandle($userInfo, $dealRecordInfo) {
        $result = [
            'res' => false,
            'msg' => '删除成功',
            'data' => [],
        ];

        if (!isset($dealRecordInfo['deal_record_ids'])) {
            $result['msg'] = 'deal_record_ids异常';
            return $result;
        }

        $dealRecordIdsArr = explode(',', $dealRecordInfo['deal_record_ids']);
        $dealRecordIdsArr = array_filter(array_unique($dealRecordIdsArr));
        if (empty($dealRecordIdsArr)) {
            $result['msg'] = 'deal_record_ids异常';
            return $result;
        }

        foreach ($dealRecordIdsArr as $index => $dealRecordId) {
            if (!is_numeric($dealRecordId) || $dealRecordId <= 0) {
                $result['msg'] = 'deal_record_ids异常';
                return $result;
            }
            $dealRecordIdsArr[$index] = intval($dealRecordId);
        }
        $dealRecordIdsArr = array_unique($dealRecordIdsArr);

        DB::beginTransaction();
        $dealRecordModel = new DealRecord();
        $dealRecordUserModel = new DealRecordUser();
        $dealRecordGoodsModel = new DealRecordGoods();

        // 校验交易信息是否存在
        $existedDealRecordInfo = $dealRecordModel->selectDataByIds($dealRecordIdsArr, ['id', 'check_status']);
        if (count($existedDealRecordInfo) != count($dealRecordIdsArr)) {
            DB::rollBack();
            $result['msg'] = '交易信息不存在';
            return $result;
        }

        // 如果存在审核通过的交易,判断权限,没有权限的不能删除
        $existedCheckDeal = false;
        foreach ($existedDealRecordInfo as $info) {
            if ($info['check_status'] == 2) {
                $existedCheckDeal = true;
                break;
            }
        }
        if ($existedCheckDeal && empty($userInfo['is_review'])) {
            DB::rollBack();
            $result['msg'] = '存在审核通过的记录,您无删除权限,请联系管理员';
            return $result;
        }

        $deleteDealRecordRes = $dealRecordModel->deleteDataByField('id', $dealRecordIdsArr);
        if (false === $deleteDealRecordRes) {
            DB::rollBack();
            $result['msg'] = '删除失败';
            return $result;
        }

        $deleteDealRecordUserRes = $dealRecordUserModel->deleteDataByField('deal_record_id', $dealRecordIdsArr);
        if (false === $deleteDealRecordUserRes) {
            DB::rollBack();
            $result['msg'] = '删除失败';
            return $result;
        }

        $deleteDealRecordGoodsRes = $dealRecordGoodsModel->deleteDataByField('deal_record_id', $dealRecordIdsArr);
        if (false === $deleteDealRecordGoodsRes) {
            DB::rollBack();
            $result['msg'] = '删除失败';
            return $result;
        }

        // 写入日志
        $insertLogRes = (new LogModel())->insertData([
            'operator' => $userInfo['id'],
            'type' => 3,
            'url' => '交易记录',
            'operate_name' => '删除',
            'object_id' => 0,
            'content' => $dealRecordInfo['deal_record_ids'],
        ]);
        if (false === $insertLogRes) {
            DB::rollBack();
            $result['msg'] = '日志记录失败';
            return $result;
        }

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

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

        if (empty($userInfo['is_review'])) {
            $result['msg'] = '您无操作权限,请联系管理员';
            return $result;
        }

        if (!isset($dealRecordInfo['deal_record_ids'])) {
            $result['msg'] = 'deal_record_ids异常';
            return $result;
        }

        if (!isset($dealRecordInfo['invalid_reason']) || mb_strlen($dealRecordInfo['invalid_reason']) == 0 || mb_strlen($dealRecordInfo['invalid_reason']) > 100) {
            $result['msg'] = 'invalid_reason异常';
            return $result;
        }

        $dealRecordIdsArr = explode(',', $dealRecordInfo['deal_record_ids']);
        $dealRecordIdsArr = array_filter(array_unique($dealRecordIdsArr));
        if (empty($dealRecordIdsArr)) {
            $result['msg'] = 'deal_record_ids异常';
            return $result;
        }

        foreach ($dealRecordIdsArr as $index => $dealRecordId) {
            if (!is_numeric($dealRecordId) || $dealRecordId <= 0) {
                $result['msg'] = 'deal_record_ids异常';
                return $result;
            }
            $dealRecordIdsArr[$index] = intval($dealRecordId);
        }
        $dealRecordIdsArr = array_unique($dealRecordIdsArr);

        DB::beginTransaction();

        // 校验交易信息是否存在
        $dealRecordModel = new DealRecord();
        $existedDealRecordInfo = $dealRecordModel->selectDataByIds($dealRecordIdsArr, ['id']);
        if (count($existedDealRecordInfo) != count($dealRecordIdsArr)) {
            DB::rollBack();
            $result['msg'] = '交易信息不存在';
            return $result;
        }

        $updateData = ['status' => 0, 'status_remark' => $dealRecordInfo['invalid_reason']];
        $updateDealRecordRes = $dealRecordModel->updateDataByIds('id', $dealRecordIdsArr, $updateData);
        if (false === $updateDealRecordRes) {
            DB::rollBack();
            $result['msg'] = '操作失败';
            return $result;
        }

        // 写入日志
        $logData = [];
        $tmp = [
            'operator' => $userInfo['id'],
            'type' => 2,
            'url' => '交易记录',
            'operate_name' => '设置无效',
            'content' => json_encode(['data' => $updateData], JSON_UNESCAPED_UNICODE),
        ];
        foreach ($dealRecordIdsArr as $dealRecordId) {
            $tmp['object_id'] = $dealRecordId;
            $logData[] = $tmp;
        }
        $insertLogRes = (new LogModel())->insertMultiData($logData);
        if (false === $insertLogRes) {
            DB::rollBack();
            $result['msg'] = '日志记录失败';
            return $result;
        }

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

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

        if (!isset($dealRecordInfo['system_status']) || !is_numeric($dealRecordInfo['system_status']) || $dealRecordInfo['system_status'] < 0 || $dealRecordInfo['system_status'] > 2) {
            $result['msg'] = '系统状态异常';
            return $result;
        }
        $dealRecordInfo['system_status'] = intval($dealRecordInfo['system_status']);

        if (!isset($dealRecordInfo['deal_record_ids'])) {
            $result['msg'] = 'deal_record_ids异常';
            return $result;
        }

        $dealRecordIdsArr = explode(',', $dealRecordInfo['deal_record_ids']);
        $dealRecordIdsArr = array_filter(array_unique($dealRecordIdsArr));
        if (empty($dealRecordIdsArr)) {
            $result['msg'] = 'deal_record_ids异常';
            return $result;
        }

        foreach ($dealRecordIdsArr as $index => $dealRecordId) {
            if (!is_numeric($dealRecordId) || $dealRecordId <= 0) {
                $result['msg'] = 'deal_record_ids异常';
                return $result;
            }
            $dealRecordIdsArr[$index] = intval($dealRecordId);
        }
        $dealRecordIdsArr = array_unique($dealRecordIdsArr);

        DB::beginTransaction();

        // 校验交易信息是否存在
        $dealRecordModel = new DealRecord();
        $existedDealRecordInfo = $dealRecordModel->selectDataByIds($dealRecordIdsArr, ['*']);
        if (count($existedDealRecordInfo) != count($dealRecordIdsArr)) {
            DB::rollBack();
            $result['msg'] = '交易信息不存在';
            return $result;
        }

        $dealRecordUserModel = new DealRecordUser();
        $updateData = ['system_status' => $dealRecordInfo['system_status']];
        $updateDealRecordUserRes = $dealRecordUserModel->updateDataByIds('deal_record_id', $dealRecordIdsArr, $updateData);
        if (false === $updateDealRecordUserRes) {
            DB::rollBack();
            $result['msg'] = '操作失败';
            return $result;
        }

        // 获取交易记录下所有的学员信息, 更新包含的系统状态
        foreach ($existedDealRecordInfo as $dealRecordInfo) {
            $dealRecordUser = $dealRecordUserModel->selectDataWithField(['deal_record_id' => $dealRecordInfo['id']]);
            $systemStatusArr = array_unique(array_column($dealRecordUser, 'system_status'));
            $updateDealRecordRes = $dealRecordModel->updateData(['id' => $dealRecordInfo['id']], ['contain_system_status' => implode('%%', $systemStatusArr)]);
            if (false === $updateDealRecordRes) {
                DB::rollBack();
                $result['msg'] = '操作失败';
                return $result;
            }
        }

        // 写入日志
        $logData = [];
        $tmp = [
            'operator' => $userInfo['id'],
            'type' => 2,
            'url' => '交易记录',
            'operate_name' => '设置系统状态',
            'content' => json_encode(['data' => $updateData], JSON_UNESCAPED_UNICODE),
        ];
        foreach ($dealRecordIdsArr as $dealRecordId) {
            $tmp['object_id'] = $dealRecordId;
            $logData[] = $tmp;
        }
        $insertLogRes = (new LogModel())->insertMultiData($logData);
        if (false === $insertLogRes) {
            DB::rollBack();
            $result['msg'] = '日志记录失败';
            return $result;
        }

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

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

        if (!isset($dealRecordInfo['deal_record_ids'])) {
            $result['msg'] = 'deal_record_ids异常';
            return $result;
        }

        $dealRecordIdsArr = explode(',', $dealRecordInfo['deal_record_ids']);
        $dealRecordIdsArr = array_filter(array_unique($dealRecordIdsArr));
        if (empty($dealRecordIdsArr)) {
            $result['msg'] = 'deal_record_ids异常';
            return $result;
        }

        foreach ($dealRecordIdsArr as $index => $dealRecordId) {
            if (!is_numeric($dealRecordId) || $dealRecordId <= 0) {
                $result['msg'] = 'deal_record_ids异常';
                return $result;
            }
            $dealRecordIdsArr[$index] = intval($dealRecordId);
        }
        $dealRecordIdsArr = array_unique($dealRecordIdsArr);

        DB::beginTransaction();

        // 校验交易信息是否存在
        $dealRecordModel = new DealRecord();
        $where = ['created_by' => $userInfo['id'], 'check_status' => 0];
        $existedDealRecordInfo = $dealRecordModel->selectDataByWhereFieldAndIds($where, 'id', $dealRecordIdsArr, ['id']);
        if (count($existedDealRecordInfo) != count($dealRecordIdsArr)) {
            DB::rollBack();
            $result['msg'] = '待提交的交易信息不存在';
            return $result;
        }

        $updateDealRecordData = [
            'check_status' => 1,
        ];
        $updateDealRecordRes = $dealRecordModel->updateDataByIds('id', $dealRecordIdsArr, $updateDealRecordData);
        if (false === $updateDealRecordRes) {
            DB::rollBack();
            $result['msg'] = '操作失败';
            return $result;
        }

        // 写入日志
        $logData = [];
        $tmp = [
            'operator' => $userInfo['id'],
            'type' => 2,
            'url' => '交易记录',
            'operate_name' => '提交审核',
            'content' => json_encode(['data' => $updateDealRecordData], JSON_UNESCAPED_UNICODE),
        ];
        foreach ($dealRecordIdsArr as $dealRecordId) {
            $tmp['object_id'] = $dealRecordId;
            $logData[] = $tmp;
        }
        $insertLogRes = (new LogModel())->insertMultiData($logData);
        if (false === $insertLogRes) {
            DB::rollBack();
            $result['msg'] = '日志记录失败';
            return $result;
        }

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

    public function importSystemStatusHandle($file, $userInfo) {
        $result = [
            'res' => false,
            'msg' => '更新成功',
            'data' => [],
        ];

        if (empty($file)) {
            $result['msg'] = '请上传文件';
            return $result;
        }

        $extension = $file->getClientOriginalExtension();
        if (!in_array($extension, ['xlsx'])) {
            $result['msg'] = '不支持的文件类型';
            return $result;
        }

        // 加载Excel文件
        $spreadsheet = IOFactory::load($file->getRealPath());

        // 获取活动工作表
        $this->workSheet = $spreadsheet->getActiveSheet();
        $this->mergedCells = $this->workSheet->getMergeCells();

        $list = $this->workSheet->toArray();
        if (!is_array($list) || count($list) <= 1) {
            $result['msg'] = '文件数据不存在';
            return $result;
        }

        $finalData = [];
        $specialChars = ["\r\n", "\n", "\t", " "];
        foreach ($list as $index => $info) {
            $line = $index + 1;

            $info = array_map(function($item) use ($specialChars) {
                return trim($item);
            }, $info);

            if ($index == 0) {
                $title = $info;
                continue;
            }

            // 判断最后一行
            $isEnd = true;
            foreach ($info as $v) {
                if (!empty($v)) {
                    $isEnd = false;
                    break;
                }
            }

            if ($isEnd) {
                break;
            }

            $dealSystemStatusInfo = array_combine($title, array_slice($info, 0, count($title)));
            $dealSystemStatusInfo['line_number'] = $line;

            $checkDataRes = $this->checkSystemStatusExcelDataFormat($dealSystemStatusInfo);
            if ($checkDataRes['res'] === false) {
                $result['msg'] = $checkDataRes['msg'] ?? '数据不合法';
                return $result;
            }

            $finalData[] = $dealSystemStatusInfo;
        }

        DB::beginTransaction();
        $dealRecordModel = new DealRecord();
        $dealRecordUserModel = new DealRecordUser();

        // 写入日志
        $logData = [];
        $tmp = [
            'operator' => $userInfo['id'],
            'type' => 2,
            'url' => '交易记录',
            'operate_name' => '导入系统状态',
        ];

        foreach ($finalData as $systemStatusData) {
            $dealDate = $this->getCellValue($this->dealSystemStatusTitleRelatedCell['抵扣日期'] . $systemStatusData['line_number'])['value'];
            $userName = $this->getCellValue($this->dealSystemStatusTitleRelatedCell['学员姓名'] . $systemStatusData['line_number'])['value'];
            $systemStatus = $this->getCellValue($this->dealSystemStatusTitleRelatedCell['系统状态'] . $systemStatusData['line_number'])['value'];

            // 查询当前学员信息表
            $dealRecordInfoList = $dealRecordModel->selectDataWithField(['user_name' => $userName, 'deal_date' => $dealDate]);
            if (empty($dealRecordInfoList)) {
                DB::rollBack();
                $result['msg'] = '第' . $systemStatusData['line_number'] . '行交易信息不存在';
                return $result;
            }

            // 更新系统状态
            $dealRecordIds = array_unique(array_column($dealRecordInfoList, 'id'));
            $updateData = ['system_status' => $this->dealRecordSystemStatus[$systemStatus] ?? 0];
            $updateStatusRes = $dealRecordUserModel->updateDataByIds('deal_record_id', $dealRecordIds, $updateData);
            if (false === $updateStatusRes) {
                DB::rollBack();
                $result['msg'] = '第' . $systemStatusData['line_number'] . '行更新失败';
                return $result;
            }
            $tmp['content'] = json_encode(['ids' => $dealRecordIds, 'data' => $updateData], JSON_UNESCAPED_UNICODE);

            // 更新交易记录的系统状态contain_system_status
            // 查询交易记录学员信息,获取系统状态
            foreach ($dealRecordInfoList as $dealRecord) {
                $dealRecordUserList = $dealRecordUserModel->selectDataWithField(['deal_record_id' => $dealRecord['id']], ['system_status']);
                $tmpSystemStatus = array_unique(array_column($dealRecordUserList, 'system_status'));

                $updateSystemStatus = ['contain_system_status' => implode('%%', $tmpSystemStatus)];
                $updateRes = $dealRecordModel->updateData(['id' => $dealRecord['id']], $updateSystemStatus);
                if (false === $updateRes) {
                    DB::rollBack();
                    $result['msg'] = '第' . $systemStatusData['line_number'] . '行更新失败';
                    return $result;
                }
                $tmp['object_id'] = $dealRecord['id'];
                $logData[] = $tmp;
            }
        }

        $insertLogRes = (new LogModel())->insertMultiData($logData);
        if (false === $insertLogRes) {
            DB::rollBack();
            $result['msg'] = '日志记录失败';
            return $result;
        }

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

    private function checkSystemStatusExcelDataFormat($lineData) {
        $result = [
            'res' => false,
            'msg' => '校验通过',
            'data' => [],
        ];

        // 校验数据合法性
        if (!isset($lineData['抵扣日期']) || !isValidDateTime($lineData['抵扣日期'], 'Y-m-d')) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [抵扣日期]不合法';
            return $result;
        }

        if (!isset($lineData['学员姓名']) || mb_strlen($lineData['学员姓名']) == 0 || mb_strlen($lineData['学员姓名']) > 128) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [学员姓名]不合法';
            return $result;
        }

        if (!isset($lineData['系统状态']) || !isset($this->dealRecordSystemStatus[$lineData['系统状态']])) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [系统状态]不合法';
            return $result;
        }

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

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

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

        if ($searchParam['class_phone'] !== '' && checkPhone($searchParam['class_phone'])) {
            $result['data']['class_phone'] = $searchParam['class_phone'];
        }

        if ($searchParam['goods_name'] !== '') {
            $result['data']['goods_name'] = $searchParam['goods_name'];
        }

        if ($searchParam['deal_record_no'] !== '') {
            $result['data']['deal_record_no'] = $searchParam['deal_record_no'];
        }

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

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

        if ($searchParam['province_name'] !== '' && $searchParam['province_name'] != '全国') {
            $result['data']['province_name'] = mb_substr($searchParam['province_name'], 0, 32);
        }

        if ($searchParam['order_no'] !== '') {
            $result['data']['order_no'] = $searchParam['order_no'];
        }

        $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 getGoodsNotDeliverListHandle($searchParam) {
        $result = [
            'res' => true,
            'msg' => '获取成功',
            'data' => [],
        ];

        $searchWhere = [];

        if (isset($searchParam['user_name'])) {
            $searchWhere['ydr.user_name'] = $searchParam['user_name'];
        }

        if (isset($searchParam['class_phone'])) {
            $searchWhere['ydr.class_phone'] = $searchParam['class_phone'];
        }

        if (isset($searchParam['reception_name'])) {
            $searchWhere['ydr.reception_name'] = $searchParam['reception_name'];
        }

        if (isset($searchParam['department'])) {
            $searchWhere['ydr.department'] = $searchParam['department'];
        }

        if (isset($searchParam['province_name'])) {
            $searchWhere['ydr.province_name'] = $searchParam['province_name'];
        }

        if (isset($searchParam['deal_record_no'])) {
            $searchWhere['ydru.deal_record_no'] = $searchParam['deal_record_no'];
        }

        if (isset($searchParam['goods_name'])) {
            $searchWhere[] = ['ydrg.goods_name', 'like', '%' . $searchParam['goods_name'] . '%'];
        }

        if (isset($searchParam['order_no'])) {
            $searchWhere['ydrg.order_no'] = $searchParam['order_no'];
        }

        $timestamp = strtotime('-15 days midnight');
        $dealDateDeadLine = date('Y-m-d H:i:s', $timestamp);
//        $searchWhere[] = ['ydrg.created_at', '<', $dealDateDeadLine];

        $searchWhere['ydrg.deleted_at'] = null;
        $searchWhere['ydru.deleted_at'] = null;
        $searchWhere['ydr.deleted_at'] = null;
        $searchWhere['ydr.check_status'] = 2;

        // 邮寄
        $searchWhere[] = ['ydrg.deliver_type', '>', 1];
        $searchWhere['deliver_status'] = 3;
        $searchWhere[] = ['express_no', '=', ''];

        $dealRecordGoodsModel = new DealRecordGoods();
        $dealRecordGoodsList = $dealRecordGoodsModel->getGoodsNotDeliverList($searchWhere, ['ydrg.id','ydrg.deal_record_id','ydrg.deal_record_user_id','ydr.deal_date','ydr.reception_name','ydr.department','ydr.province_name','ydr.user_name','ydr.class_phone','ydru.deal_record_no','ydrg.goods_name','ydrg.order_no','ydrg.deliver_type','ydrg.deliver_status', 'ydrg.created_at'], $searchParam['page_size']);

        $now = strtotime(date('Y-m-d'));
        foreach ($dealRecordGoodsList['data'] as $index => $info) {
            $dealRecordGoodsList['data'][$index] = (array)$info;
            $info = (array)$info;

            $dealTime = strtotime($info['created_at']);
            $daysDiff = floor(($now - $dealTime) / 86400);

            $dealRecordGoodsList['data'][$index]['days_from_today'] = $daysDiff > 0 ? $daysDiff : 0;
        }

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

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

        if (empty($userInfo['is_review'])) {
            $result['msg'] = '您没有审核权限,请联系管理员';
            return $result;
        }

        // 2: 通过, 3: 驳回
        if (!isset($dealRecordInfo['check_status']) || !is_numeric($dealRecordInfo['check_status']) || ($dealRecordInfo['check_status'] != 2 && $dealRecordInfo['check_status'] != 3)) {
            $result['msg'] = '审核状态异常';
            return $result;
        }
        $dealRecordInfo['check_status'] = intval($dealRecordInfo['check_status']);

        // 审核驳回,需填写驳回原因
        if ($dealRecordInfo['check_status'] == 3 && (!isset($dealRecordInfo['check_remark']) || mb_strlen($dealRecordInfo['check_remark']) == 0 || mb_strlen($dealRecordInfo['check_remark']) > 64)) {
            $result['msg'] = '驳回原因异常';
            return $result;
        }

        if (!isset($dealRecordInfo['deal_record_ids'])) {
            $result['msg'] = 'deal_record_ids异常';
            return $result;
        }

        $dealRecordIdsArr = explode(',', $dealRecordInfo['deal_record_ids']);
        $dealRecordIdsArr = array_filter(array_unique($dealRecordIdsArr));
        if (empty($dealRecordIdsArr)) {
            $result['msg'] = 'deal_record_ids异常';
            return $result;
        }

        foreach ($dealRecordIdsArr as $index => $dealRecordId) {
            if (!is_numeric($dealRecordId) || $dealRecordId <= 0) {
                $result['msg'] = 'deal_record_ids异常';
                return $result;
            }
            $dealRecordIdsArr[$index] = intval($dealRecordId);
        }
        $dealRecordIdsArr = array_unique($dealRecordIdsArr);

        DB::beginTransaction();

        // 校验交易信息是否存在
        $dealRecordModel = new DealRecord();
        $existedDealRecordInfo = $dealRecordModel->selectDataByIds($dealRecordIdsArr, ['id']);
        if (count($existedDealRecordInfo) != count($dealRecordIdsArr)) {
            DB::rollBack();
            $result['msg'] = '交易信息不存在';
            return $result;
        }

        foreach ($existedDealRecordInfo as $info) {
            // 如果当前订单不在权限范围内, 不允许审核
            if (empty($userInfo['is_admin']) && strpos(','.$userInfo['deal_area_pro_name'].',', '全国' ) === false && ($info['province_name'] !== '' && strpos(','.$userInfo['deal_area_pro_name'].',', ','.$info['province_name'].',' ) === false)) {
                DB::rollBack();
                $result['msg'] = '您没有审核权限,请联系管理员';
                return $result;
            }
        }

        $updateDealRecordData = [
            'check_status' => $dealRecordInfo['check_status'],
            'check_remark' => $dealRecordInfo['check_status'] == 2 ? '' : $dealRecordInfo['check_remark'],
        ];
        $updateDealRecordRes = $dealRecordModel->updateDataByIds('id', $dealRecordIdsArr, $updateDealRecordData);
        if (false === $updateDealRecordRes) {
            DB::rollBack();
            $result['msg'] = '操作失败';
            return $result;
        }

        // 写入日志
        $logData = [];
        $tmp = [
            'operator' => $userInfo['id'],
            'type' => 2,
            'url' => '交易记录',
            'operate_name' => '审核/驳回',
            'content' => json_encode(['data' => $updateDealRecordData], JSON_UNESCAPED_UNICODE),
        ];
        foreach ($dealRecordIdsArr as $dealRecordId) {
            $tmp['object_id'] = $dealRecordId;
            $logData[] = $tmp;
        }
        $insertLogRes = (new LogModel())->insertMultiData($logData);
        if (false === $insertLogRes) {
            DB::rollBack();
            $result['msg'] = '日志记录失败';
            return $result;
        }

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

    public function importDealHandle($file, $userInfo) {
        $result = [
            'res' => false,
            'msg' => '导入成功',
            'data' => [],
        ];

        if ($userInfo['id'] == 65) {
            $result['msg'] = '此账号无法导入';
            return $result;
        }

        if (empty($file)) {
            $result['msg'] = '请上传文件';
            return $result;
        }

        $extension = $file->getClientOriginalExtension();
        if (!in_array($extension, ['xlsx'])) {
            $result['msg'] = '不支持的文件类型';
            return $result;
        }

        // 加载Excel文件
        $spreadsheet = IOFactory::load($file->getRealPath());

        // 获取活动工作表
        $this->workSheet = $spreadsheet->getActiveSheet();
        $this->mergedCells = $this->workSheet->getMergeCells();

        // 获取省份信息
        $areaProvince = (new AreaProvinceModel())->selectDataWithField([], ['name']);
        $this->areaProvince = array_column($areaProvince, 'name');

        $list = $this->workSheet->toArray();
        if (!is_array($list) || count($list) <= 1) {
            $result['msg'] = '文件数据不存在';
            return $result;
        }

        // 标题栏字母初始化
        $titleCount = count($this->importDealRecordTitle);
        $titleCell = array_slice(range('A', 'Z'), 0, $titleCount);
        $titleCell = array_combine($this->importDealRecordTitle, $titleCell);

        $title = $tmpDealRecord = $singleDealRecordList = $goodsNames = [];
        $specialChars = ["\r\n", "\n", "\t", " "];
        foreach ($list as $index => $info) {
            if (count($info) < count($this->importDealRecordTitle)) {
                $result['msg'] = '数据不符合规范';
                return $result;
            }

            $line = $index + 1;

            $info = array_map(function($item) use ($specialChars) {
                return trim($item);
            }, $info);

            if ($index == 0) {
                $title = $info;
                continue;
            }

            // 判断最后一行
            $isEnd = true;
            foreach ($info as $v) {
                if (!empty($v)) {
                    $isEnd = false;
                    break;
                }
            }

            if ($isEnd) {
                if (!empty($tmpDealRecord)) {
                    $singleDealRecordList[] = $tmpDealRecord;
                }

                break;
            }

            $dealRecordInfo = array_combine($title, array_slice($info, 0, count($title)));
            $dealRecordInfo['line_number'] = $line;

            $checkDataRes = $this->checkExcelDataFormat($dealRecordInfo);
            if ($checkDataRes['res'] === false) {
                $result['msg'] = $checkDataRes['msg'] ?? '数据不合法';
                return $result;
            }
            $goodsNames[] = $checkDataRes['data']['goods_name'] ?? '';

            // 不为空说明是一条新的抵扣记录
            if ($dealRecordInfo['接待人姓名'] !== '' && $dealRecordInfo['部门'] !== '' && !empty($tmpDealRecord)) {
                $singleDealRecordList[] = $tmpDealRecord;

                // 清空
                $tmpDealRecord = [];
            }

            $tmpDealRecord[] = $dealRecordInfo;

            // 最后一条了
            if ($index == (count($list) - 1)) {
                $singleDealRecordList[] = $tmpDealRecord;
            }
        }

        if (empty($singleDealRecordList)) {
            $result['msg'] = '数据异常,请检查数据';
            return $result;
        }

        $goodsNames = array_unique(array_filter($goodsNames));
        $existGoodsRelatedInfo = [];
        if (!empty($goodsNames)) {
            $goodsExisted = (new Goods())->selectDataByWhereFieldAndIds(['status' => 1, 'deleted_at' => null], 'goods_name', $goodsNames, ['*']);
            $goodsExistedNames = array_unique(array_column($goodsExisted, 'goods_name'));
            if (count($goodsExistedNames) != count($goodsNames)) {
                $result['msg'] = '商品名称: ' . implode(',', array_values(array_diff($goodsNames, $goodsExistedNames))) . ' 不存在';
                return $result;
            }

            $existGoodsRelatedInfo = array_column($goodsExisted, null, 'goods_name');
        }

        $finalDealRecordList = [];
        foreach ($singleDealRecordList as $singleDealRecordData) {
            if (empty($singleDealRecordData)) {
                continue;
            }

            $tmpDealRecord = [];
            // 商品名称+交付状态
            $containGoodsName = $containDeliverStatus = [];
            // 系统状态+单号
            $containSystemStatus = $containDealRecordNo = [];

            $tmpDealRecord['reception_name'] = $singleDealRecordData[0]['接待人姓名'] ?? '';
            $tmpDealRecord['department'] = $this->dealRecordDepartment[$singleDealRecordData[0]['部门']] ?? 0;
            $tmpDealRecord['province_name'] = $singleDealRecordData[0]['省份'] ?? '';
            $tmpDealRecord['user_name'] = $singleDealRecordData[0]['学员姓名'] ?? '';
            $tmpDealRecord['class_phone'] = $singleDealRecordData[0]['学员报班电话'] ?? '';
            $tmpDealRecord['deduction_money'] = round(floatval($singleDealRecordData[0]['抵扣总金额'] ?? 0), 2);
            $tmpDealRecord['remain_money'] = round(floatval($singleDealRecordData[0]['剩余总额'] ?? 0), 2);
            $tmpDealRecord['deal_goods'] = $singleDealRecordData[0]['抵扣内容'] ?? '';
            $tmpDealRecord['line_number'] = $singleDealRecordData[0]['line_number'] ?? 0;
            $tmpDealRecord['user_info'] = [];

            // 当前抵扣记录的学员信息
            $dealRecordUserData = [];
            foreach ($singleDealRecordData as $dealRecord) {
                // 说明是一个新的单号
                if ($dealRecord['单号'] !== '') {
                    if (!empty($dealRecordUserData)) {
                        $tmpDealRecord['user_info'][] = $dealRecordUserData;
                        $dealRecordUserData = [];
                    }

                    $containDealRecordNo[] = $dealRecord['单号'];
                    $dealRecordUserData['deal_record_no'] = $dealRecord['单号'];
                    $dealRecordUserData['refund_money'] = round(floatval($dealRecord['退费总额']), 2);
                    $dealRecordUserData['returned_money'] = round(floatval($dealRecord['已退金额']), 2);
                    $dealRecordUserData['remain_money'] = round(floatval($dealRecord['剩余金额']), 2);
                    $tmpSystemStatus = $this->getCellValue($titleCell['是否标记/点付'] . $dealRecord['line_number']);
                    $dealRecordUserData['system_status'] = $this->dealRecordSystemStatus[$tmpSystemStatus['value']] ?? 0;
                    $containSystemStatus[] = $dealRecordUserData['system_status'];
                    $dealRecordUserData['goods_info'] = [];
                    if ($dealRecord['商品名称'] !== '') {
                        $tmpGoods = [
                            'goods_name' => $dealRecord['商品名称'],
                            'buy_number' => intval($dealRecord['商品数量']),
                            'goods_spec' => $dealRecord['商品规格'],
                            'deduction_money' => round(floatval($dealRecord['抵扣金额']), 2),
                            'deliver_type' => $this->dealRecordDeliverType[$dealRecord['交付方式（邮寄/现场）']] ?? 0,
                            'deliver_status' => $this->dealRecordDeliverStatus[$dealRecord['交付状态（已邮寄/已拿走/待邮寄）']] ?? 0,
                            'post_address' => $dealRecord['邮寄必填*收货地址（含收货人姓名及联系方式）'],
                            'express_no' => $dealRecord['快递单号'],
                        ];

                        $tmpGoodsInfo = $existGoodsRelatedInfo[$tmpGoods['goods_name'] ?? ''] ?? [];
                        $tmpGoods['province_name'] = $tmpGoodsInfo['province_name'] ?? '';
                        $tmpGoods['category_name'] = $tmpGoodsInfo['category_name'] ?? '';
                        $tmpGoods['supplier_name'] = $tmpGoodsInfo['supplier_name'] ?? '';
                        $tmpGoods['model_name'] = $tmpGoodsInfo['model_name'] ?? '';

                        $dealRecordUserData['goods_info'][] = $tmpGoods;

                        if (!empty($dealRecord['快递单号'])) {
                            $tmpDealRecord['is_set_express'] = 1;
                        }

                        $containGoodsName[] = $dealRecord['商品名称'];
                        $containDeliverStatus[] = $this->dealRecordDeliverStatus[$dealRecord['交付状态（已邮寄/已拿走/待邮寄）']] ?? 0;

                        if (isset($v['deliver_status']) && $v['deliver_status'] !== '') {
                            $containDeliverStatus[] = $v['deliver_status'];
                        }
                    }
                } else {
                    // 说明是属于上一个单号的商品
                    // 说明是一个新的商品,写入
                    if ($dealRecord['商品名称'] !== '') {
                        $tmp = [
                            'goods_name' => $dealRecord['商品名称'],
                            'buy_number' => intval($dealRecord['商品数量']),
                            'goods_spec' => $dealRecord['商品规格'],
                            'deduction_money' => round(floatval($dealRecord['抵扣金额']), 2),
                        ];

                        $tmpGoodsInfo = $existGoodsRelatedInfo[$tmp['goods_name'] ?? ''] ?? [];
                        $tmp['province_name'] = $tmpGoodsInfo['province_name'] ?? '';
                        $tmp['category_name'] = $tmpGoodsInfo['category_name'] ?? '';
                        $tmp['supplier_name'] = $tmpGoodsInfo['supplier_name'] ?? '';
                        $tmp['model_name'] = $tmpGoodsInfo['model_name'] ?? '';

                        // 获取对应单元格的内容,有合并的情况存在
                        $deliverTypeValue = $this->getCellValue($titleCell['交付方式（邮寄/现场）'] . $dealRecord['line_number']);
                        $tmp['deliver_type'] = $this->dealRecordDeliverType[$deliverTypeValue['value']] ?? 0;

                        $deliverStatusValue = $this->getCellValue($titleCell['交付状态（已邮寄/已拿走/待邮寄）'] . $dealRecord['line_number']);
                        $tmp['deliver_status'] = $this->dealRecordDeliverStatus[$deliverStatusValue['value']] ?? 0;

                        $postAddressValue = $this->getCellValue($titleCell['邮寄必填*收货地址（含收货人姓名及联系方式）'] . $dealRecord['line_number']);
                        $tmp['post_address'] = $postAddressValue['value'];

                        $expressNoValue = $this->getCellValue($titleCell['快递单号'] . $dealRecord['line_number']);
                        $tmp['express_no'] = $expressNoValue['value'];

                        if (!empty($tmp['express_no'])) {
                            $tmpDealRecord['is_set_express'] = 1;
                        }

                        $containGoodsName[] = $dealRecord['商品名称'];
                        $containDeliverStatus[] = $tmp['deliver_status'];

                        $dealRecordUserData['goods_info'][] = $tmp;
                    }
                }
            }

            if (!empty($containGoodsName)) {
                $containGoodsName = array_unique($containGoodsName);
                $tmpDealRecord['contain_goods_name'] = implode('%%', $containGoodsName);
            }

            if (!empty($containDeliverStatus)) {
                $containDeliverStatus = array_unique($containDeliverStatus);
                $tmpDealRecord['contain_deliver_status'] = implode('%%', $containDeliverStatus);
            }

            if (!empty($containSystemStatus)) {
                $containSystemStatus = array_unique($containSystemStatus);
                $tmpDealRecord['contain_system_status'] = implode('%%', $containSystemStatus);
            }

            if (!empty($containDealRecordNo)) {
                $containDealRecordNo = array_unique($containDealRecordNo);
                $tmpDealRecord['contain_deal_record_no'] = implode('%%', $containDealRecordNo);
            }

            if (!empty($dealRecordUserData)) {
                $tmpDealRecord['user_info'][] = $dealRecordUserData;
            }

            $finalDealRecordList[] = $tmpDealRecord;
        }

//        // 处理图片
//        $coordinateRelatedImage = [];
//        $imageData = $this->workSheet->getDrawingCollection();
//        if (!empty($imageData)) {
//            $ossTokenInfoRes = (new FileService())->getOssAccessTokenHandle();
//            if ($ossTokenInfoRes['res'] === false) {
//                $result['msg'] = '图片保存失败';
//                return $result;
//            }
//            $ossTokenInfo = $ossTokenInfoRes['data'];
//
//            // 遍历所有绘图对象
//            foreach ($imageData as $drawing) {
//                // 确保是 Drawing 对象
//                if ($drawing instanceof Drawing) {
//                    // 获取图片的坐标
//                    $coordinates = $drawing->getCoordinates();
//
//                    // 将坐标转换为行和列
//                    list($column, $row) = Coordinate::coordinateFromString($coordinates);
//
//                    // 生成层级目录
//                    $remoteProtocolPath = sprintf('deal_record/images/%s/%s', date('Ymd'), $userInfo['id'] . time() . $column . $row . '.jpg');
//
//                    $uploadRes = (new FileService())->uploadFile($drawing->getPath(), $remoteProtocolPath);
//                    if ($uploadRes['res'] === false) {
//                        $result['msg'] = '图片上传失败: ' . $uploadRes['msg'] ?? '';
//                        return $result;
//                    }
//
//                    $coordinateRelatedImage[$column . $row] = 'https://xcx.tos-cn-beijing.volces.com/' . $remoteProtocolPath;
//                }
//            }
//        }

        $dealRecordDate = date('Y-m-d');

        DB::beginTransaction();
        $dealRecordModel = new DealRecord();
        $dealRecordUserModel = new DealRecordUser();
        $dealRecordGoodsModel = new DealRecordGoods();

        foreach ($finalDealRecordList as $saveDealRecord) {
            // 获取今天该学员是否已录入过,如果已录入,不允许再次录入,需要合并录入
            $dealRecordWhere = [
                'user_name' => $saveDealRecord['user_name'] ?? '',
                'class_phone' => $saveDealRecord['class_phone'] ?? '',
                'deal_date' => $dealRecordDate,
            ];
            $existedDealRecord = $dealRecordModel->findDataWithField($dealRecordWhere, ['id']);
            if (!empty($existedDealRecord)) {
                DB::rollBack();
                $result['msg'] = '学员: ' . $dealRecordWhere['user_name'] . ' 今日抵扣记录已存在,请合并录入';
                return $result;
            }

            // 写入交易记录主要信息
            $insertDealRecord = [
                'user_name' => $saveDealRecord['user_name'] ?? '',
                'class_phone' => $saveDealRecord['class_phone'] ?? '',
                'deduction_money' => $saveDealRecord['deduction_money'] ?? 0,
                'remain_money' => $saveDealRecord['remain_money'] ?? 0,
                'deal_goods' => $saveDealRecord['deal_goods'] ?? '',
                'reception_name' => $saveDealRecord['reception_name'] ?? '',
                'deal_date' => $dealRecordDate,
                'department' => $saveDealRecord['department'] ?? 0,
                'province_name' => $saveDealRecord['province_name'] ?? '',
                'is_set_express' => $saveDealRecord['is_set_express'] ?? 0,
                'contain_deal_record_no' => $saveDealRecord['contain_deal_record_no'] ?? '',
                'contain_system_status' => $saveDealRecord['contain_system_status'] ?? '',
                'contain_goods_name' => $saveDealRecord['contain_goods_name'] ?? '',
                'contain_deliver_status' => $saveDealRecord['contain_deliver_status'] ?? '',
//                'protocol_url' => $coordinateRelatedImage[$titleCell['收据/协议'] . $saveDealRecord['line_number']] ?? '',
                'origin' => 2,
                'created_by' => $userInfo['id'],
            ];
            $dealRecordId = $dealRecordModel->insertData($insertDealRecord);
            if (false === $dealRecordId) {
                DB::rollBack();
                $result['msg'] = '交易记录主要信息保存失败';
                return $result;
            }

            $containOrderNo = [];

            // 写入交易记录学员信息
            foreach ($saveDealRecord['user_info'] as $saveUserInfo) {
                $insertDealRecordUser = [
                    'deal_record_id' => $dealRecordId,
                    'deal_record_no' => $saveUserInfo['deal_record_no'],
                    'refund_money' => $saveUserInfo['refund_money'],
                    'returned_money' => $saveUserInfo['returned_money'],
                    'remain_money' => $saveUserInfo['remain_money'],
                    'system_status' => $saveUserInfo['system_status'],
                ];
                $dealRecordUserId = $dealRecordUserModel->insertData($insertDealRecordUser);
                if (false === $dealRecordUserId) {
                    DB::rollBack();
                    $result['msg'] = '交易记录学员信息保存失败';
                    return $result;
                }

                $insertGoodsData = [];
                foreach ($saveUserInfo['goods_info'] as $saveGoodsInfo) {
                    $orderNo = $this->generateOrderNo($saveDealRecord['user_name'] ?? '');

                    $insertGoodsData[] = [
                        'deal_record_id' => $dealRecordId,
                        'deal_record_user_id' => $dealRecordUserId,
                        'province_name' => $saveGoodsInfo['province_name'],
                        'category_name' => $saveGoodsInfo['category_name'],
                        'supplier_name' => $saveGoodsInfo['supplier_name'],
                        'model_name' => $saveGoodsInfo['model_name'],
                        'goods_name' => $saveGoodsInfo['goods_name'],
                        'order_no' => $orderNo,
                        'buy_number' => $saveGoodsInfo['buy_number'],
                        'goods_spec' => $saveGoodsInfo['goods_spec'],
                        'deduction_money' => $saveGoodsInfo['deduction_money'],
                        'post_address' => $saveGoodsInfo['post_address'],
                        'deliver_type' => $saveGoodsInfo['deliver_type'],
                        'deliver_status' => $saveGoodsInfo['deliver_status'],
                        'express_no' => $saveGoodsInfo['express_no'],
                    ];

                    $containOrderNo[] = $orderNo;
                }
                if (!empty($insertGoodsData)) {
                    $insertGoodsRes = $dealRecordGoodsModel->insertMultiData($insertGoodsData);
                    if (false === $insertGoodsRes) {
                        DB::rollBack();
                        $result['msg'] = '交易记录商品信息保存失败';
                        return $result;
                    }
                }
            }

            if (!empty($containOrderNo)) {
                $containOrderNo = array_unique($containOrderNo);
                $updateRes = $dealRecordModel->updateData(['id' => $dealRecordId], ['contain_order_no' => implode('%%', $containOrderNo)]);
                if (false === $updateRes) {
                    DB::rollBack();
                    $result['msg'] = '交易记录信息保存失败';
                    return $result;
                }
            }
        }

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

    public function checkProtocolOrderHandle($userInfo, $dealOrderInfo) {
        $result = [
            'res' => false,
            'msg' => '校验通过',
            'data' => [],
        ];

        if (!isset($dealOrderInfo['order_no']) || !is_array($dealOrderInfo['order_no']) || empty($dealOrderInfo['order_no'])) {
            $result['msg'] = '传参异常';
            return $result;
        }

        $orderData = [];
        foreach ($dealOrderInfo['order_no'] as $orderNo) {
            if (empty($orderNo) || !is_string($orderNo) || mb_strlen($orderNo) > 128) {
                $result['msg'] = '文件名: ' . $orderNo . ' 过长';
                return $result;
            }

            $orderNoArr = explode('.', $orderNo);
            if (count($orderNoArr) != 2) {
                $result['msg'] = '文件名: ' . $orderNo . ' 命名异常';
                return $result;
            }

            $currentOrderNo = $orderNoArr[0];
            $currentOrderNoArr = explode('_', $currentOrderNo);
            if (count($currentOrderNoArr) < 1 || count($currentOrderNoArr) > 2) {
                $result['msg'] = '文件名: ' . $orderNo . ' 命名异常';
                return $result;
            }

            $orderData[] = $currentOrderNoArr[0];
        }
        $orderData = array_unique($orderData);

        // 校验交易信息是否存在
        $dealRecordUserModel = new DealRecordUser();
        $dealRecordUserInfo = $dealRecordUserModel->selectDataByWhereFieldAndIds([], 'deal_record_no', $orderData, ['deal_record_id', 'deal_record_no']);
        $existedDealRecordNo = array_unique(array_column($dealRecordUserInfo, 'deal_record_no'));
        if (count($existedDealRecordNo) != count($orderData)) {
            $result['msg'] = '单号不存在';
            $result['data']['order_not_exist'] = array_values(array_diff($orderData, $existedDealRecordNo));
            return $result;
        }

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

    public function updateDealRecordProtocolHandle($userInfo, $dealOrderInfo) {
        $result = [
            'res' => false,
            'msg' => '校验通过',
            'data' => [],
        ];

        if ($userInfo['id'] == 65) {
            $result['msg'] = '此账号无法编辑';
            return $result;
        }

        if (!isset($dealOrderInfo['order_protocol']) || !is_array($dealOrderInfo['order_protocol']) || empty($dealOrderInfo['order_protocol'])) {
            $result['msg'] = '传参异常';
            return $result;
        }

        $allOrderNo = [];
        $orderRelatedProtocolUrl = [];
        foreach ($dealOrderInfo['order_protocol'] as $orderProtocol) {
            if (empty($orderProtocol) || !is_array($orderProtocol)) {
                $result['msg'] = '传参异常';
                return $result;
            }

            if (empty($orderProtocol['order_no']) || !is_string($orderProtocol['order_no']) || mb_strlen($orderProtocol['order_no']) > 128) {
                $result['msg'] = '文件名: ' . $orderProtocol['order_no'] . ' 命名异常';
                return $result;
            }

            if (empty($orderProtocol['url']) || !is_string($orderProtocol['url']) || mb_strlen($orderProtocol['url']) > 128) {
                $result['msg'] = 'url: ' . $orderProtocol['url'] . ' 异常';
                return $result;
            }

            $orderNoArr = explode('.', $orderProtocol['order_no']);
            if (count($orderNoArr) != 2) {
                $result['msg'] = '文件名: ' . $orderProtocol['order_no'] . ' 命名异常';
                return $result;
            }

            $currentOrderNo = $orderNoArr[0];
            $currentOrderNoArr = explode('_', $currentOrderNo);
            if (count($currentOrderNoArr) < 1 || count($currentOrderNoArr) > 2) {
                $result['msg'] = '文件名: ' . $orderProtocol['order_no'] . ' 命名异常';
                return $result;
            }
            $allOrderNo[] = $currentOrderNoArr[0];

            if (!isset($orderRelatedProtocolUrl[$currentOrderNoArr[0]])) {
                $orderRelatedProtocolUrl[$currentOrderNoArr[0]] = [];
            }
            $orderRelatedProtocolUrl[$currentOrderNoArr[0]][] = $orderProtocol['url'];
        }

        // 拿到所有的单号,去获取单号对应的deal_record_id
        $dealRecordUserModel = new DealRecordUser();
        $allOrderNo = array_unique($allOrderNo);
        $dealRecordUserInfo = $dealRecordUserModel->selectDataByWhereFieldAndIds([], 'deal_record_no', $allOrderNo, ['deal_record_id', 'deal_record_no']);
        $orderNoRelatedDealRecordId = [];
        foreach ($dealRecordUserInfo as $info) {
            if (!isset($orderNoRelatedDealRecordId[$info['deal_record_no']])) {
                $orderNoRelatedDealRecordId[$info['deal_record_no']] = [];
            }

            $orderNoRelatedDealRecordId[$info['deal_record_no']][] = $info['deal_record_id'];
        }

        DB::beginTransaction();
        $dealRecordModel = new DealRecord();

        // 写入日志
        $logData = [];
        $tmp = [
            'operator' => $userInfo['id'],
            'type' => 2,
            'url' => '交易记录',
            'operate_name' => '导入收据/协议',
        ];

        foreach ($orderNoRelatedDealRecordId as $no => $recordIds) {
            if (isset($orderRelatedProtocolUrl[$no])) {
                $updateData = ['protocol_url' => implode(',', $orderRelatedProtocolUrl[$no])];
                $updateRes = $dealRecordModel->updateDataByIds('id', $recordIds, $updateData);
                if (false === $updateRes) {
                    $result['msg'] = '导入失败';
                    DB::rollBack();
                    return $result;
                }

                foreach ($recordIds as $tmpId) {
                    $tmp['object_id'] = $tmpId;
                    $tmp['content'] = json_encode(['data' => $updateData], JSON_UNESCAPED_UNICODE);
                    $logData[] = $tmp;
                }
            }
        }

        $insertLogRes = (new LogModel())->insertMultiData($logData);
        if (false === $insertLogRes) {
            DB::rollBack();
            $result['msg'] = '日志记录失败';
            return $result;
        }

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

    private function checkExcelDataFormat($lineData) {
        $result = [
            'res' => false,
            'msg' => '校验通过',
            'data' => [
                'goods_name' => '',
            ],
        ];

        // 校验数据合法性
        if (!isset($lineData['接待人姓名']) || mb_strlen($lineData['接待人姓名']) > 32) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [接待人姓名]不合法';
            return $result;
        }

        if (!isset($lineData['部门']) || ($lineData['部门'] !== '' && !isset($this->dealRecordDepartment[$lineData['部门']]))) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [部门]不合法';
            return $result;
        }

        if (!isset($lineData['省份']) || ($lineData['省份'] !== '' && !in_array($lineData['省份'], $this->areaProvince))) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [省份]不合法';
            return $result;
        }

        if (!isset($lineData['单号']) || ($lineData['单号'] !== '' && mb_strlen($lineData['单号']) > 128)) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [单号]不合法';
            return $result;
        }

        if (!isset($lineData['学员姓名']) || ($lineData['学员姓名'] !== '' && mb_strlen($lineData['学员姓名']) > 32)) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [学员姓名]不合法';
            return $result;
        }

        if (!isset($lineData['抵扣总金额']) || ($lineData['抵扣总金额'] !== '' && (!is_numeric($lineData['抵扣总金额']) || $lineData['抵扣总金额'] < 0 || $lineData['抵扣总金额'] > 999999.99))) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [抵扣总金额]不合法';
            return $result;
        }

        if (!isset($lineData['剩余总额']) || ($lineData['剩余总额'] !== '' && (!is_numeric($lineData['剩余总额']) || $lineData['剩余总额'] > 999999.99))) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [剩余总额]不合法';
            return $result;
        }

        if (!isset($lineData['抵扣内容']) || mb_strlen($lineData['抵扣内容']) > 512) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [抵扣内容]长度超过512';
            return $result;
        }

        if (!isset($lineData['是否标记/点付']) || ($lineData['是否标记/点付'] !== '' && !isset($this->dealRecordSystemStatus[$lineData['是否标记/点付']]))) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [是否标记/点付]不合法';
            return $result;
        }

        if (!isset($lineData['学员报班电话']) || ($lineData['学员报班电话'] !== '' && mb_strlen($lineData['学员报班电话']) > 128)) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [学员报班电话]不合法';
            return $result;
        }

        if (!isset($lineData['退费总额']) || ($lineData['退费总额'] !== '' && (!is_numeric($lineData['退费总额']) || $lineData['退费总额'] < 0 || $lineData['退费总额'] > 999999.99))) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [退费总额]不合法';
            return $result;
        }

        if (!isset($lineData['已退金额']) || ($lineData['已退金额'] !== '' && (!is_numeric($lineData['已退金额']) || $lineData['已退金额'] < 0 || $lineData['已退金额'] > 999999.99))) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [已退金额]不合法';
            return $result;
        }

        if (!isset($lineData['剩余金额']) || ($lineData['剩余金额'] !== '' && (!is_numeric($lineData['剩余金额']) || $lineData['剩余金额'] < 0 || $lineData['剩余金额'] > 999999.99))) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [剩余金额]不合法';
            return $result;
        }

        if (!isset($lineData['商品名称']) || mb_strlen($lineData['商品名称']) > 128) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [商品名称]长度超过128';
            return $result;
        }
        $result['data']['goods_name'] = $lineData['商品名称'];

        if (!isset($lineData['商品数量']) || ($lineData['商品数量'] !== '' && (!is_numeric($lineData['商品数量']) || $lineData['商品数量'] < 0 || $lineData['商品数量'] > 999999))) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [商品数量]不合法';
            return $result;
        }

        if (!isset($lineData['商品规格']) || mb_strlen($lineData['商品规格']) > 32) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [商品规格]长度超过32';
            return $result;
        }

        if (!isset($lineData['抵扣金额']) || ($lineData['抵扣金额'] !== '' && (!is_numeric($lineData['抵扣金额']) || $lineData['抵扣金额'] < 0 || $lineData['抵扣金额'] > 999999.99))) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [抵扣金额]不合法';
            return $result;
        }

        if (!isset($lineData['交付方式（邮寄/现场）']) || ($lineData['交付方式（邮寄/现场）'] !== '' && !isset($this->dealRecordDeliverType[$lineData['交付方式（邮寄/现场）']]))) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [交付方式（邮寄/现场）]不合法';
            return $result;
        }

        if (!isset($lineData['交付状态（已邮寄/已拿走/待邮寄）']) || ($lineData['交付状态（已邮寄/已拿走/待邮寄）'] !== '' && !isset($this->dealRecordDeliverStatus[$lineData['交付状态（已邮寄/已拿走/待邮寄）']]))) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [交付状态（已邮寄/已拿走/待邮寄）]不合法';
            return $result;
        }

        if (!isset($lineData['邮寄必填*收货地址（含收货人姓名及联系方式）']) || mb_strlen($lineData['邮寄必填*收货地址（含收货人姓名及联系方式）']) > 128) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [邮寄必填*收货地址（含收货人姓名及联系方式）]长度超过128';
            return $result;
        }

        if (!isset($lineData['快递单号']) || mb_strlen($lineData['快递单号']) > 1024) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [快递单号]长度超过1024';
            return $result;
        }

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

    private function getCellValue($cell) {
        $result = [
            'is_merged' => false,
            'value' => '',
        ];

        if ($cell === '') {
            return $result;
        }

        $currentLetter = $cell[0];
        $currentNumber = intval(substr($cell, 1));

        // 遍历所有合并单元格
        foreach ($this->mergedCells as $mergedCell) {
            // 解析合并单元格的范围
            $range = Coordinate::splitRange($mergedCell)[0];
            $mergedLetter = $range[0][0];

            if ($currentLetter != $mergedLetter) {
                continue;
            }

            $beginNumber = intval(substr($range[0], 1));
            $endNumber = intval(substr($range[1], 1));

            // 检查当前坐标是否在合并范围内
            if ($currentNumber >= $beginNumber && $currentNumber <= $endNumber) {
                $result['is_merged'] = true;
                $cell = $currentLetter . $beginNumber;
                break;
            }
        }

        $result['value'] = trim($this->workSheet->getCell($cell)->getFormattedValue());
        return $result;
    }

    public function importDealExpressHandle($file, $userInfo) {
        $result = [
            'res' => false,
            'msg' => '更新成功',
            'data' => [],
        ];

        if (empty($file)) {
            $result['msg'] = '请上传文件';
            return $result;
        }

        $extension = $file->getClientOriginalExtension();
        if (!in_array($extension, ['xlsx'])) {
            $result['msg'] = '不支持的文件类型';
            return $result;
        }

        // 加载Excel文件
        $spreadsheet = IOFactory::load($file->getRealPath());

        // 获取活动工作表
        $this->workSheet = $spreadsheet->getActiveSheet();
        $this->mergedCells = $this->workSheet->getMergeCells();

        $list = $this->workSheet->toArray();
        if (!is_array($list) || count($list) <= 1) {
            $result['msg'] = '文件数据不存在';
            return $result;
        }

        $finalData = [];
        $specialChars = ["\r\n", "\n", "\t", " "];
        foreach ($list as $index => $info) {
            $line = $index + 1;

            $info = array_map(function($item) use ($specialChars) {
                return trim($item);
            }, $info);

            if ($index == 0) {
                $title = $info;
                continue;
            }

            // 判断最后一行
            $isEnd = true;
            foreach ($info as $v) {
                if (!empty($v)) {
                    $isEnd = false;
                    break;
                }
            }

            if ($isEnd) {
                break;
            }

            $dealExpressInfo = array_combine($title, array_slice($info, 0, count($title)));
            $dealExpressInfo['line_number'] = $line;

            $checkDataRes = $this->checkExpressExcelDataFormat($dealExpressInfo);
            if ($checkDataRes['res'] === false) {
                $result['msg'] = $checkDataRes['msg'] ?? '数据不合法';
                return $result;
            }

            $finalData[] = $dealExpressInfo;
        }

        DB::beginTransaction();
        $dealRecordModel = new DealRecord();
        $dealRecordUserModel = new DealRecordUser();
        $dealRecordGoodsModel = new DealRecordGoods();

        // 写入日志
        $logData = [];
        $tmp = [
            'operator' => $userInfo['id'],
            'type' => 2,
            'url' => '交易记录',
            'operate_name' => '导入快递单号',
        ];

        foreach ($finalData as $expressData) {
            $orderNoContent = $this->getCellValue($this->dealExpressTitleRelatedCell['订单号'] . $expressData['line_number']);
            $goodsNameContent = $this->getCellValue($this->dealExpressTitleRelatedCell['商品名称'] . $expressData['line_number']);
            $expressNoContent = $this->getCellValue($this->dealExpressTitleRelatedCell['快递单号'] . $expressData['line_number']);

            $orderNo = $orderNoContent['value'];
            $goodsName = $goodsNameContent['value'];
            $expressNo = $expressNoContent['value'];

            $orderNoIsMerged = $orderNoContent['is_merged'];
            $goodsNameIsMerged = $goodsNameContent['is_merged'];
            $expressNoIsMerged = $expressNoContent['is_merged'];

            // 存在合并单元格的行,提示
            if ($orderNoIsMerged || $goodsNameIsMerged || $expressNoIsMerged) {
                DB::rollBack();
                $result['msg'] = '第' . $expressData['line_number'] . '行存在单元格合并';
                return $result;
            }

            // 查询当前抵扣信息表
            $dealRecordGoodsInfo = $dealRecordGoodsModel->findDataWithField(['order_no' => $orderNo, 'goods_name' => $goodsName]);
            if (empty($dealRecordGoodsInfo)) {
                DB::rollBack();
                $result['msg'] = '第' . $expressData['line_number'] . '行商品名称和订单号不匹配';
                return $result;
            }

            $updateExpressNo = '';
            if ($expressNo !== '') {
                // 拿到现有的单号
                $existedExpressNo = explode(',', $dealRecordGoodsInfo['express_no']);
                $newExpressNo = explode(',', $expressNo);

                $updateExpressNoArr = array_merge($existedExpressNo, $newExpressNo);
                $updateExpressNoArr = array_unique(array_filter($updateExpressNoArr));

                $updateExpressNo = implode(',', $updateExpressNoArr);
                if (mb_strlen($updateExpressNo) > 1024) {
                    $result['msg'] = '第' . $expressData['line_number'] . '行单号超长';
                    return $result;
                }
            }

            // 更新
            $updateData = ['express_no' => $updateExpressNo];
            $updateRes = $dealRecordGoodsModel->updateData(['id' => $dealRecordGoodsInfo['id']], $updateData);
            if (false === $updateRes) {
                DB::rollBack();
                $result['msg'] = '第' . $expressData['line_number'] . '行更新失败';
                return $result;
            }

            $tmp['object_id'] = $dealRecordGoodsInfo['deal_record_id'];
            $tmp['content'] = json_encode(['data' => $updateData], JSON_UNESCAPED_UNICODE);
            $logData[] = $tmp;

            // 更新是否设置了单号
            $updateDealRecordData = ['is_set_express' => 1];

            $expressWhere = [];
            $expressWhere['deal_record_id'] = $dealRecordGoodsInfo['deal_record_id'];
            $expressWhere[] = ['express_no', '<>', ''];
            $expressInfo = $dealRecordGoodsModel->findDataWithField($expressWhere, ['id']);
            if (empty($expressInfo)) {
                $updateDealRecordData['is_set_express'] = 0;
            }
            $updateDealRecordRes = $dealRecordModel->updateData(['id' => $dealRecordGoodsInfo['deal_record_id']], $updateDealRecordData);
            if (false === $updateDealRecordRes) {
                DB::rollBack();
                $result['msg'] = '第' . $expressData['line_number'] . '行更新失败';
                return $result;
            }
        }

        $insertLogRes = (new LogModel())->insertMultiData($logData);
        if (false === $insertLogRes) {
            DB::rollBack();
            $result['msg'] = '日志记录失败';
            return $result;
        }

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

    private function checkExpressExcelDataFormat($lineData) {
        $result = [
            'res' => false,
            'msg' => '校验通过',
            'data' => [],
        ];

        // 校验数据合法性
        if (!isset($lineData['订单号']) || mb_strlen($lineData['订单号']) > 128) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [订单号]不合法';
            return $result;
        }

        if (!isset($lineData['商品名称']) || mb_strlen($lineData['商品名称']) > 128) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [商品名称]不合法';
            return $result;
        }

        if (!isset($lineData['快递单号']) || mb_strlen($lineData['快递单号']) > 512) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [快递单号]不合法';
            return $result;
        }

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

    public function updateDealExpressHandle($userInfo, $dealRecordInfo) {
        $result = [
            'res' => false,
            'msg' => '更新成功',
            'data' => [],
        ];

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

        if (!isset($dealRecordInfo['express_no']) || mb_strlen($dealRecordInfo['express_no']) > 512) {
            $result['msg'] = 'express_no异常';
            return $result;
        }

        DB::beginTransaction();

        // 校验交易抵扣信息是否存在
        $dealRecordGoodsModel = new DealRecordGoods();
        $existedDealRecordGoodsInfo = $dealRecordGoodsModel->findDataWithField(['id' => $dealRecordInfo['deal_record_goods_id']]);
        if (empty($existedDealRecordGoodsInfo)) {
            DB::rollBack();
            $result['msg'] = '交易抵扣信息不存在';
            return $result;
        }

        if ($existedDealRecordGoodsInfo['check_status'] > 1 && empty($userInfo['is_review'])) {
            DB::rollBack();
            $result['msg'] = '交易记录已审核完成,您无编辑权限,请联系管理员';
            return $result;
        }

        $updateData = ['express_no' => $dealRecordInfo['express_no']];
        $updateDealRecordGoodsRes = $dealRecordGoodsModel->updateData(['id' => $dealRecordInfo['deal_record_goods_id']], $updateData);
        if (false === $updateDealRecordGoodsRes) {
            DB::rollBack();
            $result['msg'] = '更新失败';
            return $result;
        }

        // 更新是否设置了单号
        $updateDealRecordData = ['is_set_express' => 1];
        if (empty($dealRecordInfo['express_no'])) {
            $updateDealRecordData['is_set_express'] = 0;
        }
        $dealRecordModel = new DealRecord();
        $updateDealRecordRes = $dealRecordModel->updateData(['id' => $existedDealRecordGoodsInfo['deal_record_id']], $updateDealRecordData);
        if (false === $updateDealRecordRes) {
            DB::rollBack();
            $result['msg'] = '更新失败';
            return $result;
        }

        // 写入日志
        $insertLogRes = (new LogModel())->insertData([
            'operator' => $userInfo['id'],
            'type' => 2,
            'url' => '交易记录',
            'operate_name' => '更新快递单号',
            'object_id' => $existedDealRecordGoodsInfo['deal_record_id'],
            'content' => json_encode($updateData, JSON_UNESCAPED_UNICODE),
        ]);
        if (false === $insertLogRes) {
            DB::rollBack();
            $result['msg'] = '日志记录失败';
            return $result;
        }

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

    public function checkAddGoodsHandle($goodsInfo) {
        $result = [
            'res' => false,
            'msg' => '校验成功',
            'data' => [],
        ];

        if (!isset($goodsInfo['province_name']) || mb_strlen($goodsInfo['province_name']) == 0 || mb_strlen($goodsInfo['province_name']) > 32) {
            $result['msg'] = 'province_name异常';
            return $result;
        }
        $result['data']['province_name'] = $goodsInfo['province_name'];

        if (!isset($goodsInfo['category_name']) || mb_strlen($goodsInfo['category_name']) == 0 || mb_strlen($goodsInfo['category_name']) > 32) {
            $result['msg'] = 'category_name异常';
            return $result;
        }
        $result['data']['category_name'] = $goodsInfo['category_name'];

        if (!isset($goodsInfo['supplier_name']) || mb_strlen($goodsInfo['supplier_name']) == 0 || mb_strlen($goodsInfo['supplier_name']) > 32) {
            $result['msg'] = 'supplier_name异常';
            return $result;
        }
        $result['data']['supplier_name'] = $goodsInfo['supplier_name'];

        if (!isset($goodsInfo['model_name']) || mb_strlen($goodsInfo['model_name']) == 0 || mb_strlen($goodsInfo['model_name']) > 32) {
            $result['msg'] = 'model_name异常';
            return $result;
        }
        $result['data']['model_name'] = $goodsInfo['model_name'];

        if (!isset($goodsInfo['price']) || !is_numeric($goodsInfo['price']) || $goodsInfo['price'] < 0) {
            $result['msg'] = 'price异常';
            return $result;
        }
        $result['data']['price'] = floatval($goodsInfo['price']);

        // 判断是否绑定了课程
        if (!empty($goodsInfo['course_id'])) {
            $goodsInfo['course_id'] = intval($goodsInfo['course_id']);
            if ($goodsInfo['course_id'] <= 0) {
                $result['msg'] = 'course_id异常';
                return $result;
            }
            $result['data']['course_id'] = $goodsInfo['course_id'];
        } else {
            // 如果没有绑定课程,则售价必填
            if (!isset($goodsInfo['sale_price']) || !is_numeric($goodsInfo['sale_price']) || $goodsInfo['sale_price'] <= 0 || $goodsInfo['sale_price'] >= 1000000) {
                $result['msg'] = 'sale_price异常';
                return $result;
            }
            $result['data']['sale_price'] = round(floatval($goodsInfo['sale_price']), 2);
        }

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

    public function addGoodsHandle($userInfo, $goodsInfo) {
        $result = [
            'res' => false,
            'msg' => '保存成功',
            'data' => [],
        ];

        // 判断省份是否存在
        if ($goodsInfo['province_name'] != '全国') {
            $areaProvince = (new AreaProvinceModel())->findDataWithField(['name' => $goodsInfo['province_name']]);
            if (empty($areaProvince)) {
                $result['msg'] = '省份不存在';
                return $result;
            }
        }

        $goodsName = $goodsInfo['province_name'] . $goodsInfo['category_name'] . $goodsInfo['supplier_name'] . $goodsInfo['model_name'];
        if (strpos($goodsName, '%%') !== false) {
            $result['msg'] = '商品名称包含非法字符%%';
            return $result;
        }

        if (!empty($goodsInfo['course_id'])) {
            // 校验课程是否存在
            $courseInfo = (new Course())->findDataWithField(['id' => $goodsInfo['course_id']], ['*']);
            if (empty($courseInfo)) {
                $result['msg'] = '课程不存在';
                return $result;
            }
        }

        // 写入
        $insertData = [
            'province_name' => $goodsInfo['province_name'],
            'category_name' => $goodsInfo['category_name'],
            'supplier_name' => $goodsInfo['supplier_name'],
            'model_name' => $goodsInfo['model_name'],
            'goods_name' => $goodsName,
            'price' => $goodsInfo['price'],
            'created_by' => $userInfo['id'],
            'course_id' => $goodsInfo['course_id'] ?? 0,
        ];
        if (empty($insertData['course_id'])) {
            $insertData['sale_price'] = $goodsInfo['sale_price'];
        }

        $insertRes = (new Goods())->insertData($insertData);
        if (false === $insertRes) {
            $result['msg'] = '保存失败';
            return $result;
        }

        (new LogModel())->insertData(['operator' => $userInfo['id'] ?? 0, 'url' => '添加商品', 'type' => 1, 'content' => json_encode(['data' => $insertData], JSON_UNESCAPED_UNICODE)]);

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

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

        if ($searchParam['province_name'] !== '') {
            $result['data']['province_name'] = $searchParam['province_name'];
        }

        if ($searchParam['category_name'] !== '') {
            $result['data']['category_name'] = $searchParam['category_name'];
        }

        if ($searchParam['supplier_name'] !== '') {
            $result['data']['supplier_name'] = $searchParam['supplier_name'];
        }

        if ($searchParam['model_name'] !== '') {
            $result['data']['model_name'] = $searchParam['model_name'];
        }

        if ($searchParam['goods_name'] !== '') {
            $result['data']['goods_name'] = $searchParam['goods_name'];
        }

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

        if (!empty($searchParam['is_export'])) {
            $result['data']['is_export'] = 1;
        } else {
            $result['data']['is_export'] = 0;
        }

        $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'] > 1000) {
            $result['data']['page_size'] = 20;
        }

        return $result;
    }

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

        $goodsWhere = [];

        if (isset($searchParam['province_name'])) {
            $goodsWhere['province_name'] = $searchParam['province_name'];
        }

        if (isset($searchParam['category_name'])) {
            $goodsWhere[] = ['category_name', 'like', '%' . $searchParam['category_name'] . '%'];
        }

        if (isset($searchParam['supplier_name'])) {
            $goodsWhere[] = ['supplier_name', 'like', '%' . $searchParam['supplier_name'] . '%'];
        }

        if (isset($searchParam['model_name'])) {
            $goodsWhere[] = ['model_name', 'like', '%' . $searchParam['model_name'] . '%'];
        }

        if (isset($searchParam['goods_name'])) {
            $goodsWhere[] = ['goods_name', 'like', '%' . $searchParam['goods_name'] . '%'];
        }

        if (isset($searchParam['status'])) {
            $goodsWhere['status'] = $searchParam['status'];
        }

        $goodsModel = new Goods();
        $goodsList = $goodsModel->selectDataWithPage($goodsWhere, ['id', 'province_name', 'category_name', 'supplier_name', 'model_name', 'goods_name', 'price', 'status', 'course_id', 'sale_price'], $searchParam['page_size'], 'id', 'DESC');

        // 拿到所有的课程id
        $courseIds = array_unique(array_filter(array_column($goodsList['data'], 'course_id')));
        $courseIdRelatedInfo = [];
        if (!empty($courseIds)) {
            $courseList = (new Course())->selectDataByIds($courseIds, ['*']);
            $courseIdRelatedInfo = array_column($courseList, null, 'id');
        }

        foreach ($goodsList['data'] as $index => $value) {
            $goodsList['data'][$index]['course_name'] = $courseIdRelatedInfo[$value['course_id']]['name'] ?? '';
            $goodsList['data'][$index]['sale_price'] = round($courseIdRelatedInfo[$value['course_id']]['sale_price'] ?? $value['sale_price'], 2);
        }

        if (!empty($searchParam['is_export'])) {
            if (empty($goodsList['total'])) {
                $result['msg'] = '暂无可导出的记录';
                return $result;
            }

            $this->exportGoodsHandle($goodsWhere);
            exit();
        }

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

    // 导出给财务
    protected function exportGoodsHandle($goodsWhere) {
        // 设置表头
        $title = ['省份', '商品类别', '供货商名称', '型号', '商品名称'];

        $goodsModel = new Goods();
        $goodsWhere['deleted_at'] = null;

        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->setTitle('商品');

        // 标题栏字母初始化
        $firstLevel = range('A', 'Z');
        // 标题栏结果初始化
        $titleCell = $firstLevel;

        //定义字母循环的次数
        $loopNum = 7;//8*26即为导出的列数上限
        for ($i = 0; $i < $loopNum; $i++) {
            foreach ($firstLevel as $firstValue) {
                $titleCell[] = $firstLevel[$i] . $firstValue;
            }
        }

        //根据列数获取对应的单元格索引
        $cellIndexArr = array_slice($titleCell, 0, count($title));

        // 设置标题
        foreach ($cellIndexArr as $cellIndex => $cellValue) {
            $worksheet->setcellvalue($cellValue . '1', $title[$cellIndex]);

            // 设置宽度30写死
            $worksheet->getColumnDimension($cellValue)->setWidth(30);
        }

        $totalNum = 1;

        // 获取
        $goodsOrm = DB::table('yh_goods')->where($goodsWhere);
        $goodsOrm->chunkById(100, function($list) use (&$totalNum, &$worksheet, $cellIndexArr){
            $goodsList = $list->toArray();

            // 设置标题+内容
            foreach ($goodsList as $goodsInfo) {
                // 交易记录信息
                $goodsInfo = (array)$goodsInfo;

                $exportGoods = [
                    $goodsInfo['province_name'],
                    $goodsInfo['category_name'],
                    $goodsInfo['supplier_name'],
                    $goodsInfo['model_name'],
                    $goodsInfo['goods_name'],
                ];

                $cellTitleIndex = $totalNum + 1;
                foreach ($cellIndexArr as $cellIndex => $cellValue) {
                    $worksheet->setcellvalue($cellValue . $cellTitleIndex, $exportGoods[$cellIndex]);
                }

                $totalNum++;
            }
        });

        $worksheet->getStyle('A1:' . end($cellIndexArr) . $totalNum)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,);
        $worksheet->getStyle('A1:' . end($cellIndexArr) . $totalNum)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,);
        $worksheet->getStyle('A1:' . end($cellIndexArr) . $totalNum)->applyFromArray([
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, // 边框样式
                    'color' => ['argb' => \PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLACK], // 边框颜色
                ],
            ],
        ]);

        // 设置首行字体
        $worksheet->getStyle('A1:F1')->getFont()->setSize(13)->setBold(true);

        $filename = '商品导出-' . date('Ymd') . '.xlsx';

        header("Access-Control-Allow-Origin: *");
        header('Content-Type: application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

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

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

        if (!isset($goodsInfo['goods_ids'])) {
            $result['msg'] = 'goods_ids异常';
            return $result;
        }

        $goodsIdsArr = explode(',', $goodsInfo['goods_ids']);
        $goodsIdsArr = array_filter(array_unique($goodsIdsArr));
        if (empty($goodsIdsArr)) {
            $result['msg'] = 'goods_ids异常';
            return $result;
        }

        foreach ($goodsIdsArr as $index => $goodsId) {
            if (!is_numeric($goodsId) || $goodsId <= 0) {
                $result['msg'] = 'goods_ids异常';
                return $result;
            }
            $goodsIdsArr[$index] = intval($goodsId);
        }
        $goodsIdsArr = array_unique($goodsIdsArr);

        // 校验交易信息是否存在
        $goodsModel = new Goods();
        $existedGoodsInfo = $goodsModel->selectDataByIds($goodsIdsArr, ['id']);
        if (count($existedGoodsInfo) != count($goodsIdsArr)) {
            $result['msg'] = '商品不存在';
            return $result;
        }

        $updateGoodsRes = $goodsModel->updateDataByIds('id', $goodsIdsArr, ['status' => $goodsInfo['status']]);
        if (false === $updateGoodsRes) {
            $result['msg'] = '操作失败';
            return $result;
        }

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

    public function importGoodsHandle($file, $userInfo) {
        $result = [
            'res' => false,
            'msg' => '导入成功',
            'data' => [],
        ];

        if (empty($file)) {
            $result['msg'] = '请上传文件';
            return $result;
        }

        $extension = $file->getClientOriginalExtension();
        if (!in_array($extension, ['xlsx'])) {
            $result['msg'] = '不支持的文件类型';
            return $result;
        }

        // 加载Excel文件
        $spreadsheet = IOFactory::load($file->getRealPath());

        // 获取活动工作表
        $this->workSheet = $spreadsheet->getActiveSheet();
        $list = $this->workSheet->toArray();
        if (!is_array($list) || count($list) <= 1) {
            $result['msg'] = '文件数据不存在';
            return $result;
        }

        // 获取所有的省份信息
        $provinceInfos = (new AreaProvinceModel())->selectDataWithField([], ['name']);
        $provinceInfos = array_column($provinceInfos, null, 'name');
        $provinceInfos['全国'] = [];

        $finalData = [];
        $specialChars = ["\r\n", "\n", "\t", " "];
        foreach ($list as $index => $info) {
            $line = $index + 1;

            $info = array_map(function($item) use ($specialChars) {
                return trim($item);
            }, $info);

            if ($index == 0) {
                $title = $info;
                continue;
            }

            // 判断最后一行
            $isEnd = true;
            foreach ($info as $v) {
                if (!empty($v)) {
                    $isEnd = false;
                    break;
                }
            }

            if ($isEnd) {
                break;
            }

            $goodsInfo = array_combine($title, array_slice($info, 0, count($title)));
            $goodsInfo['line_number'] = $line;

            $checkDataRes = $this->checkGoodsExcelDataFormat($goodsInfo);
            if ($checkDataRes['res'] === false) {
                $result['msg'] = $checkDataRes['msg'] ?? '数据不合法';
                return $result;
            }

            if (!isset($provinceInfos[$goodsInfo['省份']])) {
                $result['msg'] = '第' . $line . '行: [省份]不存在';
                return $result;
            }

            $finalData[] = $goodsInfo;
        }

        $multiInsertGoodsData = [];
        foreach ($finalData as $goodsData) {
            $tmp = [
                'province_name' => $goodsData['省份'] ?? '',
                'category_name' => $goodsData['商品类别'] ?? '',
                'supplier_name' => $goodsData['供货商名称'] ?? '',
                'model_name' => $goodsData['型号'] ?? '',
                'price' => $goodsData['成本价'] ?? 0,
                'created_by' => $userInfo['id'],
                'origin' => 2,
            ];
            $tmp['goods_name'] = $tmp['province_name'] . $tmp['category_name'] . $tmp['supplier_name'] . $tmp['model_name'];
            if (strpos($tmp['goods_name'], '%%') !== false) {
                $result['msg'] = '商品名称包含非法字符%%';
                return $result;
            }

            $multiInsertGoodsData[] = $tmp;
        }

        if (!empty($multiInsertGoodsData)) {
            $insertRes = (new Goods())->insertMultiData($multiInsertGoodsData);
            if (false === $insertRes) {
                $result['msg'] = '导入失败';
                return $result;
            }
        }

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

    private function checkGoodsExcelDataFormat($lineData) {
        $result = [
            'res' => false,
            'msg' => '校验通过',
            'data' => [],
        ];

        // 校验数据合法性
        if (!isset($lineData['省份']) || $lineData['省份'] === '' || mb_strlen($lineData['省份']) > 32) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [省份]不合法';
            return $result;
        }

        if (!isset($lineData['商品类别']) || $lineData['商品类别'] === '' || mb_strlen($lineData['商品类别']) > 32) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [商品类别]不合法';
            return $result;
        }

        if (!isset($lineData['供货商名称']) || $lineData['供货商名称'] === '' || mb_strlen($lineData['供货商名称']) > 32) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [供货商名称]不合法';
            return $result;
        }

        if (!isset($lineData['型号']) || $lineData['型号'] === '' || mb_strlen($lineData['型号']) > 32) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [型号]不合法';
            return $result;
        }

        if (!isset($lineData['成本价']) || !is_numeric($lineData['成本价']) || $lineData['成本价'] < 0 || $lineData['成本价'] > 999999.99) {
            $result['msg'] = '第' . $lineData['line_number'] . '行: [成本价]不合法';
            return $result;
        }

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

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

        if (!isset($goodsInfo['goods_id']) || !is_numeric($goodsInfo['goods_id']) || $goodsInfo['goods_id'] <= 0) {
            $result['msg'] = '商品id异常';
            return $result;
        }
        $goodsInfo['goods_id'] = intval($goodsInfo['goods_id']);

        if (!isset($goodsInfo['price']) || !is_numeric($goodsInfo['price']) || $goodsInfo['price'] < 0) {
            $result['msg'] = '价格异常';
            return $result;
        }
        $goodsInfo['price'] = floatval($goodsInfo['price']);

        // 校验交易信息是否存在
        $goodsModel = new Goods();
        $existedGoodsInfo = $goodsModel->findDataWithField(['id' => $goodsInfo['goods_id']], ['*']);
        if (empty($existedGoodsInfo)) {
            $result['msg'] = '商品不存在';
            return $result;
        }

        if ($existedGoodsInfo['price'] > 0) {
            $result['msg'] = '成本价格不允许编辑';
            return $result;
        }

        if (empty($userInfo['is_admin']) && $userInfo['id'] != $existedGoodsInfo['created_by']) {
            $result['msg'] = '您非此商品创建者,不允许编辑';
            return $result;
        }

        DB::beginTransaction();

        $updateData = ['price' => $goodsInfo['price']];
        $updateGoodsRes = $goodsModel->updateData(['id' => $goodsInfo['goods_id']], $updateData);
        if (false === $updateGoodsRes) {
            DB::rollBack();
            $result['msg'] = '操作失败';
            return $result;
        }

        // 写入日志
        $insertLogRes = (new LogModel())->insertData([
            'operator' => $userInfo['id'],
            'type' => 2,
            'url' => '商品',
            'operate_name' => '更新商品成本价',
            'object_id' => $goodsInfo['goods_id'],
            'content' => json_encode($updateData, JSON_UNESCAPED_UNICODE),
        ]);
        if (false === $insertLogRes) {
            DB::rollBack();
            $result['msg'] = '日志记录失败';
            return $result;
        }

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

    public function checkGoodsRelatedAppletHandle($goodsInfo) {
        $result = [
            'res' => false,
            'msg' => '校验成功',
            'data' => [],
        ];

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

        // 判断是否绑定了课程
        if (!empty($goodsInfo['course_id'])) {
            $goodsInfo['course_id'] = intval($goodsInfo['course_id']);
            if ($goodsInfo['course_id'] <= 0) {
                $result['msg'] = 'course_id异常';
                return $result;
            }
            $result['data']['course_id'] = $goodsInfo['course_id'];
        } else {
            // 如果没有绑定课程,则售价必填
            if (!isset($goodsInfo['sale_price']) || !is_numeric($goodsInfo['sale_price']) || $goodsInfo['sale_price'] <= 0 || $goodsInfo['sale_price'] >= 1000000) {
                $result['msg'] = 'sale_price异常';
                return $result;
            }
            $result['data']['sale_price'] = round(floatval($goodsInfo['sale_price']), 2);
        }

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

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

        $goodsModel = new Goods();
        $existedGoodsInfo = $goodsModel->findDataWithField(['id' => $goodsInfo['goods_id']], ['*']);
        if (empty($existedGoodsInfo)) {
            $result['msg'] = '商品不存在';
            return $result;
        }

        $updateData = [];

        if (!empty($goodsInfo['course_id'])) {
            // 校验课程是否存在
            $courseInfo = (new Course())->findDataWithField(['id' => $goodsInfo['course_id']], ['*']);
            if (empty($courseInfo)) {
                $result['msg'] = '课程不存在';
                return $result;
            }

            $updateData['course_id'] = $goodsInfo['course_id'];
            $updateData['sale_price'] = 0;
        } else {
            $updateData['course_id'] = 0;
            $updateData['sale_price'] = $goodsInfo['sale_price'] ?? 0;
        }

        DB::beginTransaction();

        $updateGoodsRes = $goodsModel->updateData(['id' => $goodsInfo['goods_id']], $updateData);
        if (false === $updateGoodsRes) {
            DB::rollBack();
            $result['msg'] = '操作失败';
            return $result;
        }

        // 写入日志
        $insertLogRes = (new LogModel())->insertData([
            'operator' => $userInfo['id'],
            'type' => 2,
            'url' => '商品',
            'operate_name' => '商品关联小程序商品',
            'object_id' => $goodsInfo['goods_id'],
            'content' => json_encode($updateData, JSON_UNESCAPED_UNICODE),
        ]);
        if (false === $insertLogRes) {
            DB::rollBack();
            $result['msg'] = '日志记录失败';
            return $result;
        }

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

    public function getDealStatisticsHandle($searchParam) {
        $result = [
            'res' => false,
            'msg' => '获取成功',
            'data' => [
                'total' => [],
                'date_list' => [],
            ],
        ];

        if ($searchParam['date_start'] === '') {
            $searchParam['date_start'] = date('Y-m') . '-01';
        }

        if ($searchParam['date_end'] === '') {
            $searchParam['date_end'] = date('Y-m-d');
        }

        $startTimestamp = strtotime($searchParam['date_start']);
        $endTimestamp = strtotime($searchParam['date_end']);
        if (false === $startTimestamp || false === $endTimestamp || $startTimestamp > $endTimestamp) {
            $result['msg'] = '日期选择异常';
            return $result;
        }

        $dateRange = [];
        while ($startTimestamp <= $endTimestamp) {
            $dateRange[] = date('Y-m-d', $startTimestamp);
            $startTimestamp = strtotime('+1 day', $startTimestamp);
        }

        $dealDateRelatedDealRecord = [];
        foreach ($dateRange as $rangeDate) {
            $dealDateRelatedDealRecord[$rangeDate] = [
                'zongbu_people' => 0,
                'zongbu_money' => 0,
                'fenxiao_people' => 0,
                'fenxiao_money' => 0,
                'kaoyan_people' => 0,
                'kaoyan_money' => 0,
                'wangxiao_people' => 0,
                'wangxiao_money' => 0,
            ];
        }

        // 获取所有的符合条件的订单
        $dealRecordModel = new DealRecord();

        $dealRecordWhere = [];
        $dealRecordWhere['status'] = 1;
        $dealRecordWhere['check_status'] = 2;
        $dealRecordWhere[] = ['deal_date', '>=', $searchParam['date_start']];
        $dealRecordWhere[] = ['deal_date', '<=', $searchParam['date_end']];

        $dealRecordList = $dealRecordModel->selectDataWithField($dealRecordWhere, ['department', 'deduction_money', 'deal_date']);

        // 开始统计
        foreach ($dealRecordList as $dealRecord) {
            // 部门, 1: 总部, 2: 分校, 3: 考研, 4: 网校
            switch ($dealRecord['department']) {
                case 1:
                    $dealDateRelatedDealRecord[$dealRecord['deal_date']]['zongbu_people']++;
                    $dealDateRelatedDealRecord[$dealRecord['deal_date']]['zongbu_money'] += $dealRecord['deduction_money'];
                    break;
                case 2:
                    $dealDateRelatedDealRecord[$dealRecord['deal_date']]['fenxiao_people']++;
                    $dealDateRelatedDealRecord[$dealRecord['deal_date']]['fenxiao_money'] += $dealRecord['deduction_money'];
                    break;
                case 3:
                    $dealDateRelatedDealRecord[$dealRecord['deal_date']]['kaoyan_people']++;
                    $dealDateRelatedDealRecord[$dealRecord['deal_date']]['kaoyan_money'] += $dealRecord['deduction_money'];
                    break;
                case 4:
                    $dealDateRelatedDealRecord[$dealRecord['deal_date']]['wangxiao_people']++;
                    $dealDateRelatedDealRecord[$dealRecord['deal_date']]['wangxiao_money'] += $dealRecord['deduction_money'];
                    break;
                default:
                    break;
            }
        }

        $result['data']['total']['zongbu_people'] = array_sum(array_column($dealDateRelatedDealRecord, 'zongbu_people'));
        $result['data']['total']['zongbu_money'] = round(array_sum(array_column($dealDateRelatedDealRecord, 'zongbu_money')), 2);
        $result['data']['total']['fenxiao_people'] = array_sum(array_column($dealDateRelatedDealRecord, 'fenxiao_people'));
        $result['data']['total']['fenxiao_money'] = round(array_sum(array_column($dealDateRelatedDealRecord, 'fenxiao_money')), 2);
        $result['data']['total']['kaoyan_people'] = array_sum(array_column($dealDateRelatedDealRecord, 'kaoyan_people'));
        $result['data']['total']['kaoyan_money'] = round(array_sum(array_column($dealDateRelatedDealRecord, 'kaoyan_money')), 2);
        $result['data']['total']['wangxiao_people'] = array_sum(array_column($dealDateRelatedDealRecord, 'wangxiao_people'));
        $result['data']['total']['wangxiao_money'] = round(array_sum(array_column($dealDateRelatedDealRecord, 'wangxiao_money')), 2);
        $result['data']['total']['total_people'] = $result['data']['total']['zongbu_people'] + $result['data']['total']['fenxiao_people'] + $result['data']['total']['kaoyan_people'] + $result['data']['total']['wangxiao_people'];
        $result['data']['total']['total_money'] = round($result['data']['total']['zongbu_money'] + $result['data']['total']['fenxiao_money'] + $result['data']['total']['kaoyan_money'] + $result['data']['total']['wangxiao_money'], 2);
        $result['data']['date_list'] = [];
        foreach ($dealDateRelatedDealRecord as $dealDate => $dealDateStatis) {
            $dealDateStatis['deal_date'] = $dealDate;
            $dealDateStatis['total_people'] = $dealDateStatis['zongbu_people'] + $dealDateStatis['fenxiao_people'] + $dealDateStatis['kaoyan_people'] + $dealDateStatis['wangxiao_people'];
            $dealDateStatis['zongbu_money'] = round($dealDateStatis['zongbu_money'], 2);
            $dealDateStatis['fenxiao_money'] = round($dealDateStatis['fenxiao_money'], 2);
            $dealDateStatis['kaoyan_money'] = round($dealDateStatis['kaoyan_money'], 2);
            $dealDateStatis['wangxiao_money'] = round($dealDateStatis['wangxiao_money'], 2);
            $dealDateStatis['total_money'] = round($dealDateStatis['zongbu_money'] + $dealDateStatis['fenxiao_money'] + $dealDateStatis['kaoyan_money'] + $dealDateStatis['wangxiao_money'], 2);

            $result['data']['date_list'][] = $dealDateStatis;
        }

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

    public function getDealGoodsStatisticsHandle($searchParam) {
        $result = [
            'res' => false,
            'msg' => '获取成功',
            'data' => [
                'total' => [
                    'deduction_money' => 0,
                    'cost_money' => 0,
                    'cost_ratio' => '-',
                ],
                'goods_list' => [],
            ],
        ];

        if ($searchParam['date_start'] === '') {
            $searchParam['date_start'] = date('Y-m') . '-01';
        }

        if ($searchParam['date_end'] === '') {
            $searchParam['date_end'] = date('Y-m-d');
        }

        $startTimestamp = strtotime($searchParam['date_start']);
        $endTimestamp = strtotime($searchParam['date_end']);
        if (false === $startTimestamp || false === $endTimestamp || $startTimestamp > $endTimestamp) {
            $result['msg'] = '日期选择异常';
            return $result;
        }

        // 获取所有的符合条件的订单
        $dealRecordModel = new DealRecord();
        $dealRecordGoodsModel = new DealRecordGoods();
        $goodsModel = new Goods();

        $dealRecordWhere = [];
        $dealRecordWhere['status'] = 1;
        $dealRecordWhere['check_status'] = 2;
        $dealRecordWhere[] = ['deal_date', '>=', $searchParam['date_start']];
        $dealRecordWhere[] = ['deal_date', '<=', $searchParam['date_end']];
        $dealRecordList = $dealRecordModel->selectDataWithField($dealRecordWhere, ['id']);
        if (empty($dealRecordList)) {
            $result['res'] = true;
            return $result;
        }

        $allDealRecordIds = array_column($dealRecordList, 'id');
        // 获取交易记录下的所有商品信息
        $getDealGoodsList = $dealRecordGoodsModel->selectDataByWhereFieldAndIds([], 'deal_record_id', $allDealRecordIds, ['province_name', 'category_name', 'goods_name', 'buy_number', 'deduction_money']);
        if (empty($getDealGoodsList)) {
            $result['res'] = true;
            return $result;
        }

        // 处理一下商品省份+分类的顺序,全国的排在前面展示
        $dealGoodsList = [];
        $quanGuoGood = $othersGoods = [];
        foreach ($getDealGoodsList as $dealList) {
            if ($dealList['province_name'] == '全国') {
                $quanGuoGood[] = $dealList;
            } else {
                $othersGoods[] = $dealList;
            }
        }
        $dealGoodsList = array_merge($quanGuoGood, $othersGoods);

        // 拿到所有的商品信息,获取商品的成本价
        $allGoodsName = array_unique(array_column($dealGoodsList, 'goods_name'));
        $allGoodsInfo = $goodsModel->selectDataByWhereFieldAndIdsOrder([], 'goods_name', $allGoodsName, ['goods_name', 'price']);
        if (empty($dealGoodsList)) {
            $result['res'] = true;
            return $result;
        }
        $goodsRelatedPrice = array_column($allGoodsInfo, 'price', 'goods_name');

        // 开始统计
        $goodsStatis = [];
        foreach ($dealGoodsList as $dealGoodsInfo) {
            if (!isset($goodsRelatedPrice[$dealGoodsInfo['goods_name']])) {
                continue;
            }

            $key = $dealGoodsInfo['province_name'] . '+' . $dealGoodsInfo['category_name'];
            if (!isset($goodsStatis[$key])) {
                $goodsStatis[$key] = [
                    'deduction_money' => 0,
                    'cost_money' => 0,
                ];
            }

            $goodsStatis[$key]['deduction_money'] += $dealGoodsInfo['deduction_money'];
            $goodsStatis[$key]['cost_money'] += $goodsRelatedPrice[$dealGoodsInfo['goods_name']] * $dealGoodsInfo['buy_number'];
        }

        foreach ($goodsStatis as $goodsCategory => $goodsStatisInfo) {
            $result['data']['total']['deduction_money'] += $goodsStatisInfo['deduction_money'];
            $result['data']['total']['cost_money'] += $goodsStatisInfo['cost_money'];

            $tmp = [
                'goods_category' => $goodsCategory,
                'deduction_money' => round($goodsStatisInfo['deduction_money'], 2),
                'cost_money' => round($goodsStatisInfo['cost_money'], 2),
            ];
            $tmp['cost_ratio'] = ($goodsStatisInfo['deduction_money'] > 0) ? round($goodsStatisInfo['cost_money'] / $goodsStatisInfo['deduction_money'] * 100, 2) . '%' : '-';

            $result['data']['goods_list'][] = $tmp;
        }

        $result['data']['total']['deduction_money'] = round($result['data']['total']['deduction_money'], 2);
        $result['data']['total']['cost_money'] = round($result['data']['total']['cost_money'], 2);
        $result['data']['total']['cost_ratio'] = ($result['data']['total']['deduction_money'] > 0) ? round($result['data']['total']['cost_money'] / $result['data']['total']['deduction_money'] * 100, 2) . '%' : '-';

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

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

        $currentYearMonth = date('Y-m');

        if ($searchParam['month'] === '') {
            $searchParam['month'] = date('Y-m');
        }

        if (!isValidDateTime($searchParam['month'], 'Y-m')) {
            $result['msg'] = '日期选择异常';
            return $result;
        }

        $dateStart = $searchParam['month'] . '-01';
        $dateEnd = date('Y-m-t', strtotime($dateStart));

        $days = date('t', strtotime($dateStart));
        if ($searchParam['month'] == $currentYearMonth) {
            $days = intval(date('d'));
            $dateEnd = date('Y-m-d');
        }

        $dateRange = [];
        for ($i = 1; $i <= $days; $i++) {
            if ($i < 10) {
                $dateRange[] = $searchParam['month'] . '-0' . $i;
            } else {
                $dateRange[] = $searchParam['month'] . '-' . $i;
            }
        }
        $result['data']['date'] = $dateRange;

        // 获取所有的省份(澳门算总部的,不计算在分校里)
        $allProvince = (new AreaProvinceModel())->selectDataWithField([['name', '<>', '澳门']], ['name']);
        $allProvinceName = array_column($allProvince, 'name');

        $totalStatis = [
            'total' => [
                'total_people' => 0,
                'total_money' => 0,
            ],
        ];
        foreach ($dateRange as $d) {
            $totalStatis[$d] = [
                'total_people' => 0,
                'total_money' => 0,
            ];
        }

        $dealBranchRelatedDateStatis = [];
        foreach ($allProvinceName as $provinceName) {
            $dealBranchRelatedDateStatis[$provinceName] = [
                'total' => [
                    'total_people' => 0,
                    'total_money' => 0,
                ],
            ];
            foreach ($dateRange as $d) {
                $dealBranchRelatedDateStatis[$provinceName][$d] = [
                    'total_people' => 0,
                    'total_money' => 0,
                ];
            }
        }

        // 获取所有的符合条件的订单
        $dealRecordModel = new DealRecord();

        $dealRecordWhere = [];
        $dealRecordWhere['status'] = 1;
        $dealRecordWhere['check_status'] = 2;
        $dealRecordWhere['department'] = 2;// 只要分校的
        $dealRecordWhere[] = ['deal_date', '>=', $dateStart];
        $dealRecordWhere[] = ['deal_date', '<=', $dateEnd];

        $dealRecordList = $dealRecordModel->selectDataWithField($dealRecordWhere, ['province_name', 'deduction_money', 'deal_date']);

        // 开始统计
        foreach ($dealRecordList as $dealRecord) {
            if (isset($dealBranchRelatedDateStatis[$dealRecord['province_name']])) {
                $totalStatis['total']['total_people']++;
                $totalStatis['total']['total_money'] += $dealRecord['deduction_money'];
                $totalStatis[$dealRecord['deal_date']]['total_people']++;
                $totalStatis[$dealRecord['deal_date']]['total_money'] += $dealRecord['deduction_money'];

                $dealBranchRelatedDateStatis[$dealRecord['province_name']]['total']['total_people']++;
                $dealBranchRelatedDateStatis[$dealRecord['province_name']]['total']['total_money'] += $dealRecord['deduction_money'];
                $dealBranchRelatedDateStatis[$dealRecord['province_name']][$dealRecord['deal_date']]['total_people']++;
                $dealBranchRelatedDateStatis[$dealRecord['province_name']][$dealRecord['deal_date']]['total_money'] += $dealRecord['deduction_money'];
            }
        }

        $returnData = [];
        $tmp = [
            'name' => '总计',
            'total' => $totalStatis['total'],
            'date_list' => [],
        ];
        unset($totalStatis['total']);
        foreach ($totalStatis as $totalDate => $totalData) {
            $totalData['date'] = $totalDate;
            $tmp['date_list'][] = $totalData;
        }
        $returnData[] = $tmp;

        foreach ($dealBranchRelatedDateStatis as $provinceName => $detail) {
            $detail['total']['total_money'] = round($detail['total']['total_money'], 2);
            $tmp = [
                'name' => $provinceName,
                'total' => $detail['total'] ?? [],
                'date_list' => [],
            ];

            unset($detail['total']);
            foreach ($detail as $k => $v) {
                $v['total_money'] = round($v['total_money'], 2);
                $v['date'] = $k;
                $tmp['date_list'][] = $v;
            }

            $returnData[] = $tmp;
        }

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

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

        if ($searchParam['month'] === '') {
            $searchParam['month'] = date('Y-m');
        }

        if (!isValidDateTime($searchParam['month'], 'Y-m')) {
            $result['msg'] = '日期选择异常';
            return $result;
        }

        $dateStart = $searchParam['month'] . '-01';
        $dateEnd = date('Y-m-t', strtotime($dateStart));

        // 获取所有的符合条件的订单
        $dealRecordModel = new DealRecord();
        $dealRecordGoodsModel = new DealRecordGoods();
        $goodsModel = new Goods();

        $dealRecordWhere = [];
        $dealRecordWhere['status'] = 1;
        $dealRecordWhere['check_status'] = 2;
        $dealRecordWhere[] = ['deal_date', '>=', $dateStart];
        $dealRecordWhere[] = ['deal_date', '<=', $dateEnd];
        if ($searchParam['province_name'] !== '') {
            $dealRecordWhere['department'] = 2;
            $dealRecordWhere['province_name'] = $searchParam['province_name'];
        }
        $dealRecordList = $dealRecordModel->selectDataWithField($dealRecordWhere, ['id', 'department', 'province_name']);
        if (empty($dealRecordList)) {
            $result['res'] = true;
            return $result;
        }
        $dealRecordIdRelatedInfo = array_column($dealRecordList, null, 'id');

        $allDealRecordIds = array_column($dealRecordList, 'id');
        // 获取交易记录下的所有商品信息
        $getDealGoodsList = $dealRecordGoodsModel->selectDataByWhereFieldAndIds([], 'deal_record_id', $allDealRecordIds, ['deal_record_id', 'province_name', 'category_name', 'goods_name', 'buy_number', 'deduction_money']);
        if (empty($getDealGoodsList)) {
            $result['res'] = true;
            return $result;
        }

        // 处理一下商品省份+分类的顺序,全国的排在前面展示
        $dealGoodsList = $categoryList = [];
        $quanGuoGood = $othersGoods = $quanGuoCategory = $othersCategory = [];
        foreach ($getDealGoodsList as $dealInfo) {
            if ($dealInfo['province_name'] == '全国') {
                $quanGuoGood[] = $dealInfo;
                $quanGuoCategory[] = $dealInfo['province_name'] . '+' . $dealInfo['category_name'];
            } else {
                $othersGoods[] = $dealInfo;
                $othersCategory[] = $dealInfo['province_name'] . '+' . $dealInfo['category_name'];
            }
        }
        $dealGoodsList = array_merge($quanGuoGood, $othersGoods);
        $category = array_merge(array_unique($quanGuoCategory), array_unique($othersCategory));
        $result['data']['category'] = $category;

        // 拿到所有的商品信息,获取商品的成本价
        $allGoodsName = array_unique(array_column($dealGoodsList, 'goods_name'));
        $allGoodsInfo = $goodsModel->selectDataByWhereFieldAndIdsOrder([], 'goods_name', $allGoodsName, ['goods_name', 'price']);
        if (empty($dealGoodsList)) {
            $result['res'] = true;
            return $result;
        }
        $goodsRelatedPrice = array_column($allGoodsInfo, 'price', 'goods_name');

        // 获取所有的省份(澳门算总部的,不计算在分校里)
        $allProvince = (new AreaProvinceModel())->selectDataWithField([], ['name']);
        $allProvinceName = array_column($allProvince, 'name');

        if ($searchParam['province_name'] !== '') {
            $allProvinceName = [$searchParam['province_name']];
        }

        // 需要统计的维度
        $totalStatis = ['总计', '总部总计', '考研总计', '网校总计', '分校总计'];
        $allStatis = array_merge($totalStatis, $allProvinceName);

        // 统计列表初始化
        $getStatisData = [];
        foreach ($allStatis as $title) {
            $getStatisData[$title]['total'] = [
                'deduction_money' => 0,
                'cost_money' => 0,
            ];

            foreach ($category as $c) {
                $getStatisData[$title][$c] = [
                    'deduction_money' => 0,
                    'cost_money' => 0,
                ];
            }
        }

        // 开始统计
        foreach ($dealGoodsList as $deal) {
            // 该抵扣商品对应的交易记录信息
            if (!isset($dealRecordIdRelatedInfo[$deal['deal_record_id']])) {
                continue;
            }

            // 该抵扣商品的成本价信息
            if (!isset($goodsRelatedPrice[$deal['goods_name']])) {
                continue;
            }

            $currentCategory = $deal['province_name'] . '+' . $deal['category_name'];
            $deductionMoney = $deal['deduction_money'];
            $costMoney = $goodsRelatedPrice[$deal['goods_name']] * $deal['buy_number'];

            $getStatisData['总计']['total']['deduction_money'] += $deductionMoney;
            $getStatisData['总计']['total']['cost_money'] += $costMoney;
            $getStatisData['总计'][$currentCategory]['deduction_money'] += $deductionMoney;
            $getStatisData['总计'][$currentCategory]['cost_money'] += $costMoney;

            // 部门, 1: 总部, 2: 分校, 3: 考研, 4: 网校
            switch ($dealRecordIdRelatedInfo[$deal['deal_record_id']]['department']) {
                case 1:
                    $getStatisData['总部总计']['total']['deduction_money'] += $deductionMoney;
                    $getStatisData['总部总计']['total']['cost_money'] += $costMoney;
                    $getStatisData['总部总计'][$currentCategory]['deduction_money'] += $deductionMoney;
                    $getStatisData['总部总计'][$currentCategory]['cost_money'] += $costMoney;
                    break;
                case 2:
                    if ($dealRecordIdRelatedInfo[$deal['deal_record_id']]['province_name'] == '澳门') {
                        $getStatisData['总部总计']['total']['deduction_money'] += $deductionMoney;
                        $getStatisData['总部总计']['total']['cost_money'] += $costMoney;
                        $getStatisData['总部总计'][$currentCategory]['deduction_money'] += $deductionMoney;
                        $getStatisData['总部总计'][$currentCategory]['cost_money'] += $costMoney;
                        break;
                    }

                    $getStatisData['分校总计']['total']['deduction_money'] += $deductionMoney;
                    $getStatisData['分校总计']['total']['cost_money'] += $costMoney;
                    $getStatisData['分校总计'][$currentCategory]['deduction_money'] += $deductionMoney;
                    $getStatisData['分校总计'][$currentCategory]['cost_money'] += $costMoney;

                    $getStatisData[$dealRecordIdRelatedInfo[$deal['deal_record_id']]['province_name']]['total']['deduction_money'] += $deductionMoney;
                    $getStatisData[$dealRecordIdRelatedInfo[$deal['deal_record_id']]['province_name']]['total']['cost_money'] += $costMoney;
                    $getStatisData[$dealRecordIdRelatedInfo[$deal['deal_record_id']]['province_name']][$currentCategory]['deduction_money'] += $deductionMoney;
                    $getStatisData[$dealRecordIdRelatedInfo[$deal['deal_record_id']]['province_name']][$currentCategory]['cost_money'] += $costMoney;
                    break;
                case 3:
                    $getStatisData['考研总计']['total']['deduction_money'] += $deductionMoney;
                    $getStatisData['考研总计']['total']['cost_money'] += $costMoney;
                    $getStatisData['考研总计'][$currentCategory]['deduction_money'] += $deductionMoney;
                    $getStatisData['考研总计'][$currentCategory]['cost_money'] += $costMoney;
                    break;
                case 4:
                    $getStatisData['网校总计']['total']['deduction_money'] += $deductionMoney;
                    $getStatisData['网校总计']['total']['cost_money'] += $costMoney;
                    $getStatisData['网校总计'][$currentCategory]['deduction_money'] += $deductionMoney;
                    $getStatisData['网校总计'][$currentCategory]['cost_money'] += $costMoney;
                    break;
                default:
                    break;
            }
        }

        $returnStatisData = [];
        foreach ($getStatisData as $tmpTitle => $tmpData) {
            if ($tmpTitle == '澳门') {
                continue;
            }

            if ($searchParam['province_name'] !== '' && in_array($tmpTitle, $totalStatis)) {
                continue;
            }

            $tmp = [
                'name' => $tmpTitle,
                'total' => [
                    'deduction_money' => round($tmpData['total']['deduction_money'], 2),
                    'cost_money' => round($tmpData['total']['cost_money'], 2),
                ],
                'category_list' => [],
            ];
            $tmp['total']['cost_ratio'] = ($tmp['total']['deduction_money'] > 0) ? round($tmp['total']['cost_money'] / $tmp['total']['deduction_money'] * 100, 2) . '%' : '-';

            unset($tmpData['total']);
            foreach ($tmpData as $tmpCategory => $tmpCategoryData) {
                $tmpCategoryStatis = [
                    'category' => $tmpCategory,
                    'deduction_money' => round($tmpCategoryData['deduction_money'], 2),
                    'cost_money' => round($tmpCategoryData['cost_money'], 2),
                ];
                $tmpCategoryStatis['cost_ratio'] = ($tmpCategoryStatis['deduction_money'] > 0) ? round($tmpCategoryStatis['cost_money'] / $tmpCategoryStatis['deduction_money'] * 100, 2) . '%' : '-';

                $tmp['category_list'][] = $tmpCategoryStatis;
            }

            $returnStatisData[] = $tmp;
        }

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

    }

}
