<?php

namespace App\Http\Services;

use App\Models\Category;
use App\Models\Course;
use App\Models\CourseEvaluate;
use App\Models\CourseRelated;
use App\Models\FrontUserModel;
use App\Models\Log as LogModel;
use App\Models\UsersFront;
use App\Models\UsersFrontModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Overtrue\Pinyin\Pinyin;

class CourseService extends BaseService
{

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

        if (!isset($courseInfo['name']) || mb_strlen($courseInfo['name']) == 0 || mb_strlen($courseInfo['name']) > 128) {
            $result['msg'] = '课程名称异常';
            return $result;
        }

        if (!isset($courseInfo['category_id']) || !is_numeric($courseInfo['category_id']) || $courseInfo['category_id'] <= 0) {
            $result['msg'] = '课程分类异常';
            return $result;
        }
        $courseInfo['category_id'] = intval($courseInfo['category_id']);

        if (!isset($courseInfo['sort']) || !is_numeric($courseInfo['sort']) || $courseInfo['sort'] <= 0 || $courseInfo['sort'] > 9999) {
            $result['msg'] = '排序异常';
            return $result;
        }
        $courseInfo['sort'] = intval($courseInfo['sort']);

        if (!isset($courseInfo['course_hour']) || mb_strlen($courseInfo['course_hour']) == 0 || mb_strlen($courseInfo['course_hour']) > 32) {
            $result['msg'] = '单位异常';
            return $result;
        }

        if (!isset($courseInfo['origin_price']) || !is_numeric($courseInfo['origin_price']) || $courseInfo['origin_price'] <= 0 || $courseInfo['origin_price'] >= 1000000) {
            $result['msg'] = '原价格异常';
            return $result;
        }

        if (!isset($courseInfo['sale_price']) || !is_numeric($courseInfo['sale_price']) || $courseInfo['sale_price'] <= 0 || $courseInfo['sale_price'] >= 1000000) {
            $result['msg'] = '销售价格异常';
            return $result;
        }

        if (!isset($courseInfo['description'])) {
            $result['msg'] = '描述异常';
            return $result;
        }
        $courseInfo['description'] = str_replace("<p><br></p>", '', $courseInfo['description']);
        if (mb_strlen($courseInfo['description']) == 0) {
            $result['msg'] = '描述异常';
            return $result;
        }

        if (!isset($courseInfo['gift_desc']) || mb_strlen($courseInfo['gift_desc']) == 0 || mb_strlen($courseInfo['gift_desc']) > 256) {
            $result['msg'] = '赠品异常';
            return $result;
        }

        if (isset($courseInfo['child_course_id'])) {
            if (!is_string($courseInfo['child_course_id'])) {
                $result['msg'] = '子课程异常';
                return $result;
            }

            $childCourseIdArr = array_unique(array_filter(explode(',', $courseInfo['child_course_id'])));
            foreach ($childCourseIdArr as $index => $courseId) {
                if (!is_numeric($courseId) || $courseId <= 0) {
                    $result['msg'] = '子课程异常';
                    return $result;
                }
                $childCourseIdArr[$index] = intval($courseId);
            }
            $courseInfo['child_course_id'] = $childCourseIdArr;
            if (count($courseInfo['child_course_id']) > 10) {
                $result['msg'] = '最多添加10个子课程';
                return $result;
            }

            if (!empty($courseInfo['child_course_id'])) {
                if (!isset($courseInfo['max_select_num']) || $courseInfo['max_select_num'] <= 0 || $courseInfo['max_select_num'] > 9999) {
                    $result['msg'] = '最大可选子课程数异常';
                    return $result;
                }
            }
        }

