<?php

namespace app\manystoreapi\controller;

use app\common\controller\ManystoreApiBase;
use app\common\model\manystore\UserAuth;
use app\common\model\school\classes\Teacher as Teachermodel;
use app\common\model\User;
use app\manystore\model\Manystore;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 机构API后台：机构教师接口
 */
class Teacher extends ManystoreApiBase
{
//    protected $noNeedLogin = ["detail",'people','spec',"teacher_list"];
//    protected $noNeedRight = '*';

    protected $model = null;

    /**
     * 初始化操作
     * @access protected
     */
    public function _initialize()
    {

        $this->model = new Teachermodel;
        parent::_initialize();

        //判断登录用户是否是员工
    }


    /**
     * @ApiTitle( 老师详情)
     * @ApiSummary(老师详情)
     * @ApiMethod(GET)
     * @ApiParams(name = "id", type = "int",required=true,description = "老师id")
     * @ApiReturn({
     *
     *})
     */
    public function detail(){
        $id = $this->request->get('id/d','');

        if(empty($id)){
            $this->apierror(__('缺少必要参数'));
        }

        try {
            $res =  $this->model->detail($id);
        } catch (\Exception $e){
//            Log::log($e->getMessage());
            $this->apierror($e->getMessage(),['errcode'=>$e->getCode()]);
        }
        $this->apisuccess('获取成功', ['detail' => $res]);
    }







    /**
     * @ApiTitle( 老师或专家列表（取决于搜索条件）)
     * @ApiSummary(老师或专家列表（取决于搜索条件）)
     * @ApiMethod(GET)
     * @ApiParams(name = "keywords", type = "string",required=false,description = "搜索关键字")
     * @ApiParams(name = "page", type = "string",required=true,description = "页数")
     * @ApiParams(name = "limit", type = "string",required=true,description = "条数")
     * @ApiParams(name = "status", type = "string",required=false,description = "查展示专家请传1，非专家也查请传0")
     * @ApiParams(name = "recommend", type = "string",required=false,description = "平台首页推荐:0=否,1=是")
     * @ApiParams(name = "shop_id", type = "string",required=false,description = "机构店铺id")
     * @ApiParams(name = "user_id", type = "string",required=false,description = "教师用户id")
     * @ApiReturn({
     *
     *})
     */
    public function teacher_list()
    {
        $user_id = 0;
        $user = $this->auth->getUser();//登录用户
        if($user)$user_id = $user['id'];
        $params=[
            "shop_id"=>$this->auth->shop_id,
        ];
        $page      =  $this->request->get('page/d', 0); //页数
        $limit   =  $this->request->get('limit/d', 0); //条数
        $params['keywords']  =  $this->request->get('keywords/s', ''); //搜索关键字
        $params['status']  =  $this->request->get('status/s', ''); //搜索关键字
        $params['recommend']  =  $this->request->get('recommend/s', ''); //搜索关键字
        $params['shop_id']  =  $this->request->get('shop_id/d', ''); //搜索关键字
        $params['user_id']  =  $this->request->get('user_id/d', ''); //搜索关键字



//        $type =  $this->request->get('type/s', ''); //筛选学员和教练单

        try{
            //当前申请状态
            $res =  $this->model::allList($page, $limit,$params);
//            if($user_id =='670153'){
//               file_put_contents("ceshi66.txt",(new AppointmentOrder())->getLastSql());
//            }
        }catch (\Exception $e){

            $this->apierror($e->getMessage());
        }
        $this->apisuccess('查询成功', $res);
    }


    /**
     * @ApiTitle( 微信小程序码)
     * @ApiSummary(微信小程序码)
     * @ApiMethod(GET)
     * @ApiParams(name = "ids", type = "int",required=true,description = "老师id")
     * @ApiReturn({
     *  微信小程序码图片流
     *})
     */
    public function miniqrcode($ids = ''){
        $param = $this->request->param();
        try{
            if(isset($param['ids']))$ids = $param['ids'];
            //设置模拟资格
            $url =  \app\common\model\school\classes\Teacher::getMiniQrcodeLink($ids);

        }catch (\Exception $e){
            $this->apierror($e->getMessage());
        }

        return $url["response"];
    }

    protected function updateCheck($id,$params=[],$row=null){

        // 课程存在售后订单则不允许操作
        if($params && $row){

            if(!$this->no_auth_fields_check($params,$row)){
                return true;
            }
        }

        // 课程存在未完成订单则不允许操作
        $classesLib =  \app\common\model\school\classes\ClassesLib::where("teacher_id",$id)->find();
        if($classesLib)$this->apierror("存在正在教授的课程无法继续操作！请将课程讲师更换成其他人或者删除该课程后再操作！");


    }

