<?php

namespace app\manystore\controller\school\classes;

use app\common\controller\ManystoreBase;
use app\admin\model\dyqc\ManystoreShop;
use app\common\controller\Backend;
use app\common\model\school\classes\lib\Spec;
use app\common\model\school\classes\Order;
use app\manystore\model\Manystore;
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;

/**
 * 机构课程库
 *
 * @icon fa fa-circle-o
 */
class ClassesLib extends ManystoreBase
{

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

    /**
     * ClassesLib模型对象
     * @var \app\manystore\model\school\classes\ClassesLib
     */
    protected $model = null;

    //不用审核允许修改的字段
    protected $no_auth_fields = ["classes_type","classes_cate_ids","classes_label_ids","self_label_tag",'headimage','images','notice','content',"virtual_num","virtual_collect","underline_price","selfhot","price","classes_num"];

    //更新数据是否需要触发审核开关
    protected $need_auth = true;
    protected $have_auth = false;

    protected $success_auth = false;

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

        $this->view->assign("addTypeList", $this->model->getAddTypeList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("addressTypeList", $this->model->getAddressTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("authStatusList", $this->model->getAuthStatusList());
        $this->view->assign("recommendList", $this->model->getRecommendList());
        $this->view->assign("hotList", $this->model->getHotList());
        $this->view->assign("newList", $this->model->getNewList());
        $this->view->assign("selfhotList", $this->model->getSelfhotList());

        $this->view->assign("classesTypeList", $this->model->getClassesTypeList());
        $this->view->assign("classesTypeListJson", json_encode($this->model->getClassesTypeList(), JSON_UNESCAPED_UNICODE));

        $this->view->assign("classes_number_only_one", config("site.classes_number_only_one"));

         $this->view->assign("specStatusList", (new \app\manystore\model\school\classes\ClassesSpec)->getStatusList());

         $this->getCity();

        $this->view->assign('check_full',(new \app\common\model\dyqc\ManystoreShop)->checkFull(SHOP_ID));
        $this->view->assign('check_full_msg',(new \app\common\model\dyqc\ManystoreShop)->checkFullMsg(SHOP_ID));
    }

    public function import()
    {
        parent::import();
    }

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


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->searchFields = ["id","title","address","address_detail","address_city","user.nickname","user.realname","user.mobile","manystoreshop.name"];
        //设置过滤方法
        $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, $page, $alias, $bind, $excludearray) = $this->buildparams(null, null, ["has_expire"]);

            if (isset($excludearray['has_expire']['value']) && $excludearray['has_expire']['value']) {
                $has_expire = $excludearray['has_expire']['value'];
                $as = (new \app\common\model\school\classes\ClassesLib())->getWithAlisaName();
                switch ($has_expire) {
                    case '1':  //查过期
                        $expireWhere = [
                            $as . '.end_time', '<=', time(),
                        ];
                        break;
                    case '2':  //查未过期
                        $expireWhere = [
                            $as . '.end_time', '>', time(),
                        ];
                        break;
                    default:
                }

            } else {
                $expireWhere = [[]];
            }

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

//            var_dump($this->model->getLastSql());die;

            foreach ($list as $row) {

                $row->getRelation('manystore')->visible(['nickname']);
				$row->getRelation('manystoreshop')->visible(['name','image','address_city','province','city','district','address','address_detail']);
				$row->getRelation('user')->visible(['nickname','realname','mobile','avatar']);
				$row->getRelation('admin')->visible(['nickname','avatar']);
            }

             $rows = $list->items();
             $types = \app\admin\model\school\classes\Type::column("name", 'id');

            foreach ($rows as $k=>&$v){
                $v["classes_type_name"] = $types[$v["classes_type"]] ?? "无" ;
            }

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

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