        if (!isset($courseInfo['head_img']) || mb_strlen($courseInfo['head_img']) == 0 || mb_strlen($courseInfo['head_img']) > 256) {
            $result['msg'] = '课程图片异常';
            return $result;
        }

//        if (!isset($courseInfo['course_introduction'])) {
//            $result['msg'] = '课程介绍异常';
//            return $result;
//        }
//
//        if (!isset($courseInfo['goods_introduction'])) {
//            $result['msg'] = '商品介绍异常';
//            return $result;
//        }

        if (!isset($courseInfo['status']) || $courseInfo['status'] < 0 || $courseInfo['status'] > 2) {
            $result['msg'] = '发布状态异常';
            return $result;
        }

        if (isset($courseInfo['post_type'])) {
            if (!is_numeric($courseInfo['post_type']) || $courseInfo['post_type'] < 1 || $courseInfo['post_type'] > 3) {
                $result['msg'] = '邮寄类型异常';
                return $result;
            }
            $courseInfo['post_type'] = intval($courseInfo['post_type']);

            // 自定义的邮寄类型, 说明
            if ($courseInfo['post_type'] == 3 && (!isset($courseInfo['post_remark']) || mb_strlen($courseInfo['post_remark']) == 0 || mb_strlen($courseInfo['post_remark']) > 256)) {
                $result['msg'] = '邮寄自定义说明异常';
                return $result;
            }
        }

        if (!isset($courseInfo['stock']) || !is_numeric($courseInfo['stock']) || $courseInfo['stock'] <= 0 || $courseInfo['stock'] > 999999) {
            $result['msg'] = '库存异常';
            return $result;
        }
        $courseInfo['stock'] = intval($courseInfo['stock']);

        if (!isset($courseInfo['sales']) || !is_numeric($courseInfo['sales']) || $courseInfo['sales'] <= 0 || $courseInfo['sales'] > 999999) {
            $result['msg'] = '销量异常';
            return $result;
        }
        $courseInfo['sales'] = intval($courseInfo['sales']);

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