    /**
     * @ApiTitle( 老师删除)
     * @ApiSummary(老师删除)
     * @ApiMethod(POST)
     * @ApiParams(name = "ids", type = "int",required=true,description = "老师id")
     * @ApiReturn({
     *  微信小程序码图片流
     *})
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->apierror(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            if($this->shopIdAutoCondition){
                $this->model->where(array('shop_id'=>SHOP_ID));
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            foreach ($list as $item) {
                $this->updateCheck($item->id);
            }
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->apierror($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->apierror($e->getMessage());
            }
            if ($count) {
                $this->apisuccess();
            } else {
                $this->apierror(__('No rows were deleted'));
            }
        }
        $this->apierror(__('Parameter %s can not be empty', 'ids'));
    }



    protected function update_check(&$params,$row=null)
    {

        $shop_id = SHOP_ID;
        $manystore = Manystore::where("shop_id", $shop_id)->find();
        if (!$manystore) {
            $this->apierror("店铺不存在");
        }
        $params["manystore_id"] = $manystore["id"];
        $params["shop_id"] = $shop_id;
        $user = User::where("id|nickname|realname|mobile", $params["user_id"])->find();
        if(!$user) $this->apierror("未找到用户请先让用户登录小程序再提交表单");


        //添加用户机构认证
        try {
            \app\common\model\manystore\UserAuth::auth(0,$shop_id,$user["id"],0,'shop',$this->auth->id);
        }catch (\Exception $e){

        }
        //如果开启了检测用户授权，则检测用户是否授权
        if(config("site.shop_auth_user_check")){
            if(!UserAuth::authcheck($shop_id,$user["id"])) $this->apierror("用户未授权当前机构！请先让用户授权同意您再操作！");
        }



        $params["user_id"] = $user["id"];

        $user_id = $params["user_id"];
        //修改
        if($row){
            //用户已是其他的教师（搜索）
            $teacher_user =  $this->model->where("user_id",$user_id)->where("id","<>",$row["id"])->find();
            if($teacher_user){
                $this->apierror("用户已存在或已是其他授权机构教师！");
            }
        }else{
            //新增
            //用户已是教师（搜索）
            $teacher_user =  $this->model->where("user_id",$user_id)->find();
            if($teacher_user){
                $this->apierror("用户已存在或已是其他授权机构教师！");
            }
        }


    }



    /**
     * @ApiTitle( 老师添加)
     * @ApiSummary(老师添加)
     * @ApiMethod(POST)
     * @ApiParams(name = "user_id", type = "int",required=true,description = "教师前台用户id")
     * @ApiParams(name = "name", type = "int",required=true,description = "教师名")
     * @ApiParams(name = "head_image", type = "int",required=true,description = "教师头像")
     * @ApiParams(name = "content", type = "int",required=true,description = "教师简介")
     * @ApiParams(name = "status", type = "int",required=true,description = "机构展示专家信息:1=上架,2=下架")
     * @ApiParams(name = "recommend", type = "int",required=true,description = "平台首页推荐:0=否,1=是")
     * @ApiParams(name = "expert_image", type = "int",required=true,description = "专家头像")
     * @ApiParams(name = "expert_content", type = "int",required=true,description = "专家介绍")
     * @ApiParams(name = "weigh", type = "int",required=true,description = "weigh")
     * @ApiReturn({
     *
     *})
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                if($this->storeIdFieldAutoFill && STORE_ID ){
                    $params['store_id'] = STORE_ID;
                }

                if($this->shopIdAutoCondition && SHOP_ID){
                    $params['shop_id'] = SHOP_ID;
                }
                try {
                    $this->update_check($params,$row=null);
                } catch (ValidateException|PDOException|Exception $e) {
                    $this->apierror($e->getMessage());
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $this->update_check($params,$row=null);
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->apierror($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->apierror($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->apierror($e->getMessage());
                }
                if ($result !== false) {
                    $this->apisuccess();
                } else {
                    $this->apierror(__('No rows were inserted'));
                }
            }
            $this->apierror(__('Parameter %s can not be empty', ''));
        }
    }

    /**
     * @ApiTitle( 老师编辑)
     * @ApiSummary(老师编辑)
     * @ApiMethod(POST)
     * @ApiParams(name = "ids", type = "int",required=true,description = "教师id")
     * @ApiParams(name = "user_id", type = "int",required=true,description = "教师前台用户id")
     * @ApiParams(name = "name", type = "int",required=true,description = "教师名")
     * @ApiParams(name = "head_image", type = "int",required=true,description = "教师头像")
     * @ApiParams(name = "content", type = "int",required=true,description = "教师简介")
     * @ApiParams(name = "status", type = "int",required=true,description = "机构展示专家信息:1=上架,2=下架")
     * @ApiParams(name = "recommend", type = "int",required=true,description = "平台首页推荐:0=否,1=是")
     * @ApiParams(name = "expert_image", type = "int",required=true,description = "专家头像")
     * @ApiParams(name = "expert_content", type = "int",required=true,description = "专家介绍")
     * @ApiParams(name = "weigh", type = "int",required=true,description = "weigh")
     * @ApiReturn({
     *
     *})
     */
    public function edit($ids = null)
    {
        $ids = $ids ? $ids : $this->request->post("ids");

        if ($this->request->isPost()) {
            if($this->shopIdAutoCondition){
                $this->model->where(array('shop_id'=>SHOP_ID));
            }
            $row = $this->model->where(array('id'=>$ids))->find();
            if (!$row) {
                $this->apierror(__('No Results were found'));
            }

            $params = $this->request->post();
            if ($params) {
                $result = false;
                try {
                    $this->update_check($params,$row);
                } catch (ValidateException|PDOException|Exception $e) {
                    $this->apierror($e->getMessage());
                }


                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $this->update_check($params,$row);


                    $result = $row->allowField(true)->save($params);

                    $classesLibs = \app\common\model\school\classes\ClassesLib::where( ['teacher_id'=>$row["id"]])->select();
                    foreach ($classesLibs as $classesLib){
                        $classesLib->user_id = $row["user_id"];
                        $classesLib->save();
                        //执行课程订单更新
                        \app\common\model\school\classes\ClassesLib::update_classes($classesLib["id"]);
                    }


                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->apierror($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->apierror($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->apierror($e->getMessage());
                }
                if ($result !== false) {
                    $this->apisuccess("更新成功");
                } else {
                    $this->apierror(__('No rows were updated'));
                }
            }
            $this->apierror(__('Parameter %s can not be empty', ''));
        }
    }




}

