<?php

namespace app\admin\controller\inspection;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 巡检计划管理
 *
 * @icon fa fa-circle-o
 */
class Plan extends Backend
{
    
    /**
     * Plan模型对象
     * @var \app\admin\model\inspection\Plan
     */
    protected $model = null;
    protected $noNeedRight = ['dynamicselect','sel_staff'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\inspection\Plan;

    }

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

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $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
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list->items() as $k=>&$v){
                $routeModel = new \app\admin\model\inspection\Route();
                $routeInfo = $routeModel->where(['id'=>$v['route_id']])->find();
                $v['route_name'] = empty($routeInfo)?'':$routeInfo['route_name'];
            }

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

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

    public function dynamicselect(){
        $route = new \app\admin\model\inspection\Plan();
        $list = $route->order("id desc")->select();
        foreach($list as $k=>$v){
            $agentJson[$v['id']] = $v['plan_name'];
        }

        echo json_encode($agentJson,JSON_FORCE_OBJECT);
    }


    /**
     * 选择巡检人
     */
    public function sel_staff(){

        return $this->fetch();
    }

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

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->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);
                    }
                    if($params['circle_type'] == 1){
                        $params['circle_value'] = "";
                    }else if($params['circle_type'] == 2){
                        if(empty($params['week'])){
                            $this->error("请选择星期");
                        }
                        $params['circle_value'] = implode(",",$params['week']);
                    }else if($params['circle_type'] == 3){
                        if(empty($params['month'])){
                            $this->error("请选择执行的天");
                        }
                        $params['circle_value'] = implode(",",$params['month']);
                    }

                    $result = $this->model->allowField(true)->save($params);
                    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', ''));
        }

        $routeModel = new \app\admin\model\inspection\Route();
        $routeList = $routeModel->order("id desc")->select();
        $this->assign('routeList',$routeList);

        $this->assign('week',['1'=>'星期一','2'=>'星期二','3'=>'星期三','4'=>'星期四','5'=>'星期五','6'=>'星期六','7'=>'星期日']);
        $month = range(1,31);
        $this->assign('month',$month);
        return $this->view->fetch();

    }

    /**
     * 编辑
     * @param null $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    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)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $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(true)->validate($validate);
                    }

                    if($params['circle_type'] == 1){
                        $params['circle_value'] = "";
                    }else if($params['circle_type'] == 2){
                        if(empty($params['week'])){
                            $this->error("请选择星期");
                        }
                        $params['circle_value'] = implode(",",$params['week']);
                    }else if($params['circle_type'] == 3){
                        if(empty($params['month'])){
                            $this->error("请选择执行的天");
                        }
                        $params['circle_value'] = implode(",",$params['month']);
                    }
                    $result = $row->allowField(true)->save($params);
                    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', ''));
        }
        switch($row['circle_type']){
            case 1:
                $row['week'] = $row['month'] = "";
                break;
            case 2:
                $row['week'] = $row['circle_value'];
                $row['month'] = "";
                break;

            case 3:
                $row['week'] = "";
                $row['month'] = $row['circle_value'];

                break;

        }
        $this->view->assign("row", $row);

        $routeModel = new \app\admin\model\inspection\Route();
        $routeList = $routeModel->order("id desc")->select();
        $this->assign('routeList',$routeList);

        $this->assign('week',['1'=>'星期一','2'=>'星期二','3'=>'星期三','4'=>'星期四','5'=>'星期五','6'=>'星期六','7'=>'星期日']);
        $month = range(1,31);
        $this->assign('month',$month);

        //获取员工姓名
        $staffModel = new \app\admin\model\inspection\Staff();
        $staffInfo = $staffModel->where(['id'=>$row['staff_id']])->find();
        $this->assign('staff_name',empty($staffInfo)?'':$staffInfo['staff_name']);


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

}