<?php

namespace app\admin\controller\school\classes;

use app\admin\model\Admin;
use app\common\controller\Backend;
use app\common\model\manystore\UserAuth;
use app\common\model\User;
use app\manystore\model\Manystore;
use fast\Tree;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;
use think\Url;

/**
 * 机构老师
 *
 * @icon fa fa-circle-o
 */
class Teacher extends Backend
{
    protected $noNeedLogin = ["miniqrcode"];
    /**
     * Teacher模型对象
     * @var \app\admin\model\school\classes\Teacher
     */
    protected $model = null;

    protected $selectpageFields = 'id,name,head_image,manystore_id,shop_id,user_id';
    protected $searchFields = 'id,name,user_id';

    protected $qSwitch = true;
    protected $qFields = ["manystore_id","shop_id","user_id"];

    public function _initialize()
    {
        $this->model = new \app\admin\model\school\classes\Teacher;
        parent::_initialize();

        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("recommendList", $this->model->getRecommendList());
        $this->getAuthMsg();
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->searchFields = ["id","name","user.nickname","user.realname","user.mobile"];

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','manystore','shop'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['nickname','realname','avatar','mobile']);
				$row->getRelation('manystore')->visible(['nickname']);
				$row->getRelation('shop')->visible(['name','logo','image','address_city','province','city','district','address','address_detail']);
            }

            $rows = $list->items();
            foreach ($rows as $k=>&$v){
                $v["miniqrcode_link"] = Url::build("/school/classes/teacher/miniqrcode", ["ids" => $v["id"]]);
            }

            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }






    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->error("存在正在教授的课程无法继续操作！请将课程讲师更换成其他人或者删除该课程后再操作！");
    }


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

        $shop_id = $params["shop_id"];
        $manystore = Manystore::where("shop_id",$shop_id)->find();
        if(!$manystore){
            $this->error("店铺不存在");
        }
        //用户不存在
        $user_id = $params["user_id"];
        $user = User::where("id",$user_id)->find();
        if(!$user){
            $this->error("用户不存在");
        }


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

        }


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



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







        $params["manystore_id"] = $manystore["id"];
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        try {
           $this->update_check($params,$row=null);
        } catch (ValidateException|PDOException|Exception $e) {
            $this->error($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()->validate($validate);
            }
            $this->update_check($params,$row=null);
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        try {
            $this->update_check($params,$row);
        } catch (ValidateException|PDOException|Exception $e) {
            $this->error($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 . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->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|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        foreach ($list as $item) {
            $this->updateCheck($item->id);
        }


        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
//                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }



    /**
     * 跳转链接
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function url($ids = ''){
        $param = $this->request->param();
        if($this->request->isPost()){
            try{
                if(isset($param['ids']))$ids = $param['ids'];
                //设置模拟资格
                $url =  \app\common\model\school\classes\Teacher::getPath($ids);

            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success($url);
        }
        $row = $this->model->get($ids);
        $this->view->assign('vo', $row);
        return $this->view->fetch();
    }


    /**
     * 微信小程序码
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    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->error($e->getMessage());
        }

        return $url["response"];
    }




    /**
     * 查看微信小程序码
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function lookminiqrcode($ids = ''){
        $param = $this->request->param();
        if($this->request->isPost()){
            try{
                if(isset($param['ids']))$ids = $param['ids'];
                //设置模拟资格
                $url =  \app\common\model\school\classes\Teacher::getMiniQrcodeLink($ids);

            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success("生成小程序码成功",null,$url);
        }
        $row = $this->model->get($ids);
        $this->view->assign('vo', $row);
        return $this->view->fetch();
    }



}