    protected function authClasses(&$params,$row=null){
        //审核失败需填写原因
        if($params["auth_status"] == '2' && empty($params["reason"])){
            $this->error("审核失败需填写原因");
        }

        if($params["auth_status"] == '2'){
            //审核不通过会平台下架
            $params["status"] = '3';
        }

        //更新
        if($row){

            if($params["auth_status"] != '1' && $row["auth_status"] == '1'){
                $this->error("审核已通过的课程不允许再修改审核状态!");
            }

            if($params["auth_status"] != '0' && $row["auth_status"] == '0'){
                //填写审核时间和审核人
                $params["auth_time"] = time();
                $params["admin_id"] = $this->auth->id;
                if($params["auth_status"] == '1'){
                    //审核通过
                    $this->success_auth = true;
                }
            }
            //审核通过
            if($this->success_auth){
                //如果是平台下架,则更新成正常下架
                if($params["status"] == '3') $params["status"] = '2';
            }



        }else{
            //新增

        }

    }

    protected function no_auth_fields_check($params,$row){

        foreach ($params as $k=>$v){

            //说明数值有变动
            //$params[$k] 去掉两端空格
            $params[$k] = trim($v);

            if($row[$k]!=$params[$k]){
                //特殊:如果是上架状态或下架状态也可以修改
                if($k=="status" && ($params[$k]=='1' || $params[$k]=='2')){
                     continue;
                }
                //当修改参数不在允许修改的字段中
                if(!in_array($k,$this->no_auth_fields)){

                    $this->have_auth = true;break;

                }
            }

        }

        return $this->have_auth;

    }

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

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