    public function addCourseHandle($userInfo, $courseInfo) {
        $result = [
            'res' => false,
            'msg' => '添加成功',
            'data' => [],
        ];

        $courseModel = new Course();

        if (isset($courseInfo['child_course_id'])) {
            // 判断要添加的子课程是否存在
            $existedCourse = $courseModel->selectDataByIds($courseInfo['child_course_id'] ?? [], ['id', 'name', 'status']);
            if (count($existedCourse) != count($courseInfo['child_course_id'])) {
                $result['msg'] = '子课程不存在';
                return $result;
            }
            foreach ($existedCourse as $value) {
                if ($value['status'] != 2) {
                    $result['msg'] = '存在未发布的子课程';
                    return $result;
                }
            }

            // 判断子课程下是否有子课程, 目前课程最多支持2级, 如果有的课程下有子课程, 不允许添加
            $courseRelatedModel = new CourseRelated();
            $existedChildCourse = $courseRelatedModel->selectDataByWhereFieldAndIds([], 'course_id', $courseInfo['child_course_id'] ?? [], ['child_course_id']);
            // 如果这些子课程下已有子课程, 判断子子课程是否还存在, 如果存在则不允许添加
            if (!empty($existedChildCourse)) {
                $existedChildChildCourse = $courseModel->selectDataByIds(array_unique(array_column($existedChildCourse, 'child_course_id')), ['id']);
                if (!empty($existedChildChildCourse)) {
                    $result['msg'] = '子课程下已存在子课程,不允许添加';
                    return $result;
                }
            }
        }

        // 判断课程分类id是否存在
        $categoryModel = new Category();
        $categoryInfo = $categoryModel->findDataWithField(['id' => $courseInfo['category_id']]);
        if (empty($categoryInfo)) {
            $result['msg'] = '课程分类不存在';
            return $result;
        }

        // 开始写入
        DB::beginTransaction();

        $courseCode = $this->generateCourseCode($categoryInfo['name'] ?? '');
        // 判断当前编码是否已存在, 如果是, 重新生成
        while (true) {
            $existCourseCode = $courseModel->findDataWithField(['course_code' => $courseCode], ['id']);
            if (empty($existCourseCode)) {
                break;
            }

            $courseCode = $this->generateCourseCode($categoryInfo['name'] ?? '');
        }

        $courseIntroduction = str_replace("<p><br></p>", '', $courseInfo['course_introduction'] ?? '');
        $goodsIntroduction = str_replace("<p><br></p>", '', $courseInfo['goods_introduction'] ?? '');

        $insertCourse = [
            'name' => $courseInfo['name'] ?? '',
            'category_id' => $courseInfo['category_id'],
            'sort' => $courseInfo['sort'],
            'course_hour' => $courseInfo['course_hour'] ?? '',
            'origin_price' => $courseInfo['origin_price'] ?? 0,
            'sale_price' => $courseInfo['sale_price'] ?? 0,
            'description' => $courseInfo['description'] ?? '',
            'gift_desc' => $courseInfo['gift_desc'] ?? '',
            'head_img' => $courseInfo['head_img'] ?? '',
            'course_introduction' => $courseIntroduction,
            'goods_introduction' => $goodsIntroduction,
            'max_select_num' => !empty($courseInfo['child_course_id']) ? $courseInfo['max_select_num'] : 0,
            'status' => $courseInfo['status'] ?? 0,
            'stock' => $courseInfo['stock'] ?? 0,
            'sales' => $courseInfo['sales'] ?? 0,
            'course_code' => $courseCode,
            'created_by' => $userInfo['id'] ?? 0,
        ];
        if (isset($courseInfo['post_type'])) {
            $insertCourse['post_type'] = $courseInfo['post_type'];
            if ($courseInfo['post_type'] == 3) {
                $insertCourse['post_remark'] = $courseInfo['post_remark'];
            }
        }
        $courseId = $courseModel->insertGetId($insertCourse);
        if (false === $courseId) {
            DB::rollBack();
            $result['msg'] = '课程添加失败';
            return $result;
        }

        if (isset($courseInfo['child_course_id'])) {
            $insertCourseRelated = [];
            $tmp = ['course_id' => $courseId, 'created_by' => $userInfo['id'] ?? 0];
            foreach ($courseInfo['child_course_id'] as $childCourseId) {
                $tmp['child_course_id'] = $childCourseId;
                $insertCourseRelated[] = $tmp;
            }

            $insertCourseRelated = $courseRelatedModel->insertMultiData($insertCourseRelated);
            if (false === $insertCourseRelated) {
                DB::rollBack();
                $result['msg'] = '子课程添加失败';
                return $result;
            }
        }

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

    private function generateCourseCode($categoryName) {
        $categoryPinyin = Pinyin::sentence($categoryName, 'none')->toArray();

        return ($categoryPinyin[0] ?? '') . date('Ymd') . mt_rand(1000, 9999);
    }

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

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

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

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

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

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

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

        $where = [];
        if (isset($searchParam['name'])) {
            $where[] = ['name', 'like', '%' . $searchParam['name'] . '%'];
        }
        if (isset($searchParam['category_id'])) {
            $where['category_id'] = $searchParam['category_id'];
        }
        if (isset($searchParam['is_recommend'])) {
            $where['is_recommend'] = $searchParam['is_recommend'];
        }
        if (isset($searchParam['course_code'])) {
            $where['course_code'] = $searchParam['course_code'];
        }

        $courseModel = new Course();
        // 小程序只看发布的, 管理员可以看预发布的
        if ($searchParam['platform'] == 'applet') {
            $status = [2];
            if ($userInfo['is_preview'] == 1) {
                $status = [1, 2];
            }
            $courseList = $courseModel->selectDataWithPageAndComplexCondition($where, $status, ['id', 'name', 'category_id', 'course_hour', 'origin_price', 'sale_price', 'description', 'gift_desc', 'head_img', 'course_introduction', 'goods_introduction', 'max_select_num', 'post_type', 'post_remark', 'status', 'sort', 'is_recommend', 'stock', 'sales', 'created_at'], $searchParam['page_size']);
        } else if ($searchParam['platform'] == 'web') {
            if (isset($searchParam['status'])) {
                $where['status'] = $searchParam['status'];
            }

            // 后台看所有的
            $courseList = $courseModel->selectDataWithPageSort($where, ['id', 'name', 'category_id', 'course_hour', 'origin_price', 'sale_price', 'description', 'gift_desc', 'head_img', 'course_introduction', 'goods_introduction', 'max_select_num', 'post_type', 'post_remark', 'status', 'sort', 'is_recommend', 'is_top', 'stock', 'sales', 'course_code', 'created_at'], $searchParam['page_size']);
        }

        $allCategoryIds = array_filter(array_unique(array_column($courseList['data'], 'category_id')));
        $categoryIdRelatedName = [];
        if (!empty($allCategoryIds)) {
            $categoryInfo = (new Category())->selectDataByIds($allCategoryIds, ['id', 'name']);
            $categoryIdRelatedName = array_column($categoryInfo, 'name', 'id');
        }

        foreach ($courseList['data'] as $index => $value) {
            $courseList['data'][$index]['origin_price'] = floatval($value['origin_price']);
            $courseList['data'][$index]['sale_price'] = floatval($value['sale_price']);
            $courseList['data'][$index]['category_name'] = $categoryIdRelatedName[$value['category_id']] ?? '';
        }

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

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

        if (!isset($courseInfo['course_ids'])) {
            $result['msg'] = 'course_ids异常';
            return $result;
        }
        $courseIdsArr = explode(',', $courseInfo['course_ids']);
        $courseIdsArr = array_filter(array_unique($courseIdsArr));
        if (empty($courseIdsArr)) {
            $result['msg'] = 'course_ids异常';
            return $result;
        }
        foreach ($courseIdsArr as $index => $courseId) {
            if (!is_numeric($courseId) || $courseId <= 0) {
                $result['msg'] = 'course_ids异常';
                return $result;
            }
            $courseIdsArr[$index] = intval($courseId);
        }
        $courseIdsArr = array_unique($courseIdsArr);

        if (!isset($courseInfo['status']) || $courseInfo['status'] < 0 || $courseInfo['status'] > 2) {
            $result['msg'] = 'status异常';
            return $result;
        }

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

        foreach ($existedCourseInfo as $value) {
            // 已发布的课程不允许改为预发布
            if ($value['status'] == 2 && $courseInfo['status'] == 1) {
                $result['msg'] = '已发布的课程不能改为预发布';
                return $result;
            }
        }

        $updateCourseRes = $courseModel->updateDataByIds('id', $courseIdsArr, ['status' => $courseInfo['status']]);
        if (false === $updateCourseRes) {
            $result['msg'] = '操作失败';
            return $result;
        }

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

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

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

        $courseIdsArr = explode(',', $courseIds['course_ids']);
        $courseIdsArr = array_filter(array_unique($courseIdsArr));
        if (empty($courseIdsArr)) {
            $result['msg'] = 'course_ids异常';
            return $result;
        }

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

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

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

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

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

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

        if (!is_numeric($courseId) || $courseId <= 0) {
            $result['msg'] = 'course_id异常';
            return $result;
        }

        $courseModel = new Course();
        $courseInfo = $courseModel->findDataWithField(['id' => intval($courseId)], ['id', 'name', 'category_id', 'sort', 'course_hour', 'origin_price', 'sale_price', 'description', 'gift_desc', 'head_img', 'course_introduction', 'goods_introduction', 'max_select_num', 'post_type', 'post_remark', 'status', 'stock', 'sales', 'course_code', 'created_at']);
        if (empty($courseInfo)) {
            $result['msg'] = '课程不存在';
            return $result;
        }
        $courseInfo['origin_price'] = floatval($courseInfo['origin_price']);
        $courseInfo['sale_price'] = floatval($courseInfo['sale_price']);

        $courseInfo['child_course_info'] = [];
        // 获取课程的子课程信息
        $courseRelatedModel = new CourseRelated();
        $relatedData = $courseRelatedModel->selectDataWithField(['course_id' => $courseId], ['child_course_id']);
        $childCourseIds = array_unique(array_column($relatedData, 'child_course_id'));
        if (!empty($childCourseIds)) {
            // 获取子课程信息
            $childCourseInfo = $courseModel->selectDataByIds($childCourseIds, ['id', 'name', 'course_hour', 'origin_price', 'sale_price', 'description', 'head_img', 'course_introduction', 'goods_introduction', 'max_select_num']);
            $courseInfo['child_course_info'] = $childCourseInfo;
        }

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

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

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

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

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

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

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

        if (!empty($courseInfo['child_course_id'])) {
            // 判断要添加的子课程是否存在
            $existedCourse = $courseModel->selectDataByIds($courseInfo['child_course_id'] ?? [], ['id', 'name', 'status']);
            if (count($existedCourse) != count($courseInfo['child_course_id'])) {
                $result['msg'] = '子课程不存在';
                return $result;
            }
            foreach ($existedCourse as $value) {
                if ($value['status'] != 2) {
                    $result['msg'] = '存在未发布的子课程';
                    return $result;
                }
            }
        }

        // 判断课程分类id是否存在
        $categoryModel = new Category();
        $categoryInfo = $categoryModel->findDataWithField(['id' => $courseInfo['category_id']]);
        if (empty($categoryInfo)) {
            $result['msg'] = '课程分类不存在';
            return $result;
        }

        DB::beginTransaction();

        $courseIntroduction = str_replace("<p><br></p>", '', $courseInfo['course_introduction'] ?? '');
        $goodsIntroduction = str_replace("<p><br></p>", '', $courseInfo['goods_introduction'] ?? '');

        // 更新
        $updateCourseData = [
            'name' => $courseInfo['name'] ?? '',
            'category_id' => $courseInfo['category_id'],
            'sort' => $courseInfo['sort'],
            'course_hour' => $courseInfo['course_hour'] ?? '',
            'origin_price' => $courseInfo['origin_price'] ?? 0,
            'sale_price' => $courseInfo['sale_price'] ?? 0,
            'description' => $courseInfo['description'] ?? '',
            'gift_desc' => $courseInfo['gift_desc'] ?? '',
            'head_img' => $courseInfo['head_img'] ?? '',
            'course_introduction' => $courseIntroduction,
            'goods_introduction' => $goodsIntroduction,
            'max_select_num' => $courseInfo['max_select_num'] ?? 0,
            'status' => $courseInfo['status'] ?? 0,
            'stock' => $courseInfo['stock'] ?? 0,
            'sales' => $courseInfo['sales'] ?? 0,
        ];
        if (isset($courseInfo['post_type'])) {
            $updateCourseData['post_type'] = $courseInfo['post_type'];

            if ($courseInfo['post_type'] == 3) {
                $updateCourseData['post_remark'] = $courseInfo['post_remark'];
            } else {
                $updateCourseData['post_remark'] = '';
            }
        }
        $updateCourseRes = $courseModel->updateData(['id' => $courseInfo['course_id']], $updateCourseData);
        if (false === $updateCourseRes) {
            DB::rollBack();
            $result['msg'] = '更新失败';
            return $result;
        }

        // 先把课程的已有的子课程删除
        $courseRelatedModel = new CourseRelated();
        $deleteCourseRelated = $courseRelatedModel->deleteData(['course_id' => $courseInfo['course_id']]);
        if (false === $deleteCourseRelated) {
            $result['msg'] = '更新失败';
            Log::error("子课程删除失败: " . json_encode($courseInfo));
            return $result;
        }

        if (!empty($courseInfo['child_course_id'])) {
            $insertCourseRelated = [];
            $tmp = ['course_id' => $courseInfo['course_id'], 'created_by' => $userInfo['id'] ?? 0];
            foreach ($courseInfo['child_course_id'] as $childCourseId) {
                $tmp['child_course_id'] = $childCourseId;
                $insertCourseRelated[] = $tmp;
            }

            $insertCourseRelated = $courseRelatedModel->insertMultiData($insertCourseRelated);
            if (false === $insertCourseRelated) {
                DB::rollBack();
                $result['msg'] = '更新失败';
                Log::error("子课程添加失败: " . json_encode($courseInfo));
                return $result;
            }
        }

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

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

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

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

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

        $updateCourseRes = $courseModel->updateData(['id' => $courseInfo['course_id']], ['is_recommend' => $courseInfo['is_recommend']]);
        if (false === $updateCourseRes) {
            $result['msg'] = '更新失败';
            return $result;
        }

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

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

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

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

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

        $updateData = [
            'is_top' => $courseInfo['is_top'],
        ];
        $updateData['set_top_time'] = ($courseInfo['is_top'] == 1) ? time() : 0;

        $updateCourseRes = $courseModel->updateData(['id' => $courseInfo['course_id']], $updateData);
        if (false === $updateCourseRes) {
            $result['msg'] = '更新失败';
            return $result;
        }

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

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

        if (empty($courseIds)) {
            $result['msg'] = 'course_ids异常';
            return $result;
        }

        $courseIdsArr = explode(',', $courseIds);
        $courseIdsArr = array_filter(array_unique($courseIdsArr));
        if (empty($courseIdsArr)) {
            $result['msg'] = 'course_ids异常';
            return $result;
        }

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

        // 校验课程是否存在
        $courseModel = new Course();
        $existedCourseInfo = $courseModel->selectDataByIds($courseIdsArr, ['id as course_id', 'stock']);
        if (count($existedCourseInfo) != count($courseIdsArr)) {
            $result['msg'] = '课程不存在或已失效';
            return $result;
        }

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

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

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

        if (!isset($courseInfo['sales']) || $courseInfo['sales'] <= 0 || $courseInfo['sales'] > 999999) {
            $result['msg'] = 'sales异常';
            return $result;
        }
        $courseInfo['sales'] = intval($courseInfo['sales']);

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

        $updateCourseRes = $courseModel->updateData(['id' => $courseInfo['course_id']], ['sales' => $courseInfo['sales']]);
        if (false === $updateCourseRes) {
            $result['msg'] = '操作失败';
            return $result;
        }

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

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

        if (!isset($courseInfo['course_id']) || !is_numeric($courseInfo['course_id']) || $courseInfo['course_id'] < 1) {
            $result['msg'] = '课程id异常';
            return $result;
        }
        $result['data']['course_id'] = intval($courseInfo['course_id']);

        if (!isset($courseInfo['is_anonymous']) || !is_numeric($courseInfo['is_anonymous']) || $courseInfo['is_anonymous'] < 0 || $courseInfo['is_anonymous'] > 1) {
            $result['msg'] = '是否匿名异常';
            return $result;
        }
        $result['data']['is_anonymous'] = intval($courseInfo['is_anonymous']);

        if (!isset($courseInfo['score']) || !is_numeric($courseInfo['score']) || $courseInfo['score'] < 1 || $courseInfo['score'] > 5) {
            $result['msg'] = '评分异常';
            return $result;
        }
        $result['data']['score'] = intval($courseInfo['score']);

        if (!isset($courseInfo['content']) || mb_strlen($courseInfo['content']) > 256) {
            $result['msg'] = '评价内容异常';
            return $result;
        }
        $result['data']['content'] = $courseInfo['content'];

        if (!isset($courseInfo['image_url']) || mb_strlen($courseInfo['image_url']) > 512) {
            $result['msg'] = '评价图片异常';
            return $result;
        }
        $result['data']['image_url'] = $courseInfo['image_url'];

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

    public function addCourseEvaluateHandle($userInfo, $courseInfo) {
        $result = [
            'res' => false,
            'msg' => '评价成功',
            'data' => [],
        ];

        $courseModel = new Course();
        $courseDetail = $courseModel->findDataWithField(['id' => $courseInfo['course_id']]);
        if (empty($courseDetail)) {
            $result['msg'] = '产品不存在';
            return $result;
        }

        $insertData = [
            'user_id' => $userInfo['id'],
            'course_id' => $courseInfo['course_id'],
            'is_anonymous' => $courseInfo['is_anonymous'],
            'score' => $courseInfo['score'],
            'content' => $courseInfo['content'],
            'image_url' => $courseInfo['image_url'],
        ];

        $courseEvaluateModel = new CourseEvaluate();
        $insertRes = $courseEvaluateModel->insertData($insertData);
        if (false === $insertRes) {
            $result['msg'] = '评价失败';
            return $result;
        }

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

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

        if (!isset($searchParam['course_id']) || !is_numeric($searchParam['course_id']) || $searchParam['course_id'] <= 0) {
            $result['msg'] = '课程id不合法';
            return $result;
        }
        $result['data']['course_id'] = intval($searchParam['course_id']);

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

        $courseModel = new Course();
        $courseDetail = $courseModel->findDataWithField(['id' => $searchParam['course_id']]);
        if (empty($courseDetail)) {
            $result['msg'] = '产品不存在';
            return $result;
        }

        $where = [
            'course_id' => $searchParam['course_id'],
            'status' => 1,
        ];

        $courseEvaluateModel = new CourseEvaluate();

        // 后台看所有的
        $courseEvaluateList = $courseEvaluateModel->selectDataWithPage($where, ['user_id', 'is_anonymous', 'score', 'content', 'image_url', 'reply_content', 'reply_time', 'created_at'], $searchParam['page_size']);

        $userFrontModel = new FrontUserModel();
        $userIds = array_unique(array_column($courseEvaluateList['data'], 'user_id'));
        $userInfos = $userFrontModel->selectDataByIds($userIds, ['*']);
        $userIdRelatedInfo = array_column($userInfos, null, 'id');

        foreach ($courseEvaluateList['data'] as $index => $value) {
            $courseEvaluateList['data'][$index]['created_at'] = date('Y-m-d', strtotime($value['created_at']));

            if ($value['reply_time'] > 0) {
                $courseEvaluateList['data'][$index]['reply_time'] = date('Y-m-d', $value['reply_time']);
            } else {
                $courseEvaluateList['data'][$index]['reply_time'] = '';
            }

            if ($value['is_anonymous'] > 0) {
                $courseEvaluateList['data'][$index]['user_name'] = '匿名';
            } else if (!empty($userIdRelatedInfo[$value['user_id']]['phone'])) {
                $courseEvaluateList['data'][$index]['user_name'] = substr($userIdRelatedInfo[$value['user_id']]['phone'], 0, 3) . '****' . substr($userIdRelatedInfo[$value['user_id']]['phone'], -4);
            } else {
                $courseEvaluateList['data'][$index]['user_name'] = '未知用户';
            }

            unset($courseEvaluateList['data'][$index]['user_id']);
            unset($courseEvaluateList['data'][$index]['is_anonymous']);
        }

        $result['res'] = true;
        $result['data']['page'] = $searchParam['page'];
        $result['data']['page_size'] = $searchParam['page_size'];
        $result['data']['total'] = $courseEvaluateList['total'];
        $result['data']['list'] = $courseEvaluateList['data'];
        return $result;
    }

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

        if ($searchParam['course_id'] !== '' && is_numeric($searchParam['course_id']) && $searchParam['course_id'] > 0) {
            $result['data']['course_id'] = intval($searchParam['course_id']);
        }

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

        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'];
            }
        }

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

        $where = [];

        if (isset($searchParam['course_id'])) {
            $where['course_id'] = $searchParam['course_id'];
        }

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

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

        $courseEvaluateModel = new CourseEvaluate();

        // 后台看所有的
        $courseEvaluateList = $courseEvaluateModel->selectDataWithPage($where, ['id', 'user_id', 'status', 'course_id', 'content', 'created_at'], $searchParam['page_size']);

        // 获取用户信息
        $userFrontModel = new FrontUserModel();
        $userIds = array_unique(array_column($courseEvaluateList['data'], 'user_id'));
        $userInfos = $userFrontModel->selectDataByIds($userIds, ['*']);
        $userIdRelatedInfo = array_column($userInfos, null, 'id');

        // 获取课程信息
        $courseModel = new Course();
        $courseIds = array_unique(array_column($courseEvaluateList['data'], 'course_id'));
        $courseInfos = $courseModel->selectDataByIdsTrashed($courseIds, ['*']);
        $courseRelatedInfo = array_column($courseInfos, null, 'id');

        foreach ($courseEvaluateList['data'] as $index => $value) {
            $courseEvaluateList['data'][$index]['user_phone'] = $userIdRelatedInfo[$value['user_id']]['phone'] ?? '未知用户';
            $courseEvaluateList['data'][$index]['course_name'] = $courseRelatedInfo[$value['course_id']]['name'] ?? '未知课程';
            $courseEvaluateList['data'][$index]['price'] = $courseRelatedInfo[$value['course_id']]['sale_price'] ?? 0;
        }

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

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

        if ($searchParam['evaluate_id'] <= 0) {
            return $result;
        }

        $where = [
            'id' => $searchParam['evaluate_id'],
        ];

        $courseEvaluateModel = new CourseEvaluate();
        $courseEvaluateDetail = $courseEvaluateModel->findDataWithField($where, ['user_id', 'is_anonymous', 'score', 'content', 'image_url', 'reply_content', 'created_at']);
        if (empty($courseEvaluateDetail)) {
            $result['res'] = false;
            $result['msg'] = '不存在的评价';
            return $result;
        }

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

        $result['data']['user_phone'] = $userDetail['phone'];
        $result['data']['score'] = $courseEvaluateDetail['score'];
        $result['data']['content'] = $courseEvaluateDetail['content'];
        $result['data']['image_url'] = $courseEvaluateDetail['image_url'];
        $result['data']['reply_content'] = $courseEvaluateDetail['reply_content'];
        $result['data']['created_at'] = $courseEvaluateDetail['created_at'];
        return $result;
    }

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

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

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

        if (isset($checkInfo['reply_content']) && mb_strlen($checkInfo['reply_content']) > 256) {
            $result['msg'] = '回复内容过长';
            return $result;
        }

        $where = [
            'id' => $checkInfo['evaluate_id'],
        ];

        $courseEvaluateModel = new CourseEvaluate();
        $courseEvaluateDetail = $courseEvaluateModel->findDataWithField($where, ['id']);
        if (empty($courseEvaluateDetail)) {
            $result['msg'] = '不存在的评价';
            return $result;
        }

        $updateData = [
            'status' => $checkInfo['status'],
            'reply_content' => $checkInfo['reply_content'] ?? '',
            'reply_time' => ($checkInfo['reply_content'] ?? '') === '' ? 0 : time(),
        ];
        $updateRes = $courseEvaluateModel->updateData($where, $updateData);
        if (false === $updateRes) {
            $result['msg'] = '审核失败';
            return $result;
        }

        (new LogModel())->insertData(['operator' => $userInfo['id'] ?? 0, 'url' => '审核评价', 'type' => 2, 'object_id' => $checkInfo['evaluate_id'], 'content' => json_encode(['data' => $updateData], JSON_UNESCAPED_UNICODE)]);

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



}
