Workorder.php 13.3 KB
<?php

namespace app\admin\controller\inspection;

use app\admin\model\notices\Noticesnormal;
use app\common\controller\Backend;
use app\common\library\Getui;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 巡检工单
 *
 * @icon fa fa-circle-o
 */
class Workorder extends Backend
{
    
    /**
     * Workorder模型对象
     * @var \app\admin\model\inspection\Workorder
     */
    protected $model = null;

    protected $searchFields = 'id,message,staff.staff_name,warning.title';

    protected $modelValidate = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\inspection\Workorder;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    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->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(['warning','staff','category','categoryp'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('warning')->visible(['title']);
                $row->getRelation('staff')->visible(['staff_name']);
                $row->getRelation('category')->visible(['name']);
                $row->getRelation('categoryp')->visible(['name']);
            }

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

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

    /**
     * 添加
     */
    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);
                    }

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

                    $staffModel = new \app\admin\model\inspection\Staff();
                    $staff = $staffModel
                        ->field('u.id,u.clientid')
                        ->alias('staff')
                        ->join('user u', 'u.id=staff.user_id', 'LEFT')
                        ->where(['staff.id' => $params['staff_id']])
                        ->find();
                    if ($staff && !empty($staff['clientid'])){
                        //发送推送消息
                        $getui = new Getui();
                        $cid = $staff['clientid'];
                        $notifyTitle = $params['message'] ?? '异常';
                        if (!empty($params['warning_id'])){
                            $warning = \app\admin\model\inspection\Warning::get($params['warning_id']);
                            if ($warning){
                                $notifyTitle = $warning['title'];
                            }
                        }
                        $notifyBody = $notifyTitle . ',请及时处理';
                        $payload = ['notice_type' => 1, 'workorder_id' => $this->model->id,'title' => $notifyTitle, 'content' => $notifyBody];
                        $resArr = $getui->pushToSingleByCid($cid, $notifyTitle, $notifyBody, 'payload', '', json_encode($payload));
                        //记录消息推送日志
                        $logData = [
                            'notice_type' => 1,
                            'notice_title' => $notifyTitle,
                            'notice_content' => $notifyBody,
                            'relation_table' => 'inspection_workorder',
                            'relation_id' => $this->model->id,
                            'send_type' => 2,//管理员
                            'send_id' => $this->auth->id,
                            'rec_type' => 1,//会员
                            'rec_id' => $staff['id']
                        ];
                        if ($resArr['code'] == 0){
                            $logData['taskid'] = '';
                            $logData['push_res'] = '';
                            foreach ($resArr['data'] as $taskid => $cr){
                                $logData['taskid'] = $taskid;
                                $logData['push_res'] = $cr[$cid] ?? '';
                            }
                        }else{
                            $logData['error_msg'] = $resArr['code'] . ':' . $resArr['msg'];
                        }
                        $noticesnormalModel = new Noticesnormal();
                        $noticesnormalModel->allowField(true)->save($logData);
                    }
                    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('发布成功', '', $resArr);
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    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);
                if ($params['status'] == '3' && empty($params['refuse_reason'])){
                    $this->error('请填写审核未通过的原因');
                }
                $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);
                    }
                    $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', ''));
        }
        $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();
            $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) {
                    $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'));
    }

    //通过异常报告ID获取异常详细信息
    public function getWarningById(){
        $warningId = $this->request->get('id') ?? 0;
        $warning = \app\admin\model\inspection\Warning::get($warningId);
        if ($warning){
            $this->success('成功', '', $warning);
        }else{
            $this->error('失败');
        }
    }

    //获取处理结果
    public function dealList(){
        $workorderId = $this->request->get('id') ?? 0;
//        if ($this->request->isPost()) {
//            $workorderId = $this->request->post('id') ?? 0;
//            $status = $this->request->post('status') ?? 0;
//            if (in_array($status, [2,3])){
//                $this->error('status参数错误');
//            }
//            $find = \app\admin\model\inspection\Workorder::get($workorderId);
//            if (!$find){
//                $this->error('工单不存在');
//            }
//            $find['status'] = $status;
//            $find->save();
//            $this->success();
//        }
//        $find = \app\admin\model\inspection\Workorder::get($workorderId);
//        if (!$find){
//            $this->error('工单不存在');
//        }
//        $this->assign('workorder', $find);
        $workorderdealModel = new \app\admin\model\inspection\Workorderdeal();
        $workorderdeals = $workorderdealModel->where(['workorder_id' => $workorderId])->order(['id' => 'desc'])->select();
        if ($workorderdeals){
            $workorderdeals = collection($workorderdeals)->toArray();
            foreach ($workorderdeals as &$workorderdeal){
                $staff = \app\admin\model\inspection\Staff::get($workorderdeal['staff_id']);
                $workorderdeal['staff_info'] = $staff;
                $workorderdeal['images_arr'] = [];
                if (!empty($workorderdeal['images'])){
                    $imageArr = explode(',', $workorderdeal['images']);
                    foreach ($imageArr as $imageKey => $image){
                        if (strpos($image, "http") !== 0) {
                            $imageArr[$imageKey] = full_image_kevin($image);
                        }
                    }
                    $workorderdeal['images_arr'] = $imageArr;
                }
                $workorderdeal['files_arr'] = [];
                $workorderdeal['videos_arr'] = [];
                if (!empty($workorderdeal['files'])){
                    $filesArr = explode(',', $workorderdeal['files']);
                    foreach ($filesArr as $fileKey => $file){
                        if (strpos($file, "http") !== 0) {
                            $filesArr[$fileKey] = full_image_kevin($file);
                        }
                        if (preg_match("/\.mp4$/", $filesArr[$fileKey])) {
                            $workorderdeal['videos_arr'][] = $filesArr[$fileKey];
                        } else {
                            $workorderdeal['files_arr'][] = $filesArr[$fileKey];
                        }
                    }
                }
            }
            $this->assign('deals', $workorderdeals);
        }else{
            $this->assign('deals', []);
        }
        return $this->view->fetch();
    }

}