<?php

namespace app\admin\controller\TeachersStrength;

use app\BaseController;
use app\common\model\TeachersStrength\Teacher as ModelTeacher;
use app\Request;
use think\Validate;
use think\exception\ValidateException;
use think\facade\Filesystem;
use app\common\arw\adjfut\src\Excel;
use app\common\arw\adjfut\src\UploadFile;
use app\common\exception\Tool;
use think\facade\Db;
use think\facade\Env;


class Teacher extends BaseController
{
    /**
     * 获取教师列表
     */
    public function getTeacherList(Request $request, $isExport = false): array
    {
        $params = $request->param();
        $con = [];

        $con = Tool::getOptionalQuery(['teacher_name', 'LIKE'], ['teacher_position', 'LIKE'], ['a.subject_guid', '='], ['a.teacher_status', '='],);

        $query = ModelTeacher::where($con)
            ->field([
                'a.teacher_id',
                'a.teacher_guid',
                'a.teacher_name',
                'a.teacher_position',
                'a.teacher_img',
                'a.subject_guid',
                'b.subject_name',
                'a.teacher_intro',
                'a.teacher_content',
                'a.teacher_status',
                'a.teacher_order'
            ])
            ->alias('a')
            ->leftJoin('subject b', 'a.subject_guid = b.subject_guid')
            ->order('teacher_order', 'asc');

        return $isExport ? $query->select()->toArray() : msg("获取教师列表成功!", $query);
    }

    /**
     * 编辑教师
     */
    public function editTeacher(Request $request): array
    {
        Db::startTrans();
        Tool::adminLockTableWrite('teacher');
        try {
            $params = $request->param();
            $this->validate($params, [
                'teacher_name|教师名称' => 'require',
                'teacher_position|教师职位' => 'require',
                'teacher_img|教师图片' => 'require',
                'subject_guid|授课科目' => 'require',
                'teacher_intro|教师简介' => 'require',
            ]);
            $model = ModelTeacher::where('teacher_guid', $params['teacher_guid'])->find();
            if (!$model) throwErrorMsg("该教师不存在", 1);
            $model->allowField([
                'teacher_update_user_guid',
                'teacher_name',
                'teacher_position',
                'teacher_img',
                'teacher_content',
                'subject_guid',
                'teacher_intro',
                'teacher_status',
                'teacher_order'
            ])->save($params);
            Db::commit();
            Tool::unlockTable();
            return msg('编辑成功!');
        } catch (\Throwable $th) {
            Tool::unlockTable();
            Db::rollback();
            throw  $th;
        }
    }

    /**
     * 添加教师
     */
    public function addTeacher(Request $request): array
    {
        Db::startTrans();
        Tool::adminLockTableWrite('teacher');
        try {
            $params = $request->param();
            $this->validate($params, [
                'teacher_name|教师名称' => 'require',
                'teacher_position|教师职位' => 'require',
                'teacher_img|教师图片' => 'require',
                'subject_guid|授课科目' => 'require',
                'teacher_intro|教师简介' => 'require',
            ]);
            $model = ModelTeacher::create($params, [
                'teacher_guid',
                'teacher_create_user_guid',
                'teacher_update_user_guid',
                'teacher_name',
                'teacher_position',
                'teacher_content',
                'teacher_img',
                'subject_guid',
                'teacher_intro',
                'teacher_status',
                'teacher_order'
            ]);
            Db::commit();
            Tool::unlockTable();
            return msg('添加成功!');
        } catch (\Throwable $th) {
            Tool::unlockTable();
            Db::rollback();
            throw  $th;
        }
    }

    /**
     * 删除教师
     */
    public function deleteTeacher(Request $request): array
    {
        Db::startTrans();
        Tool::adminLockTableWrite('teacher');
        try {
            $params = $request->param();
            $this->validate($params, [
                'teacher_guid' => 'require',
            ]);
            $teacher = ModelTeacher::where([
                'teacher_guid' => explode(',', $params['teacher_guid'])
            ])->select();
            $teacher->delete();
            Db::commit();
            Tool::unlockTable();
            return msg('删除成功!');
        } catch (\Throwable $th) {
            Tool::unlockTable();
            Db::rollback();
            throw  $th;
        }
    }

    /**
     * 导出Excel
     */
    public function exportExcel(Request $request)
    {
        ModelTeacher::exportExcel(self::getTeacherList($request, true));
    }

    /**
     * 下载导入模板
     */
    public function downloadTemplate(Request $request)
    {
        $params = $request->param();
        $data = [
            array_values(ModelTeacher::EXCELFIELD),
            [
                '色彩课',
                '黎老师',
                '执行董事',
                '毕业于西南交大建筑与设计学院 高考美术教育13年',
                "1",
                "不展示",
            ]
        ];
        $excel = (new Excel())->exporTsheet($data);
        $excel->save('教师列表导入模板.xlsx');
    }

    /**
     * 导入excel
     */
    public function importExcel(Request $request)
    {
        Db::startTrans();
        Tool::adminLockTableWrite(['teacher','subject']);
        try {
            $file = new UploadFile('uploads', 'fileExt:xlsx');
            $file->putFile('info_article');

            $msg = ModelTeacher::importExcel($file);
            Db::commit();
            Tool::unlockTable();
            return [
                'code' => 0,
                'msg' => $msg
            ];
        } catch (\Throwable $th) {
            Db::rollback();
            Tool::unlockTable();
            throw  $th;
        }
    }
}
