<?php

namespace app\api\controller\manage;

use app\api\middleware\Auth;
use app\api\service\UtilService;
use app\api\validate\ShCourseValidate;
use app\BaseController;
use app\model\CertTag;
use app\model\CourseCategory;
use app\model\ShCourse as ShCourseModel;
use app\Request;
use think\facade\Db;

class ShCourse extends BaseController
{

    protected $middleware = [
        Auth::class,
    ];

    //机构课程列表
    public function getShCourseList(Request $request)
    {
        $parm = $request->param();
        $where = ['sh_course.is_del' => 0, 'user_id' => $request->userId];
        $map = [];
        if (isset($parm['searchKeyWords']) && $parm['searchKeyWords']) {
            $map[] = ['sh_course.title', 'like', '%' . $parm['searchKeyWords'] . '%'];
        }
        if (isset($parm['status']) && ($parm['status'] || $parm['status'] === '0')) {
            $map[] = ['status', '=', $parm['status']];
        }
        $hasmap = [];
        if (isset($parm['cate_name']) && $parm['cate_name']) {
            $hasmap[] = ['course_category.title', 'like', '%' . $parm['cate_name'] . '%'];
        }
        if (isset($parm['start_time']) && $parm['start_time'] && isset($parm['end_time']) && $parm['end_time']) {

            $start_time = strtotime($parm['start_time']);
            $end_time = strtotime($parm['end_time']);
            $map[] = ['sh_course.createtime', '>=', $start_time];
            $map[] = ['sh_course.createtime', '<=', $end_time];
        }

        $page = $request->param('page', 1);
        $pageSize = $request->param('pageSize', 10);
        $list = ShCourseModel::where($where)->where($map)->hasWhere('coursecatedata', $hasmap)
            ->field('sh_course.id,sh_course.title,sh_course.createtime,sh_course.thumb,tag_ids,price,status,is_sell,tvclick,click,cate_id,teacher_id')
            ->order('createtime desc')
            ->with(['coursecatedata'])
            ->append(['thumbpath', 'teacher_name', 'status_text'])
            ->paginate([
                'page' => $page,
                'list_rows' => $pageSize
            ]);
        $list = UtilService::listWithTags($list, (\app\model\CourseTag::class), 'tag_ids');
        return $this->returnMsg('success', 1, $list);
    }

    //获取课程列表 作业 课时 选择时用
    public function selectShCourseList(Request $request)
    {
        $where = ['is_del' => 0, 'user_id' => $request->userId];
        $list = ShCourseModel::where($where)
            ->field('id,title')
            ->select();
        return $this->returnMsg('success', 1, $list);
    }

    //修改课程属性
    public function updatecourseinfo(Request $request)
    {
        $vo = (new ShCourseValidate())->goCheck(['course_id', 'updateField', 'updateValue']);
        if ($vo !== true) {
            return $vo;
        }
        $parm = $request->param();
        $where = ['id' => $parm['course_id'], 'user_id' => $request->userId];
        $result = ShCourseModel::where($where)->update([$parm['updateField'] => $parm['updateValue']]);
        event('Course', ['course_id' => $parm['course_id'], 'tasktype' => 'course', 'action' => 'shcourseupdate']); //同步数据
        return $this->returnMsg('操作成功', 1, $result);

    }

    //删除课程
    public function coursedelete(Request $request)
    {

        $vo = (new ShCourseValidate())->goCheck(['course_id']);
        if ($vo !== true) {
            return $vo;
        }
        // 启动事务
        Db::startTrans();
        try {
            $parm = $request->param();
            $where = ['id' => $parm['course_id'], 'user_id' => $request->userId];
            $result = ShCourseModel::where($where)->update(['is_del' => 1]);
            \app\model\ShCourseClassCategory::where('course_id', $parm['course_id'])->update(['is_del' => 1]); //删除章节
            \app\model\ShCourseClass::where('course_id', $parm['course_id'])->update(['is_del' => 1]); //删除课时
            \app\model\ShCourseWork::where('course_id', $parm['course_id'])->update(['is_del' => 1]); //删除作业
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->returnMsg($e->getMessage());
        }

        event('Course', ['course_id' => $parm['course_id'], 'tasktype' => 'course', 'action' => 'shcourseupdate']); //同步数据
        return $this->returnMsg('操作成功', 1, $result);
    }

    //添加课程
    public function createShCourse(Request $request)
    {
        $filed = ['title', 'cate_id', 'thumb', 'teacher_id', 'detailthumb', 'content','tag_ids','teacher_id','price'];
        $vo = (new ShCourseValidate())->goCheck($filed);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->only($filed);
        $data['sn'] = UtilService::generateCompactOrderNo($request->userId, 'K');
        $data['createtime'] = time();
        $data['user_id'] = $request->userId;
        $result = ShCourseModel::create($data);
        return $this->returnMsg('操作成功', 1, $result);
    }

    //修改课程
    public function editShCourse(Request $request)
    {
        $filed = ['course_id', 'title', 'cate_id', 'thumb', 'teacher_id', 'detailthumb', 'content','tag_ids','teacher_id','price'];
        $vo = (new ShCourseValidate())->goCheck($filed);
        if ($vo !== true) {
            return $vo;
        }

        $parm = $request->param();
        $udpatedata = $request->only($filed);
        unset($udpatedata['course_id']);
        $udpatedata['updatetime'] = time();
        $udpatedata['status'] = 0; //修改为待提交
        $result = ShCourseModel::where(['user_id' => $request->userId, 'id' => $parm['course_id']])->update($udpatedata);
        return $this->returnMsg('操作成功', 1, $result);

    }

    //课程详情
    public function ShCourseDetail(Request $request)
    {
        $vo = (new ShCourseValidate())->goCheck(['course_id']);
        if ($vo !== true) {
            return $vo;
        }
        $parm = $request->param();
        $info = ShCourseModel::find($parm['course_id'])->append(['thumbpath','detailthumbpath', 'cate_name', 'teacher_name', 'status_text']);
        $info = UtilService::infoWithTags($info, (\app\model\CourseTag::class), 'tag_ids');
        return $this->returnMsg('操作成功', 1, $info);

    }

    //课程分类
    public function ShCourseCategory()
    {
        $list = (new CourseCategory)->getCourseCategoryList();
        return $this->returnMsg('操作成功', 1, $list);
    }


}