        // 课程存在未完成订单则不允许操作
        $order = Order::where("classes_lib_id",$id)->where("status","in","0,3")->find();
        if($order)$this->error("存在正在使用中的课程订单或存在正在售后中的课程订单无法继续操作!");
        // 课程存在售后订单则不允许操作
    }



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

        $shop_id = SHOP_ID;
        $params["shop_id"] = $shop_id;


        try {
             $classesLib =  new \app\common\model\school\classes\ClassesLib();
             $classesLib->no_auth_fields = $this->no_auth_fields;
             $classesLib->need_auth = $this->need_auth;
             $classesLib->have_auth = $this->have_auth;
             $classesLib->classesCheck($params,$shop_id,$row);

             $this->need_auth = $classesLib->need_auth;
             $this->have_auth = $classesLib->have_auth;



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




        //特有认证判断
//        $this->authClasses($params,$row);
//        var_dump($row);die;
        //更新
        if($row){

            if($row['status'] == "3" && $params['status'] != $row['status']){
                $this->error("平台下架审核的课程无法上架!");
            }


            //如果是审核失败,提交后自动更新成审核中
            if($row['auth_status'] == 2){
                $params['status'] = "3";
                $params['auth_status'] = 0;
                $params["reason"] = "";
            }


        }else{
            //新增(需审核)
            $params["add_type"] = '1';
            $params["add_id"] = $this->auth->id;
            $params['status'] = "3";//平台下架
            $params['auth_status'] = 0;


            $this->have_auth = true;
        }




    }

    protected function update_classes($classes_lib_id){
                //课时数必须大于等于课时核销数
       $count = \app\common\model\school\classes\ClassesSpec::where("classes_lib_id",$classes_lib_id)->count();
       $classes_num = \app\common\model\school\classes\ClassesLib::where("id",$classes_lib_id)->value("classes_num");
       if($count < $classes_num){
       throw new \Exception("课时数必须大于等于课时核销数");
       }
        \app\common\model\school\classes\ClassesLib::update_classes($classes_lib_id);
    }



    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function addnew()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if($this->storeIdFieldAutoFill && STORE_ID ){
                    $params['store_id'] = STORE_ID;
                }

                if($this->shopIdAutoCondition && SHOP_ID){
                    $params['shop_id'] = SHOP_ID;
                }
                 //是否采用模型验证
                    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 = false;
                Db::startTrans();
                try {


                    $spec = $params["spec"];
                    unset($params["spec"]);
                    $result = $this->model->allowField(true)->save($params);
                    \app\common\model\school\classes\ClassesLib::add_virtual_init($this->model["id"]);
                    //添加课程规格
                    foreach ($spec as $k=>$v){
                        $v["classes_lib_id"] = $this->model["id"];
                        \app\common\model\school\classes\ClassesSpec::create($v);
                    }

                    //因为是批量添加,所有规格重新进行检测,防止出现时间重叠
                    $specss = \app\common\model\school\classes\ClassesSpec::where("classes_lib_id",$this->model["id"])->select();
            foreach ($specss as $k=>$specs){
                        $params =$specs;
                        (new \app\common\model\school\classes\ClassesSpec)->specCheck($params,null,$specs);
             }

                    $this->update_classes($this->model["id"]);
                    if($this->have_auth){
                        //调用通过事件
                        $data = ['classes' => $this->model];
                        \think\Hook::listen('classes_auth_need_after', $data);

                    }


                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }



    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if($this->storeIdFieldAutoFill && STORE_ID ){
                    $params['store_id'] = STORE_ID;
                }

                if($this->shopIdAutoCondition && SHOP_ID){
                    $params['shop_id'] = SHOP_ID;
                }

                $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);
                    \app\common\model\school\classes\ClassesLib::add_virtual_init($this->model["id"]);
                    $this->update_classes($this->model["id"]);
                    if($this->have_auth){
                        //调用通过事件
                        $data = ['classes' => $this->model];
                        \think\Hook::listen('classes_auth_need_after', $data);

                    }


                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if($this->shopIdAutoCondition){
            $this->model->where(array('shop_id'=>SHOP_ID));
        }
        $row = $this->model->where(array('id'=>$ids))->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");



            if ($params) {
                $params = $this->preExcludeFields($params);

                                    //是否采用模型验证
//                    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 = false;
                Db::startTrans();
                try {


            $spec = $params["spec"] ?? [];//$params["delete_spec_ids"]
            $delete_spec_ids =   $params["delete_spec_ids"] ?? [];
            unset($params["spec"]);
            unset($params["delete_spec_ids"]);

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

           foreach ($spec as $k=>$v){
                 $v["classes_lib_id"] = $row["id"];
                 //有id更新,否则新增
                 if(isset($v["id"]) && $v["id"]){
                     \app\common\model\school\classes\ClassesSpec::update((new \app\common\model\school\classes\ClassesSpec)->checkAssemblyParameters($v));
                 }else{
                     \app\common\model\school\classes\ClassesSpec::create((new \app\common\model\school\classes\ClassesSpec)->checkAssemblyParameters($v));
                 }
           }
           //删除规格
             foreach ($delete_spec_ids as $k=>$delete_spec){
                   (new \app\common\model\school\classes\ClassesSpec)->updateCheck($delete_spec["id"]);

                 $delete_spec->delete();
             }

                            //因为是批量添加,所有规格重新进行检测,防止出现时间重叠
                    $specss = \app\common\model\school\classes\ClassesSpec::where("classes_lib_id",$row["id"])->select();
            foreach ($specss as $k=>$specs){
                         $params =$specs;
                        (new \app\common\model\school\classes\ClassesSpec)->specCheck($params,null,$specs);
             }


                    $this->update_classes($row["id"]);

                    if($this->have_auth){
                        //调用通过事件
                        $data = ['classes' => $row];
                        \think\Hook::listen('classes_auth_need_after', $data);

                    }


                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

            $spec = \app\common\model\school\classes\ClassesSpec::where("classes_lib_id",$row["id"])->field("id,classes_lib_id,name,start_time,end_time,limit_num,status,weigh")->order('weigh desc,id desc')->select();
            foreach ($spec as $k=>&$v){
                $v["time"] = date("Y/m/d H:i",$v["start_time"])." - ".date("Y/m/d H:i",$v["end_time"]);
            }
            $row["spec"] = json_encode($spec, JSON_UNESCAPED_UNICODE);//不转义任何字符串
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("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) {

                    //删除课程规格
                    Spec::where("classes_lib_id",$v->id)->delete();

                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


}