<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
/**
 * 维修单
 *
 * @icon fa fa-circle-o
 */
class Maintain extends Backend
{

    /**
     * Maintain模型对象
     * @var \app\admin\model\Maintain
     */
    protected $model = null;

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



    /**
     * 查看
     */
    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(['company','user','usercompany','worker'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('company')->visible(['companyname']);
				$row->getRelation('user')->visible(['nickname','mobile']);
				$row->getRelation('usercompany')->visible(['projectname']);
				$row->getRelation('worker')->visible(['truename','mobile']);
            }

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

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

    /**
     * 编辑
     *
     * @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()) {

            //
            $row['filedata_array'] = json_decode($row['filedata'],true);
            //

            $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);
        $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);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
        Db::rollback();
        $this->error($e->getMessage());
    }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 总部指派
     * 复制pc端的指派,稍作调整
     */
    public function zhipai()
    {
        $id = input('id',0);
        $row = Db::name('maintain')->where('id',$id)->find();
        if(!$this->request->isPost()){
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }

        //检查师傅
        $worker_id   = input('worker_id',0);

        $worker = Db::name('worker')->where('id',$worker_id)->where('status',1)->where('company_id',1)->find();
        if(empty($worker)){
            $this->error('没找到该师傅');
        }

        //检查订单
        $id   = input('id',0);

        Db::startTrans();
        $info = Db::name('maintain')->where('id',$id)->lock(true)->find();
        if(empty($info)){
            Db::rollback();
            $this->error('没找到该信息,请刷新重试');
        }

        if(!in_array($info['status'],[0,20,22,30,40])){
            Db::rollback();
            $this->error('当前订单状态,不能指派师傅');
        }

        if(!empty($info['worker_id'])){
            Db::rollback();
            $this->error('已经指派了师傅');
        }

        //
        $update = [
            'worker_id'  => $worker_id,
            'status'     => 50,
            'updatetime' => time(),
        ];
        $rs_update = Db::name('maintain')->where('id',$id)->update($update);
        if($rs_update === false){
            Db::rollback();
            $this->error('指派失败,请重试');
        }

        //
        Db::commit();
        $this->success();
    }

}