Plan.php 12.3 KB
<?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->relationSearch = true;
        //设置过滤方法
        $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('staff')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {
                $row->getRelation('staff')->visible(['staff_name','mobile']);
            }
            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(empty($params['staff_id'])){
                        $this->error("请选择巡检人员");
                    }
                    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']);
                    }
                    // 把结束时间设置为当天最后一秒
                    if (!empty($params['endtime'])){
                        $params['endtime'] = date('Y-m-d H:i:s',strtotime($params['endtime']) + 24*3600 - 1);
                    }

                    // 至少有一次执行时间点
                    if (empty($params['exetimes']) || $params['num'] <= 0){
                        $this->error('请至少添加一个巡检时间点');
                    }

                    $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(empty($params['staff_id'])){
                        $this->error("请选择巡检人员");
                    }
                    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']);
                    }
                    // 把结束时间设置为当天最后一秒
                    if (!empty($params['endtime'])){
                        $params['endtime'] = date('Y-m-d H:i:s',strtotime($params['endtime']) + 24*3600 - 1);
                    }

                    // 至少有一次执行时间点
                    if (empty($params['exetimes']) || $params['num'] <= 0){
                        $this->error('请至少添加一个巡检时间点');
                    }

                    $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']);

        //发送exetimes到js
        $this->assignconfig('exetimes', $row['exetimes']);

        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();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    //删除关联数据
                    $projectIds = Db::name('inspection_project')->where(['plan_id' => $v['id']])->column('id');
                    if (!empty($projectIds)){
                        Db::name('inspection_project_item')->where(['project_id' => ['in', $projectIds]])->delete();
                        Db::name('inspection_warning')->where(['project_id' => ['in', $projectIds]])->delete();
                        Db::name('inspection_project')->where(['id' => ['in', $projectIds]])->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'));
    }
}