<?php

namespace app\admin\controller;
use think\App;
use think\Db;
use think\Exception;

class Orders extends Auth {
    public function __construct(App $app = null) {
        parent::__construct($app);
        $this->model = new \app\common\model\Orders();
        $this->table = $this->model->table;
    }
    //用户订单列表
    public function selfIndex() {
        $mode = input('mode', 1);
        if (request()->isAjax()) {
            //分页参数
            $length = input('rows', 10, 'intval');   //每页条数
            $page = input('page', 1, 'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx', 'id', 'trim');      //排序列
            $sort = input('sord', 'desc', 'trim');        //排序方式
            $order = $sortRow . ' ' . $sort;
            $map[] = ['del', '=', 0];
            $map[] = ['org_id', '=', $this->orgId];
            $order_mode = input('order_mode', '', 'trim');
            if ($order_mode != '') {
                $map[] = ['order_mode', '=', $order_mode];
            }
            if($mode >0){
                $map[] = ['work_type_mode', '=', $mode];

            }else{
                $map[] = ['source_type', '=', 4];

            }
            $sn = input('sn', '', 'trim');
            if ($sn) {
                $map[] = ['sn', 'like', '%' . $sn . '%'];
            }
            if (!is_admin($this->userId)) {
                $map[] = ['user_id', '=', $this->userId];
            }
            $map = empty($map) ? true : $map;
            //数据查询
            $lists = db($this->table)->where($map)->limit($start, $length)->order($order)->select();
            foreach ($lists as $k => $v) {
                $lists[$k] = $this->model->formatOrder($v);
            }
            //数据返回
            $totalCount = db($this->table)->where($map)->count();
            $totalPage = ceil($totalCount / $length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }
        else {
            $mode_name = $this->getTableField('work_type_mode', ['id' => $mode], 'name');
            if($mode==4){
                $mode_name = '应急';
            }
            $this->assign('m_name', $mode_name);
            $this->assign('mode', $mode);
            $order_mode = Db::name('order_mode')->select();
            $this->assign('order_mode_list', $order_mode);
            if ($mode == 1) {
                return $this->fetch('selfIndex1');
            }
            else {
                if ($mode == 3) {
                    return $this->fetch('selfIndex3');
                }
                else {
                    return $this->fetch('selfIndex');
                }
            }
        }
    }
    //用户添加订单
    public function selfAdd($mode = 1) {
        if (request()->isPost()) {
            $data = request()->post();
            $data['user_id'] = $this->userId;
            $data['org_id'] = $this->orgId;
            $data['work_type_mode'] = $mode;
            $data['images'] = isset($data['images']) && !empty($data['images']) ? implode(',', $data['images']) : '';
            $res = $this->model->addSave($data);
            if ($res) {
                $this->success('操作成功');
            }
            else {
                $this->error($this->model->getError());
            }
        }
        else {
            $dep = $this->getTableField('user_dep', ['user_id' => $this->userId], 'dep_id');
            $depList = (new \app\common\model\Dep())->getList();
            $this->assign('dep_id', $dep);
            $this->assign('dep_list', $depList);
            $this->assign('mode', $mode);
            if ($mode == 3) {
                $address = (new \app\common\model\Address())->getListByType(2);
                $conveyCate = (new \app\common\model\ConveyCate());
                $priority = $conveyCate->priority;
                $order_convey = $conveyCate->getList();
                $order_device = (new \app\common\model\ConveyDevice())->getList();
                $this->assign('address', $address);
                $this->assign('priority', $priority);
                $this->assign('order_convey_type', $order_convey);
                $this->assign('order_device', $order_device);
            }
            $user = Db::name('user')
                ->where('id',$this->userId)
                ->find();
            $this->assign('user',$user);
            if ($mode == 3) {
                return $this->fetch('self_add3');
            }
            else {
                return $this->fetch('self_add');
            }
        }
    }
    //用户取消订单
    public function cancel($id) {
        $res = $this->model->cancel($id, $this->userId);
        if (!$res) {
            $this->error($this->model->getError());
        }
        $this->success('取消成功');
    }
    //调度取消订单
    public function disCancel($id) {
        if (request()->isGet()) {
            $this->assign('id', $id);
            return $this->fetch();
        }
        else {
            $reason = input('cancel_reason');
            $res = $this->model->cancel($id, $this->userId, 2, $reason);
            if (!$res) {
                $this->error($this->model->getError());
            }
            $this->success('取消成功');
        }
    }
    //延迟订单
    public function batchdelay($id) {
        if (request()->isGet()) {
            $delay_reason = Db::name('delay_reason')
                ->where('org_id', $this->orgId)
                ->where('enable', 1)
                ->where('del', 0)
                ->select();
            $this->assign('delay_reason', $delay_reason);
            $this->assign('id', $id);
            return $this->fetch();
        }
        else {
            $delay_reason_id = input('delay_reason_id');
            if (empty($delay_reason_id)) {
                $this->error('请选择延迟原因');
            }
            $res = $this->model->delay_reason($id, $delay_reason_id);
            if (!$res) {
                $this->error($this->model->getError());
            }
            $this->success('延迟成功');
        }
    }
    //取消延迟订单
    public function batchcanceldelay($id) {
        if (request()->isGet()) {
            $this->assign('id', $id);
            return $this->fetch();
        }
        else {
            $res = $this->model->batchcanceldelay($id);
            if (!$res) {
                $this->error($this->model->getError());
            }
            $this->success('延迟成功');
        }
    }
    //用户查看订单详情
    public function detail($id) {
        if (!$id) {
            $this->error('参数错误');
        }
        $order = Db::name('orders')->where(['id' => $id])->find();
        $order = $this->model->formatOrder($order, 1);
        $order['images'] = !empty($order['images']) ? explode(',', $order['images']) : '';

        if($order['work_type_mode'] == 3){
            // 地点路径
            $conveyends = Db::name('order_convey_end')
                ->alias('a')
                ->join('address b','b.id = a.addr')
                ->where('a.order_id',$id)
                ->order('a.id asc')
                ->field('a.addr,b.title,a.scan,a.create_time,a.update_time')
                ->select();
            $order['ends'] = $conveyends?$conveyends:[];
        }


        $this->assign('info', $order);
        $workTypeName = $this->getTableField('work_type_mode', ['id' => $order['work_type_mode']], 'name');
        $this->assign('meta_title', $workTypeName . '订单详情');
        return $this->fetch();
    }
    //调度订单列表
    public function index() {
        $mode = input('mode', 0);
        $quality_type = input('quality_type','');
        $level1 = check_is_dispatch($this->userId);
        $level2 = check_two_dispatch($this->userId);
        $turnoff = two_dispatch_off($this->orgId);
        if (request()->isAjax()) {
            //分页参数
            $length = input('rows', 10, 'intval');   //每页条数
            $page = input('page', 1, 'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx', 'id', 'trim');      //排序列
            $sort = input('sord', 'desc', 'trim');        //排序方式
            $order = $sortRow . ' ' . $sort;
            $content = input('content', '', 'trim');
            if ($content) {
                $map[] = ['content', 'like', '%' . $content . '%'];
            }
            $dep_id = input('dep_id', '', 'trim');
            if ($dep_id != '') {
                $map[] = ['dep_id', '=', $dep_id];
            }
            $dep_cate = input('dep_cate', '', 'trim');
            if ($dep_cate != '') {
                $depIds = Db::name('dep')
                    ->where('org_id',$this->orgId)
                    ->where('cate_id',$dep_cate)
                    ->where('del',0)
                    ->column('id');
                if(!empty($depIds)){
                    $map[] = ['dep_id', 'in', $depIds];
                }else{
                    $map[] = ['dep_id', '=', -1];

                }
            }
            $order_mode = input('order_mode', '', 'trim');
            $map6 = [];
            if ($order_mode != '') {
                if($level1 && $turnoff && $mode != 15){ // 一级调度且二级调度开关开着,品质整改例外
                    if ($order_mode == 1) {
                        $map[] = ['is_deal', '=', 0];
                    }else if ($order_mode == 4) {
                        $map6[] = ['is_deal', '=', 1];
                    }
                }
                if($order_mode==100){//已挂起
                    $gq = Db::name('todo')
                        ->where('work_type_mode',1)
                        ->where('todo_mode',2)
                        ->where('pause',1)
                        ->column('order_id');
                    if(empty($gq)){
                        $map[] = ['id', '=', -1];
                    }else{
                        $map[] = ['id', 'in', $gq];
                    }
                }else{
                    $map[] = ['order_mode', '=', $order_mode];
                }
            }
            $b = input('start', '', 'trim');
            $e = input('end', '', 'trim');
            if ($b) {
                $b = date('Ymd', strtotime($b));
                $map[] = ['create_yyyymmdd', '>=', $b];
            }
            if ($e) {
                $e = date('Ymd', strtotime($e));
                $map[] = ['create_yyyymmdd', '<=', $e];
            }
            $map[] = ['del', '=', 0];
            $map[] = ['org_id', '=', $this->orgId];
            if($mode==-1){
                $map[] = ['source_type', '=', 4];
            }
            $type = input('type', '', 'trim');
            $oids = [];
            if ($type != '') {
                $map1[] = ['parent_id', '=', $type];
                $type_id = Db::name('order_type')
                    ->where($map1)
                    ->where('org_id', $this->orgId)
                    ->where('enable', 1)
                    ->column('id');
                if (!empty($type_id)) {
                    $map3[] = ['type_id', 'in', $type_id];
                    $ids = Db::name('order_repair')
                        ->where($map3)
                        ->column('order_id');
                    if (!empty($ids)) {
                        $oids = $ids;
                    }
                    else {
                        $oids = [];
                    }
                }
                else {
                    $oids = [];
                }
            }

            if($level2 && $turnoff){ // 二级调度
                $roles_id = Db::name('user_roles')
                    ->where('user_id', $this->userId)
                    ->value('roles_id');
                $ids = Db::name('dispatch_log')
                    ->where('roles_id', $roles_id)
                    ->whereOr('to_user_id', $this->userId)
                    ->column('order_id');
                if (empty($ids)) {
                    $map[] = ['id', '=', -1];
                } else {
                    if($type != ''){
                        $oids = array_intersect($oids,$ids);
                        if($oids){
                            $map[] = ['id', 'in', $oids];
                        }else{
                            $map[] = ['id', '=', -1];
                        }
                    }else{
                        $map[] = ['id', 'in', $ids];

                    }
                }
            }else{
                if($type != ''){
                    if($oids){
                        $map[] = ['id', 'in', $oids];
                    }else{
                        $map[] = ['id', '=', 0];
                    }
                }
            }
            if($mode == 15){ // 品质检查,单独处理
                $map[] = ['work_type_mode','=',$mode];
                if($quality_type!=''){
                    $map[] = ['quality_type','=',$quality_type];

                }
            }else{
                $work_type_mode = input('work_type_mode','','trim');
                if(!is_admin($this->userId)){
                    $auth = get_dispatch_auth($this->userId);
                    if($auth){
                        $map[] = ['work_type_mode', 'in', $auth];
                        if($mode > 0){
                            $map[] = ['work_type_mode', '=', $mode];
                        }else{
                            if($work_type_mode!=''){
                                $map[] = ['work_type_mode','=',$work_type_mode];
                            }
                        }
                    }else{
                        $map[] = ['work_type_mode', '=', -1];
                    }
                }else{
                    if($mode > 0){
                        $map[] = ['work_type_mode', '=', $mode];
                    }else{
                        if($work_type_mode!=''){
                            $map[] = ['work_type_mode','=',$work_type_mode];
                        }
                    }
                }
            }
            $sn = input('sn', '', 'trim');
            if ($sn) {
                $map[] = ['sn', 'like', '%' . $sn . '%'];
            }
            $from = input('from', '', 'trim');
            if ($from) {
                if($from >3){
                    $map[] = ['from','=',0];
                    $map[] = ['work_type_mode','=',$from-3];
                }else{
                    $map[] = ['from','=',$from];
                }
            }
            $map = empty($map) ? true : $map;
            //数据查询
            $lists = db($this->table)->where($map)
                ->whereOr($map6)
                ->limit($start, $length)->order($order)->select();

            foreach ($lists as $k => $v) {
                $lists[$k] = $this->model->formatOrder($v);
                if ($turnoff && $level1 && $v['order_mode'] == 1 && $v['is_deal'] == 1) {
                    $lists[$k]['order_mode_text'] = '已派发';
                }
                $lists[$k]['bh_nums'] = Db::name('todo')->where('order_id',$v['id'])->where('del',0)->where('todo_mode',4)->count();
                $gq = Db::name('todo')
                   ->where('order_id',$v['id'])
                   ->where('work_type_mode',1)
                   ->where('todo_mode',2)
                   ->where('pause',1)
                   ->find();
                $lists[$k]['gq'] = $gq?'存在挂起':'';
            }

            //数据返回
            $totalCount = db($this->table)->where($map)->count();

            $totalPage = ceil($totalCount / $length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }
        else {
            if($mode >0){
                $mode_name = $this->getTableField('work_type_mode', ['id' => $mode], 'name');
            }else{
                $mode_name = '';
            }
            if($mode==4){
                $mode_name = '应急';
            }
            $auths = [1,2,3,4,15,0];
            if(!is_admin($this->userId)){
                $auth = get_dispatch_auth($this->userId);
                if($auth){
                    $auths = array_intersect($auths,$auth);
                    if($mode > 0){
                        $auths = array_intersect($auths,[$mode]);
                    }
                }else{
                    $auths = [];
                }
            }
            $this->assign('auths',$auths);

            $dep_list = (new \app\common\model\Dep())->getList();
            $order_type = (new \app\common\model\OrderType())->list();
            $order_mode = Db::name('order_mode')
                ->select();
            $this->assign('dep_list', $dep_list);
            $this->assign('order_type_list', $order_type);
            $this->assign('m_name', $mode_name);
            $this->assign('mode', $mode);
            $this->assign('order_mode_list', $order_mode);
            $this->assign('dispatch_type', check_two_dispatch($this->userId));
            $this->assign('quality_type',$quality_type);
            $dep_cate = model('DepCate')->getList();
            $this->assign('dep_cate',$dep_cate);

            //抢单开关
            $this->assign('org_grab_order',(new \app\common\model\Config())
                ->getConfig('org_grab_order1',$this->orgId));

            $is = 0;
            if(!isset($_GET['quality_type']) && $mode==15){
                $is = 1;
            }
            $this->assign('is',$is);

            if ($mode == 1) {
                return $this->fetch('index1');
            }
            else {
                if ($mode == 3) {
                    return $this->fetch('index3');
                }else if (in_array($mode,[0,-1])) {
                    return $this->fetch('index0');
                }
                else {
                    return $this->fetch('index');
                }
            }
        }
    }
    //调度删除订单
    public function del($id = 0) {
        if (!$id) {
            $this->error('参数错误');
        }
        $model = (new \app\common\model\Orders());
        $res = $model->del($id, $this->userId);
        if (!$res) {
            $this->error($model->getError());
        }
        $this->success('删除成功');
    }
    //调度添加订单
    public function dispatchAdd($mode = 1) {
        $id = input('id', 0);
        if (request()->isPost()) {
            $data = request()->post();
            $data['user_id'] = $this->userId;
            $data['org_id'] = $this->orgId;
            $data['work_type_mode'] = isset($data['work_type_mode'])?$data['work_type_mode']:$mode;
            $data['images'] = isset($data['images']) && !empty($data['images']) ? implode(',', $data['images']) : '';
            if ($id > 0) {
//                $phoneInfo = Db::name('phone_monitor_record')
//                    ->where('id', $id)
//                    ->find();
                $data['id'] = $id;
                $data['user_id'] = $this->userId;
            }
            $res = $this->model->addSave($data, 1);
            if ($res) {
                $this->success('操作成功');
            }
            else {
                $this->error($this->model->getError());
            }
        }
        else {
            if($mode==0){//创建一键呼叫
                $dep = $this->getTableField('user_dep', ['user_id' => $this->userId], 'dep_id');
                $depList = (new \app\common\model\Dep())->getList();
                $this->assign('dep_id', $dep);
                $this->assign('dep_list', $depList);

                $order_type = (new \app\common\model\OrderType())->getList();
                $address = (new \app\common\model\Address())->getListByType(1);
                $this->assign('order_type_list', $order_type);
                $this->assign('address_list', $address);
                $order_repair = Db::name('order_repair')
                    ->where('order_id', $id)
                    ->find();
                $this->assign('order_repair', $order_repair);

                $workType = Db::name('work_type_mode')
                    ->where('type',1)
                    ->select();
                $config = Db::name('config')
                    ->where('name','web_order_transfer_type')
                    ->value('value');
                if(empty($config)){
                    $workType = [];
                }else{
                    $ll = explode('|',$config);
                    foreach ($workType as $kk=>$vv){
                        if(!in_array($vv['id'],$ll)){
                            unset($workType[$kk]);
                        }
                    }
                }

                if(!is_admin($this->userId)){
                    $auth = get_dispatch_auth($this->userId);
                    if(empty($auth)){
                        $workType = [];
                    }else{
                        foreach ($workType as $kk=>$vv){
                            if(!in_array($vv['id'],$auth)){
                                unset($workType[$kk]);
                            }
                        }
                    }

                }
                foreach ($workType as $k=>$v){
                    $this->assign('send_user_num'.$v['id'], $this->model->sendUserNum($v['id'], $this->orgId));
                    $this->assign('user_list'.$v['id'], (new \app\common\model\WorkTypeMode())->getRolesUserByNum($v['id'], $this->orgId, 1));
                    $two_dispatch_roles = model('user')->get_two_dispatch_role($this->orgId, $v['id']);
                    $this->assign('dispatch_roles'.$v['id'], $two_dispatch_roles);
                }

                $this->assign('dispatch_type', check_two_dispatch($this->userId));
                $this->assign('two_dispatch_off', two_dispatch_off($this->orgId));
                $this->assign('workType', $workType);
                $address = (new \app\common\model\Address())->getListByType(2);
                $conveyCate = (new \app\common\model\ConveyCate());
                $priority = $conveyCate->priority;
                $order_convey = $conveyCate->getList();
                $order_device = (new \app\common\model\ConveyDevice())->getList();
                $this->assign('address', $address);
                $this->assign('priority', $priority);
                $this->assign('order_convey_type', $order_convey);
                $this->assign('order_device', $order_device);
                $oCid = Db::name('order_convey')
                    ->where('order_id',$id)
                    ->find();
                $opt = Db::name('order_convey_patient')
                    ->where('order_id',$id)
                    ->find();

                $this->assign('ocid',$oCid);
                $this->assign('opt',$opt);
                $this->assign('ps',empty($opt)?1:0);
                $this->assign('id', $id);
                $this->assign('mode', $mode);

                return $this->fetch('yjhj_dispatch_add');

            }else{
                $dep = $this->getTableField('user_dep', ['user_id' => $this->userId], 'dep_id');
                $depList = (new \app\common\model\Dep())->getList();
                $order_type = (new \app\common\model\OrderType())->getList();
                $address = (new \app\common\model\Address())->getListByType(1);
                $this->assign('dep_id', $dep);
                $this->assign('dep_list', $depList);
                $this->assign('order_type_list', $order_type);
                $this->assign('mode', $mode);
                $this->assign('send_user_num', $this->model->sendUserNum($mode, $this->orgId));
                $this->assign('user_list', (new \app\common\model\WorkTypeMode())->getRolesUserByNum($mode, $this->orgId,1));
                $this->assign('address_list', $address);
                $this->assign('address_id', '');
                if ($mode == 3) {
                    $address = (new \app\common\model\Address())->getListByType(2);
                    $conveyCate = (new \app\common\model\ConveyCate());
                    $priority = $conveyCate->priority;
                    $order_convey = $conveyCate->getList();
                    $order_device = (new \app\common\model\ConveyDevice())->getList();
                    $this->assign('address', $address);
                    $this->assign('priority', $priority);
                    $this->assign('order_convey_type', $order_convey);
                    $this->assign('order_device', $order_device);
                }
                if ($id > 0) {
//                    $phoneInfo = Db::name('phone_monitor_record')
//                        ->where('id', $id)
//                        ->find();
                    $this->assign('address_id', 0);
//                    $depId = Db::name('user_dep')
//                        ->where('user_id', $phoneInfo['user_id'])
//                        ->value('dep_id');
                    $this->assign('dep_id', 0);
                }
                $two_dispatch_roles = model('user')->get_two_dispatch_role($this->orgId, $mode);
                $this->assign('dispatch_roles', $two_dispatch_roles);
                $this->assign('dispatch_type', check_two_dispatch($this->userId));
                $this->assign('two_dispatch_off', two_dispatch_off($this->orgId));
                $this->assign('id', $id);
                if ($mode == 3) {
                    $user = Db::name('user')
                        ->where('id',$this->userId)
                        ->find();
                    $this->assign('user',$user);
                    return $this->fetch('dispatch_add3');
                }
                else {
                    return $this->fetch('dispatch_add');
                }
            }

        }
    }
    //调度查看订单详情
    public function detail2($id) {
        if (!$id) {
            $this->error('参数错误');
        }
        $type = input('type/d',0);
        $this->assign('type', $type);
        $order = Db::name('orders')->where(['id' => $id])->find();
        $order = $this->model->formatOrder($order, 1);
        $order['images'] = !empty($order['images']) ? explode(',', $order['images']) : '';

        $is_ch = 0;
        if($order['order_mode'] == 4){
            $todoInfo = Db::name('todo')->where('order_id',$order['id'])->where('del',0)->where('todo_mode','>',1)->find();
            if(!$todoInfo){
                $is_ch = 1;
            }
        }
        $order['is_ch'] =  $is_ch;

        $this->assign('info', $order);
        $workTypeName = $this->getTableField('work_type_mode', ['id' => $order['work_type_mode']], 'name');
        $this->assign('meta_title', $workTypeName . '订单详情');
        $level2 = check_two_dispatch($this->userId);
        $level1 = check_is_dispatch($this->userId);
        $turnoff = two_dispatch_off($this->orgId);
        $this->assign('level1', $level1);
        $this->assign('level2', $level2);
        $this->assign('turnoff', $turnoff);
        $this->assign('dispatch_type', $level2);
        $this->assign('org_auto_send',(new \app\common\model\Config())
            ->getConfig('org_auto_send',$this->orgId));
        return $this->fetch();
    }
    public function zg_detail($id) {
        if (!$id) {
            $this->error('参数错误');
        }
        $type = input('type/d',0);
        $this->assign('type', $type);
        $order = Db::name('orders')->where(['id' => $id])->find();
        $order = $this->model->formatOrder($order, 1);
        $order['images'] = !empty($order['images']) ? explode(',', $order['images']) : '';
        $this->assign('info', $order);
        $workTypeName = $this->getTableField('work_type_mode', ['id' => $order['work_type_mode']], 'name');
        $this->assign('meta_title', $workTypeName . '订单详情');
        $level2 = check_two_dispatch($this->userId);
        $level1 = check_is_dispatch($this->userId);
        $turnoff = two_dispatch_off($this->orgId);
        $this->assign('level1', $level1);
        $this->assign('level2', $level2);
        $this->assign('turnoff', $turnoff);
        $this->assign('dispatch_type', $level2);
        return $this->fetch();
    }
    public function print($id) {
        if (!$id) {
            $this->error('参数错误');
        }
        $type = input('type/d',0);
        $this->assign('type', $type);
        $order = Db::name('orders')->where(['id' => $id])->find();
        $order = $this->model->formatOrder($order, 1);
        $order['images'] = !empty($order['images']) ? explode(',', $order['images']) : '';
        $this->assign('info', $order);
        $workTypeName = $this->getTableField('work_type_mode', ['id' => $order['work_type_mode']], 'name');
        $this->assign('meta_title', $workTypeName . '订单详情');
        $level2 = check_two_dispatch($this->userId);
        $level1 = check_is_dispatch($this->userId);
        $turnoff = two_dispatch_off($this->orgId);
        $this->assign('level1', $level1);
        $this->assign('level2', $level2);
        $this->assign('turnoff', $turnoff);
        $this->assign('dispatch_type', $level2);
        return $this->fetch();
    }
    //派单
    public function send($id, $mode = 1) {
        if (request()->isGet()) {
            $this->assign('id', $id);
            $this->assign('mode', $mode);
            $orders = Db::name('orders')
                ->where('id',$id)
                ->find();
            if($orders['source_type']==4 && $orders['work_type_mode']==0 && $orders['is_deal']==0){//一键呼叫
                $order_type = (new \app\common\model\OrderType())->getList();
                $address = (new \app\common\model\Address())->getListByType(1);
                $this->assign('order_type_list', $order_type);
                $this->assign('address_list', $address);
                $order_repair = Db::name('order_repair')
                    ->where('order_id', $id)
                    ->find();
                $this->assign('order_repair', $order_repair);

                $workType = Db::name('work_type_mode')
                    ->where('type',1)
                    ->select();
                $config = Db::name('config')
                    ->where('name','web_order_transfer_type')
                    ->value('value');
                if(empty($config)){
                    $workType = [];
                }else{
                    $ll = explode('|',$config);
                    foreach ($workType as $kk=>$vv){
                        if(!in_array($vv['id'],$ll)){
                            unset($workType[$kk]);
                        }
                    }
                }
                foreach ($workType as $k=>$v){
                    $this->assign('send_user_num'.$v['id'], $this->model->sendUserNum($v['id'], $this->orgId));
                    $this->assign('user_list'.$v['id'], (new \app\common\model\WorkTypeMode())->getRolesUserByNum($v['id'], $this->orgId, 1));
                    $two_dispatch_roles = model('user')->get_two_dispatch_role($this->orgId, $v['id']);
                    $this->assign('dispatch_roles'.$v['id'], $two_dispatch_roles);
                }

                $this->assign('dispatch_type', check_two_dispatch($this->userId));
                $this->assign('two_dispatch_off', two_dispatch_off($this->orgId));
                $this->assign('workType', $workType);
                $this->assign('orders', $orders);
                $address = (new \app\common\model\Address())->getListByType(2);
                $conveyCate = (new \app\common\model\ConveyCate());
                $priority = $conveyCate->priority;
                $order_convey = $conveyCate->getList();
                $order_device = (new \app\common\model\ConveyDevice())->getList();
                $this->assign('address', $address);
                $this->assign('priority', $priority);
                $this->assign('order_convey_type', $order_convey);
                $this->assign('order_device', $order_device);
                $oCid = Db::name('order_convey')
                    ->where('order_id',$id)
                    ->find();
                $opt = Db::name('order_convey_patient')
                    ->where('order_id',$id)
                    ->find();

                $this->assign('ocid',$oCid);
                $this->assign('opt',$opt);
                $this->assign('ps',empty($opt)?1:0);
                $auths = [1,2,3,4,15,0];
                if(!is_admin($this->userId)){
                    $auth = get_dispatch_auth($this->userId);
                    if($auth){
                        $auths = array_intersect($auths,$auth);
                        if($mode > 0){
                            $auths = array_intersect($auths,[$mode]);
                        }
                    }else{
                        $auths = [];
                    }
                }
                $this->assign('auths',$auths);
                return $this->fetch('yjhj_send');
            }else{
                if ($mode == 1) {
                    $order_type = (new \app\common\model\OrderType())->getList();
                    $address = (new \app\common\model\Address())->getListByType(1);
                    $this->assign('order_type_list', $order_type);
                    $this->assign('address_list', $address);
                    $order_repair = Db::name('order_repair')
                        ->where('order_id', $id)
                        ->find();
                    $this->assign('order_repair', $order_repair);
                }
                $this->assign('send_user_num', $this->model->sendUserNum($mode, $this->orgId));
                $this->assign('user_list', (new \app\common\model\WorkTypeMode())->getRolesUserByNum($mode, $this->orgId, 1));
                $two_dispatch_roles = model('user')->get_two_dispatch_role($this->orgId, $mode);
                $this->assign('dispatch_roles', $two_dispatch_roles);
                $this->assign('dispatch_type', check_two_dispatch($this->userId));
                $this->assign('two_dispatch_off', two_dispatch_off($this->orgId));
                return $this->fetch();
            }

        }
        else {
            $data = request()->post();
            $data['org_id'] = $this->orgId;
            $res = $this->model->send($id, $this->userId, $data);
            if (!$res) {
                $this->error($this->model->getError());
            }
            $this->success('操作成功');
        }
    }
    //转单
    public function zd_send($id, $mode = 1) {
        if (request()->isGet()) {
            $this->assign('id', $id);
            $this->assign('mode', $mode);
            $orders = Db::name('orders')
                ->where('id',$id)
                ->find();

            if($orders['source_type']==4 && $orders['is_deal']==0){//一键呼叫
                $order_type = (new \app\common\model\OrderType())->getList();
                $address = (new \app\common\model\Address())->getListByType(1);
                $this->assign('order_type_list', $order_type);
                $this->assign('address_list', $address);
                $order_repair = Db::name('order_repair')
                    ->where('order_id', $id)
                    ->find();
                $this->assign('order_repair', $order_repair);

                $workType = Db::name('work_type_mode')
                    ->where('type',1)
                    ->select();
                $config = Db::name('config')
                    ->where('name','web_order_transfer_type')
                    ->value('value');
                if(empty($config)){
                    $workType = [];
                }else{
                    $ll = explode('|',$config);
                    foreach ($workType as $kk=>$vv){
                        if(!in_array($vv['id'],$ll)){
                            unset($workType[$kk]);
                        }
                    }
                }
                foreach ($workType as $k=>$v){
                    $this->assign('send_user_num'.$v['id'], $this->model->sendUserNum($v['id'], $this->orgId));
                    $this->assign('user_list'.$v['id'], (new \app\common\model\WorkTypeMode())->getRolesUser($v['id'], $this->orgId, 1));
                    $two_dispatch_roles = model('user')->get_two_dispatch_role($this->orgId, $v['id']);
                    $this->assign('dispatch_roles'.$v['id'], $two_dispatch_roles);
                }

                $this->assign('dispatch_type', check_two_dispatch($this->userId));
                $this->assign('two_dispatch_off', two_dispatch_off($this->orgId));
                $this->assign('workType', $workType);
                $this->assign('orders', $orders);
                $address = (new \app\common\model\Address())->getListByType(2);
                $conveyCate = (new \app\common\model\ConveyCate());
                $priority = $conveyCate->priority;
                $order_convey = $conveyCate->getList();
                $order_device = (new \app\common\model\ConveyDevice())->getList();
                $this->assign('address', $address);
                $this->assign('priority', $priority);
                $this->assign('order_convey_type', $order_convey);
                $this->assign('order_device', $order_device);
                $oCid = Db::name('order_convey')
                    ->where('order_id',$id)
                    ->find();
                $opt = Db::name('order_convey_patient')
                    ->where('order_id',$id)
                    ->find();

                $this->assign('ocid',$oCid);
                $this->assign('opt',$opt);
                $this->assign('ps',empty($opt)?1:0);
                $auths = [1,2,3,4,15,0];
                if(!is_admin($this->userId)){
                    $auth = get_dispatch_auth($this->userId);
                    if($auth){
                        $auths = array_intersect($auths,$auth);
                        if($mode > 0){
                            $auths = array_intersect($auths,[$mode]);
                        }
                    }else{
                        $auths = [];
                    }
                }
                $this->assign('auths',$auths);
                return $this->fetch('yjhj_zd_send');
            }

        }
        else {
            $data = request()->post();
            $data['org_id'] = $this->orgId;
            $res = $this->model->zd_send($id, $data);
            if (!$res) {
                $this->error($this->model->getError());
            }
            $this->success('操作成功');
        }
    }
    //批量派单
    public function batchsend($id, $mode = 1) {
        if (request()->isGet()) {
            $this->assign('id', $id);
            $this->assign('mode', $mode);
            if ($mode == 1) {
                $order_type = (new \app\common\model\OrderType())->getList();
                $address = (new \app\common\model\Address())->getListByType(1);
                $this->assign('order_type_list', $order_type);
                $this->assign('address_list', $address);
                $order_repair = Db::name('order_repair')
                    ->where('order_id', $id)
                    ->find();
                $this->assign('order_repair', $order_repair);
            }
            $user = (new \app\common\model\WorkTypeMode())->getRolesUser($mode, $this->orgId, 1);
            $newUser = [];
            foreach ($user as $k => $v) {
                foreach ($v['user'] as $k1 => $v1) {
                    $newUser[] = $v1;
                }
            }
            foreach ($newUser as $key => $value) {
                $nums = Db::name('todo')
                    ->where(['to_user_id' => $value['id'], 'work_type_mode' => 3])
                    ->where('create_yyyymmdd', date('ymd'))
                    ->where('todo_mode', 'in', [1, 2, 3])
                    ->count();
                $newUser[$key]['nums'] = $nums;
                $addr = Db::name('convey_plan_record')
                    ->alias('cpr')
                    ->join('address ca', 'ca.id = cpr.addr_id')
                    ->field('ca.title,cpr.create_time')
                    ->where('cpr.user_id', $value['id'])
                    ->order('cpr.id desc')
                    ->find();
                $newUser[$key]['title'] = $addr ? $addr['title'] : '';
                $newUser[$key]['addr_time'] = $addr ? $addr['create_time'] : '';
            }
            $this->assign('user_list', $newUser);
            return $this->fetch();
        }
        else {
            $data = request()->post();
            $data['org_id'] = $this->orgId;
            if (empty($data['to_user_id'])) {
                $this->error('请选择执行人');
            }
            $data['to_user_id'] = implode(',', $data['to_user_id']);
            $res = $this->model->batchsend($id, $this->userId, $data);
            if (!$res) {
                $this->error($this->model->getError());
            }
            $this->success('操作成功');
        }
    }
    //完成订单
    public function finish($id) {
        $res = $this->model->finish($id);
        if (!$res) {
            $this->error($this->model->getError());
        }
        $this->success('操作成功');
    }
    //批量完成订单
    public function batchfinish($id) {
        $res = $this->model->batchfinish($id);
        if (!$res) {
            $this->error($this->model->getError());
        }
        $this->success('操作成功');
    }
    //评价
    public function comment() {
        $id = input('id');
        $score = input('score');
        $content = input('content');
        if ($score <= 0 || $score > 5) {
            $this->error('参数错误');
        }
        $res = $this->model->addComment($id, $score, $content, $this->userId, $this->orgId);
        if (!$res) {
            $this->error($this->model->getError());
        }
        $this->success('操作成功');
    }

    public function phone() {
        $phone = input('phone','','trim');
        $fp = input('fp','','trim');
        $id = input('id/d',0,'trim');
        if($phone){
            $fp = $fp?base64_decode($fp):'';
            $md5 = md5($this->orgId.'|'.$fp);
            $ret = Db::name('phone_monitor_record')->where('md5',$md5)->find();
            if(!$ret){
                $id = Db::name('phone_monitor_record')->insertGetId([
                    'org_id' => $this->orgId,
                    'phone' => $phone,
                    'path' => $fp,
                    'md5' => $md5,
                    'create_time' => date('Y-m-d H:i:s')
                ]);
            }else{
                $id = $ret['id'];
            }
        }
        $worktype = [
            ['id' => 1, 'title' => '报修'],
            ['id' => 2, 'title' => '保洁'],
            ['id' => 3, 'title' => '运送'],
            ['id' => 4, 'title' => '应急'],
        ];
        $info = Db::name('phone_monitor_record')->where('id',$id)->find();
        if(!$info){
            halt('数据存储失败');
        }
        $this->assign('worktype', $worktype);
        $this->assign('info', $info);
        $this->assign('id', $id);
        return $this->fetch();
    }

    public function phoneAdd() {
        $id = input('id');
        $worktype = [
            ['id' => 1, 'title' => '报修'],
            ['id' => 2, 'title' => '保洁'],
            ['id' => 3, 'title' => '运送'],
            ['id' => 4, 'title' => '应急'],
        ];
        $info = Db::name('phone_monitor')
            ->where('id', $id)->find();
        if (!$info) {
            echo '负责人不存在', exit();
        }
        $info['real_name'] = Db::name('user')
            ->where('id', $info['user_id'])
            ->value('real_name');
        $info['dep'] = Db::name('user_dep')
            ->alias('a')
            ->join('dep b', 'a.dep_id=b.id')
            ->where('a.user_id', $info['user_id'])
            ->value('b.title');
        $this->assign('worktype', $worktype);
        $this->assign('info', $info);
        $this->assign('id', $id);
        return $this->fetch();
    }
    //运送调度订单列表
    public function convey() {
        $mode = input('mode', 1);
        if (request()->isAjax()) {
            //分页参数
            $length = input('rows', 10, 'intval');   //每页条数
            $page = input('page', 1, 'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx', 'id', 'trim');      //排序列
            $sort = input('sord', 'desc', 'trim');        //排序方式
            $order = $sortRow . ' ' . $sort;
            $content = input('content', '', 'trim');
            if ($content) {
                $map[] = ['o.content', 'like', '%' . $content . '%'];
            }
            $dep_id = input('dep_id', '', 'trim');
            if ($dep_id != '') {
                $map[] = ['o.dep_id', '=', $dep_id];
            }
            $priority = input('priority', '', 'trim');
            if ($priority) {
                $map[] = ['oc.priority', '=', $priority];
            }
            $s = input('start', '', 'trim');
            $end = input('end', '', 'trim');
            if ($s) {
                $map[] = ['oc.start', '=', $start];
            }
            if ($end) {
                $map[] = ['oc.end', '=', $end];
            }
            $type = input('type', '', 'trim');
            if ($type) {
                $map[] = ['oc.type', '=', $type];
            }
            $xqtime = input('xqtime', '', 'trim');
            $ywctime = input('ywctime', '', 'trim');
            if ($xqtime) {
                $xqtimes = explode(' - ', $xqtime);
                $x1 = date('Ymd', strtotime($xqtimes[0]));
                $x2 = date('Ymd', strtotime($xqtimes[1]));
                $map[] = ['oc.xq_time', '>=', $x1];
                $map[] = ['oc.xq_time', '<=', $x2];
            }
            if ($ywctime) {
                $ywctimes = explode(' - ', $ywctime);
                $y1 = date('Ymd', strtotime($ywctimes[0]));
                $y2 = date('Ymd', strtotime($ywctimes[1]));
                $map[] = ['oc.ywc_time', '>=', $y1];
                $map[] = ['oc.ywc_time', '<=', $y2];
            }
            $map[] = ['o.del', '=', 0];
            $map[] = ['o.org_id', '=', $this->orgId];
            $map[] = ['o.work_type_mode', '=', 3];
            $map[] = ['o.order_mode', 'in', [1, 4]];
            $status = input('status', '', 'trim');
            $ysName = input('ysname', '');
            if ($ysName) {
                $orders = Db::name('todo')
                    ->alias('t')
                    ->where('t.org_id', $this->orgId)
                    ->where('t.del', 0)
                    ->where('t.work_type_mode', 3)
                    ->where('t.todo_mode', [1, 2, 4])
                    ->where('u.real_name', 'like', '%' . $ysName . '%')
                    ->join('orders o', 'o.id = t.order_id')
                    ->join('user u', 't.to_user_id = u.id')
                    ->group('o.id')
                    ->column('o.id');
                if ($orders) {
                    $map[] = ['o.id', 'in', $orders];
                }
                else {
                    $map[] = ['o.id', '=', 0];
                }
            }
            $map = empty($map) ? true : $map;
            //数据查询
            $lists = db($this->table)->alias('o')
                ->join('order_convey oc', 'oc.order_id=o.id')
                ->field('o.*,oc.type,oc.start,oc.end,oc.xq_time,oc.ywc_time,oc.device_id,oc.name,oc.phone,oc.priority')
                ->where($map)
                ->order(['o.order_mode' => 'asc', 'oc.xq_time' => 'desc'])
                ->select();
            $newret = [];
            foreach ($lists as $k => $v) {
                $v = $this->model->formatOrder($v);
                $todo = Db::name('todo')
                    ->alias('t')
                    ->where('t.order_id', $v['id'])
                    ->join('user u', 'u.id = t.to_user_id')
                    ->where('t.todo_mode', 'in', [1, 2, 3, 4])
                    ->where('t.del', 0)
                    ->field('u.real_name,t.create_time,t.confirm_time')
                    ->order('t.id asc')
                    ->select();
                $users = [];
                $confirmtime = '';
                foreach ($todo as $kk => $vv) {
                    $users[] = $vv['real_name'];
                    if (!$confirmtime && $vv['confirm_time']) {
                        $confirmtime = $vv['confirm_time'];
                    }
                    else {
                        if ($confirmtime && $vv['confirm_time'] && $vv['confirm_time'] < $confirmtime) {
                            $confirmtime = $vv['confirm_time'];
                        }
                    }
                }
                $v['real_names'] = implode(',', $users);
                $v['confirm_time'] = $confirmtime;
                $last = strtotime($v['ywc_time']) - time();
                $v['last_time'] = $last > 0 ? round($last / 60) : 0;
                //是否有延时
                $v['delay'] = 0; // 0=未延迟 1=延迟
                $v['delay_diff'] = 0;
                $v['delay_reason'] = '';
                $delays = Db::name('order_delay')
                    ->where('order_id', $v['id'])
                    ->select();
                $delays = $delays ? $delays : [];
                foreach ($delays as $vv) {
                    if ($vv['status'] == 0) {
                        $v['delay'] = 1;
                        $v['delay_reason'] = $this->gettablefield('delay_reason', ['id' => $vv['delay_reason_id']], 'title');
                        $vv['diff'] = time() - strtotime($vv['start_time']);
                    }
                    $v['delay_diff'] += $vv['diff'];
                }
                $v['delay_diff'] = round($v['delay_diff'] / 60);
                if ($v['delay'] == 1) {
                    $v['status'] = 3;
                } else {
                    if ($v['order_mode'] == 1) {
                        $v['status'] = 1;
                    } else {
                        $v['status'] = 2;
                    }
                }
                $convey = Db::name('convey_cate')
                    ->alias('oc')
                    ->join('time ot', 'ot.id = oc.time_id')
                    ->where('oc.id', $v['type'])
                    ->field('ot.*')
                    ->find();
                $createtime = strtotime($v['create_time']);
                $curtime = time();
                $ct = round(($curtime - $createtime) / 60);
                if ($ct < $convey['yy_time']) {
                    $ss = 0;
                }
                else {
                    if ($ct >= $convey['yy_time'] && $ct < $convey['bz_time']) {
                        $ss = 1;
                    }
                    else {
                        if ($ct >= $convey['bz_time'] && $ct < $convey['jg_time']) {
                            $ss = 2;
                        }
                        else {
                            if ($ct >= $convey['jg_time'] && $ct < $convey['wjjg_time']) {
                                $ss = 3;
                            }
                            else {
                                $ss = 4;
                            }
                        }
                    }
                }
                $v['ss'] = $ss;
                $v['xtime'] = date('H:i', strtotime($v['xq_time']));
                $v['stime'] = $v['send_time'] ? date('H:i', strtotime($v['send_time'])) : "";
                $v['ctime'] = $v['confirm_time'] ? date('H:i', strtotime($v['confirm_time'])) : "";
                $v['priorityName'] = isset($this->model->priority[$v['priority']])?$this->model->priority[$v['priority']]:'';
                if ($status == 3 && $v['delay'] == 1) { //延时任务
                    $newret[] = $v;
                }
                if ($status == 1 && $v['order_mode'] == 1) { //新任务
                    $newret[] = $v;
                }
                if ($status == 2 && $v['order_mode'] == 4) { // 进行中
                    $newret[] = $v;
                }
                if (!$status || !in_array($status, [1, 2, 3])) {
                    $newret[] = $v;
                }
                $lists[$k] = $v;
            }
            if(!empty($newret)){
                $newret = arraySequence($newret,'status');//返回数组中指定的一列
            }

            //数据返回
            $totalCount = count($lists);
            $totalPage = ceil($totalCount / $length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $newret;
            return json($result);
        }
        else {
            $mode_name = $this->getTableField('work_type_mode', ['id' => $mode], 'name');
            $order_type = (new \app\common\model\ConveyCate())->getList();
            $order_mode = Db::name('order_mode')
                ->select();
            $this->assign('order_type_list', $order_type);
            $this->assign('m_name', $mode_name);
            $this->assign('mode', $mode);
            $this->assign('order_mode_list', $order_mode);
            $this->assign('dispatch_type', check_two_dispatch($this->userId));
            $address = (new \app\common\model\Address())->getListByType(2);
            $this->assign('address', $address);
            $count = Db::name('todo')
                ->where('org_id', $this->orgId)
                ->where('del', 0)
                ->where('work_type_mode', 3)
                ->where('todo_mode', 4)
                ->count();
            $this->assign('count', $count);
            $info = Db::name('config')->where('name','org_order_refresh')
                ->find();
            $orgConfig = Db::name('config_org')
                ->where('config_id',$info['id'])
                ->where('org_id',$this->orgId)
                ->find();
            $value = $orgConfig?$orgConfig['value']:0;
            $this->assign('refresh',$value);
            return $this->fetch();
        }
    }
    //运送员状态
    public function conveystatus($id='') {
        if (request()->isAjax()) {
            //分页参数
            $length = input('rows', 10, 'intval');   //每页条数
            $page = input('page', 1, 'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx', 'id', 'trim');      //排序列
            $sort = input('sord', 'desc', 'trim');        //排序方式
            $order = $sortRow . ' ' . $sort;
            $real_name = input('real_name', '');

            $map8 = [];
            if ($real_name) {
                $map8[] = ['real_name', 'like', '%'.$real_name.'%'];
            }

            $user = (new \app\common\model\WorkTypeMode())->getRolesUser(3, $this->orgId);
            $newUser = [];
            foreach ($user as $k => $v) {
                foreach ($v['user'] as $k1 => $v1) {
                    $newUser[] = $v1['id'];
                }
            }

            $userIds1 = [];
            if($id){
                $ids = explode(',', $id);
                $map[] = ['order_id', 'in', $ids];
                $map[] = ['del', '=', 0];
                $map[] = ['org_id', '=', $this->orgId];
                $map[] = ['work_type_mode', '=', 3];
                $userIds = Db::name('todo')->where($map)->column('to_user_id');
                $userIds1 = $userIds?$userIds:[];
                $newUser = array_intersect($userIds1,$newUser);
            }

            if(empty($newUser)){
                $map8[] = ['id','=',0];
            }else{
                $map8[] = ['id','in',$newUser];
            }

            $lists = db('user')
                ->where($map8)->limit($start, $length)
                ->order($order)->select();


            foreach ($lists as $key => $value) {
                $nums = Db::name('todo')
                    ->where(['to_user_id' => $value['id'], 'work_type_mode' => 3])
                    ->where('create_yyyymmdd', date('ymd'))
                    ->where('todo_mode', 'in', [1, 2, 3])
                    ->count();
                $lists[$key]['nums'] = $nums;
                $addr = Db::name('convey_plan_record')
                    ->alias('cpr')
                    ->join('address ca', 'ca.id = cpr.addr_id')
                    ->field('ca.title,cpr.create_time')
                    ->where('cpr.user_id', $value['id'])
                    ->order('cpr.id desc')
                    ->find();
                $lists[$key]['title'] = $addr ? $addr['title'] : '';
                $lists[$key]['addr_time'] = $addr ? $addr['create_time'] : '';
                $lists[$key]['worktxt'] = $value['work'] == 1 ? '上班' : '下班';
                $lists[$key]['stationtxt'] = $value['station'] == 1 ? '驻守' : '取消驻守';
            }
            //数据返回
//            $totalCount = db('user')
//                ->where($map1)->count();
            $totalCount = db('user')
                ->where($map8)->count();
            $totalPage = ceil($totalCount / $length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }
        else {
            $this->assign('id', $id);
            return $this->fetch();
        }
    }
    //上下班
    public function work($id) {
        $user = Db::name('user')
            ->where('id', $id)
            ->find();
        $value = $user['work'] == 1 ? 0 : 1;
        $res = Db::name('user')
            ->where('id', $id)
            ->update(['work' => $value, 'update_time' => getTime()]);
        $res ? $this->success('操作成功') : $this->error('操作失败');
    }
    //驻守
    public function station($id) {
        $user = Db::name('user')
            ->where('id', $id)
            ->find();
        $value = $user['station'] == 1 ? 0 : 1;
        $res = Db::name('user')
            ->where('id', $id)
            ->update(['station' => $value, 'update_time' => getTime()]);
        $res ? $this->success('操作成功') : $this->error('操作失败');
    }
    //驳回工单列表
    public function bhTodoList() {
        if (request()->isAjax()) {
            $length = input('rows', 10, 'intval');   //每页条数
            $page = input('page', 1, 'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            $map[] = ['todo.org_id', '=', $this->orgId];
            $map[] = ['todo.del', '=', 0];
            $map[] = ['todo.todo_mode', '=', 4];
            $map[] = ['todo.work_type_mode', '=', 3];
            $totalCount = Db::name('todo')
                ->alias('todo')
                ->join('orders orders', 'orders.id = todo.order_id')
                ->join('order_convey oc', 'oc.order_id = orders.id')
                ->join('user u', 'u.id = todo.to_user_id')
                ->where($map)
                ->count();
            $totalPage = ceil($totalCount / $length);
            $ret = Db::name('todo')
                ->alias('todo')
                ->join('orders orders', 'orders.id = todo.order_id')
                ->join('order_convey oc', 'oc.order_id = orders.id')
                ->join('user u', 'u.id = todo.to_user_id')
                ->field('orders.*,u.real_name as to_real_name,oc.type,oc.start,oc.end,oc.xq_time,oc.ywc_time,oc.device_id,oc.name,oc.phone,oc.priority,todo.nodo_reason,todo.id,todo.reject_time')
                ->order('oc.xq_time', 'desc')
                ->where($map)
                ->limit($start, $length)
                ->select();
            foreach ($ret as $k => $v) {
                $ret[$k]['start_name'] = $this->gettablefield('address', array('id' => $v['start']), 'title');
                $ret[$k]['end_name'] = $this->gettablefield('address', array('id' => $v['end']), 'title');
                $ret[$k]['type_name'] = $this->gettablefield('convey_cate', array('id' => $v['type']), 'title');
                $ret[$k]['real_name'] = $this->gettablefield('user', array('id' => $v['user_id']), 'real_name');
                $ret[$k]['device_name'] = '';
                if ($v['device_id'] > 0) {
                    $ret[$k]['device_name'] = $this->gettablefield('convey_device', array('id' => $v['device_id']), 'title');
                }
                $last = strtotime($v['ywc_time']) - time();
                $ret[$k]['last_time'] = $last > 0 ? round($last / 60) : 0;
                $ret[$k]['reject_time'] = $v['reject_time'] ? date('Y-m-d h:i', strtotime($v['reject_time'])) : '';
            }
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $ret;
            return json($result);
        }
        else {
            return $this->fetch();
        }
    }
    //excel导出
    public function export($mode) {
        set_time_limit(0);
        ini_set("memory_limit", "1024M");
        $meta_title = '订单列表';
        if ($mode == 1) {
            $meta_title = '报修' . $meta_title;
        }
        elseif ($mode == 2) {
            $meta_title = '保洁' . $meta_title;
        }
        elseif ($mode == 3) {
            $meta_title = '运送' . $meta_title;
        }
        elseif ($mode == 4) {
            $meta_title = '应急' . $meta_title;
        }
        elseif ($mode == 15) {
            $meta_title = '品质整改' . $meta_title;
        }elseif ($mode == -1) {
            $meta_title = '一键呼叫' . $meta_title;
        }
        $level1 = check_is_dispatch($this->userId);
        $level2 = check_two_dispatch($this->userId);
        $turnoff = two_dispatch_off($this->orgId);
        $quality_type = input('quality_type','');

        if (request()->isGet()) {
            //排序
            $sortRow = input('sidx', 'id', 'trim');      //排序列
            $sort = input('sord', 'desc', 'trim');        //排序方式
            $order = $sortRow . ' ' . $sort;
            $content = input('content', '', 'trim');
            if ($content) {
                $map[] = ['content', 'like', '%' . $content . '%'];
            }
            $dep_id = input('dep_id', '', 'trim');
            if ($dep_id != '') {
                $map[] = ['dep_id', '=', $dep_id];
            }
            $order_mode = input('order_mode', '', 'trim');
            $map6 = [];
            if ($order_mode != '') {
                if($level1 && $turnoff && $mode != 15){ // 一级调度且二级调度开关开着,品质整改例外
                    if ($order_mode == 1) {
                        $map[] = ['is_deal', '=', 0];
                    }else if ($order_mode == 4) {
                        $map6[] = ['is_deal', '=', 1];
                    }
                }
                if($order_mode==100){//已挂起
                    $gq = Db::name('todo')
                        ->where('work_type_mode',1)
                        ->where('todo_mode',2)
                        ->where('pause',1)
                        ->column('order_id');
                    if(empty($gq)){
                        $map[] = ['id', '=', -1];
                    }else{
                        $map[] = ['id', 'in', $gq];
                    }
                }else{
                    $map[] = ['order_mode', '=', $order_mode];
                }
            }
            $b = input('start', '', 'trim');
            $e = input('end', '', 'trim');
            if ($b) {
                $b = date('Ymd', strtotime($b));
                $map[] = ['create_yyyymmdd', '>=', $b];
            }
            if ($e) {
                $e = date('Ymd', strtotime($e));
                $map[] = ['create_yyyymmdd', '<=', $e];
            }
            $map[] = ['del', '=', 0];
            $map[] = ['org_id', '=', $this->orgId];
            if($mode==-1){
                $map[] = ['source_type', '=', 4];
            }
            $type = input('type', '', 'trim');
            $oids = [];
            if ($type != '') {
                $map1[] = ['parent_id', '=', $type];
                $type_id = Db::name('order_type')
                    ->where($map1)
                    ->where('org_id', $this->orgId)
                    ->where('enable', 1)
                    ->column('id');
                if (!empty($type_id)) {
                    $map3[] = ['type_id', 'in', $type_id];
                    $ids = Db::name('order_repair')
                        ->where($map3)
                        ->column('order_id');
                    if (!empty($ids)) {
                        $oids = $ids;
                    }
                    else {
                        $oids = [];
                    }
                }
                else {
                    $oids = [];
                }
            }

            if($level2 && $turnoff){ // 二级调度
                $roles_id = Db::name('user_roles')
                    ->where('user_id', $this->userId)
                    ->value('roles_id');
                $ids = Db::name('dispatch_log')
                    ->where('roles_id', $roles_id)
                    ->whereOr('to_user_id', $this->userId)
                    ->column('order_id');
                if (empty($ids)) {
                    $map[] = ['id', '=', -1];
                } else {
                    if($type != ''){
                        $oids = array_intersect($oids,$ids);
                        if($oids){
                            $map[] = ['id', 'in', $oids];
                        }else{
                            $map[] = ['id', '=', -1];
                        }
                    }else{
                        $map[] = ['id', 'in', $ids];

                    }
                }
            }else{
                if($type != ''){
                    if($oids){
                        $map[] = ['id', 'in', $oids];
                    }else{
                        $map[] = ['id', '=', 0];
                    }
                }
            }

            if($mode == 15){ // 品质检查,单独处理
                $map[] = ['work_type_mode','=',$mode];
                if($quality_type !=''){
                    $map[] = ['quality_type','=',$quality_type];
                }
            }else{
                $work_type_mode = input('work_type_mode','','trim');
                if(!is_admin($this->userId)){
                    $auth = get_dispatch_auth($this->userId);
                    if($auth){
                        $map[] = ['work_type_mode', 'in', $auth];
                        if($mode > 0){
                            $map[] = ['work_type_mode', '=', $mode];
                        }else{
                            if($work_type_mode!=''){
                                $map[] = ['work_type_mode','=',$work_type_mode];
                            }
                        }
                    }else{
                        $map[] = ['work_type_mode', '=', -1];
                    }
                }else{
                    if($mode > 0){
                        $map[] = ['work_type_mode', '=', $mode];
                    }else{
                        if($work_type_mode!=''){
                            $map[] = ['work_type_mode','=',$work_type_mode];
                        }
                    }
                }
            }
            $sn = input('sn', '', 'trim');
            if ($sn) {
                $map[] = ['sn', 'like', '%' . $sn . '%'];
            }
            $from = input('from', '', 'trim');
            if ($from) {
                if($from >3){
                    $map[] = ['from','=',0];
                    $map[] = ['work_type_mode','=',$from-3];
                }else{
                    $map[] = ['from','=',$from];
                }
            }
            $dep_cate = input('dep_cate', '', 'trim');
            if ($dep_cate != '') {
                $depIds = Db::name('dep')
                    ->where('org_id',$this->orgId)
                    ->where('cate_id',$dep_cate)
                    ->where('del',0)
                    ->column('id');
                if(!empty($depIds)){
                    $map[] = ['dep_id', 'in', $depIds];
                }else{
                    $map[] = ['dep_id', '=', -1];

                }
            }
            $map = empty($map) ? true : $map;
            //数据查询
            $lists = db($this->table)->where($map)
                ->whereOr($map6)
                ->order($order)->select();
            foreach ($lists as $k => $v) {
                $lists[$k] = $this->model->newFormatOrder($v);
                if ($turnoff && $level1 && $v['order_mode'] == 1 && $v['is_deal'] == 1) {
                    $lists[$k]['order_mode_text'] = '已派发';
                }
            }
            include_once env('root_path') . '/extend/phpexcel/Classes/PHPExcel.php';
            //实例化PHPExcel类
            $objPHPExcel = new \PHPExcel();
            //激活当前的sheet表
            $objPHPExcel->setActiveSheetIndex(0);
            //设置表格头(即excel表格的第一行)
            if ($mode == 1) {
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A1', '编号')
                    ->setCellValue('B1', '申请时间')
                    ->setCellValue('C1', '内容')
                    ->setCellValue('D1', '所在科室/部门')
                    ->setCellValue('E1', '报修类型')
                    ->setCellValue('F1', '状态')
                    ->setCellValue('G1', '紧急程度')
                    ->setCellValue('H1', '来源')
                    ->setCellValue('I1', '部门分类');
            }
            else {
                if ($mode == 3) {
                    $objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue('A1', '编号')
                        ->setCellValue('B1', '申请时间')
                        ->setCellValue('C1', '始发大厅')
                        ->setCellValue('D1', '内容')
                        ->setCellValue('E1', '所在科室/部门')
                        ->setCellValue('F1', '状态')
                        ->setCellValue('G1', '来源')
                        ->setCellValue('H1', '部门分类');
                }
                else {
                    if($mode==0){
                        $objPHPExcel->setActiveSheetIndex(0)
                            ->setCellValue('A1', '编号')
                            ->setCellValue('B1', '申请时间')
                            ->setCellValue('C1', '内容')
                            ->setCellValue('D1', '所在科室/部门')
                            ->setCellValue('E1', '状态')
                            ->setCellValue('F1', '订单类型')
                            ->setCellValue('G1', '来源')
                            ->setCellValue('H1', '部门分类');
                    }else{

                        if($mode==15){
                            $objPHPExcel->setActiveSheetIndex(0)
                                ->setCellValue('A1', '编号')
                                ->setCellValue('B1', '申请时间')
                                ->setCellValue('C1', '内容')
                                ->setCellValue('D1', '所在科室/部门')
                                ->setCellValue('E1', '状态')
                                ->setCellValue('F1', '来源')
                                ->setCellValue('G1', '部门分类')
                                ->setCellValue('H1', '整改分类');
                        }else{
                            $objPHPExcel->setActiveSheetIndex(0)
                                ->setCellValue('A1', '编号')
                                ->setCellValue('B1', '申请时间')
                                ->setCellValue('C1', '内容')
                                ->setCellValue('D1', '所在科室/部门')
                                ->setCellValue('E1', '状态')
                                ->setCellValue('F1', '来源')
                                ->setCellValue('G1', '部门分类');
                        }
                    }

                }
            }
            // 设置表格头水平居中
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('B1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('C1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('D1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('E1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('F1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('G1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('H1')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //设置列水平居中
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('A')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('B')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('C')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('D')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('E')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('F')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('G')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('H')->getAlignment()
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //设置单元格宽度
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(10);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(50);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(20);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(20);
            //循环刚取出来的数组,将数据逐一添加到excel表格。
            if ($mode == 1) {
                for ($i = 0; $i < count($lists); $i++) {
                    $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $lists[$i]['sn']);
                    $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $lists[$i]['create_time']);
                    $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $lists[$i]['content']);
                    $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $lists[$i]['dep']);
                    $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $lists[$i]['order_type']);
                    $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $lists[$i]['order_mode_text']);
                    $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $lists[$i]['repair_priority']);
                    $objPHPExcel->getActiveSheet()->setCellValue('H' . ($i + 2), $lists[$i]['source_type_text']);
                    $objPHPExcel->getActiveSheet()->setCellValue('I' . ($i + 2), $lists[$i]['dep_cate_name']);
                }
            }
            else {
                if ($mode == 3) {
                    for ($i = 0; $i < count($lists); $i++) {
                        $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $lists[$i]['sn']);
                        $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $lists[$i]['create_time']);
                        $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $lists[$i]['start_name']);
                        $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $lists[$i]['content']);
                        $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $lists[$i]['dep']);
                        $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $lists[$i]['order_mode_text']);
                        $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $lists[$i]['source_type_text']);
                        $objPHPExcel->getActiveSheet()->setCellValue('H' . ($i + 2), $lists[$i]['dep_cate_name']);

                    }
                }
                else {
                    if($mode==0){
                        for ($i = 0; $i < count($lists); $i++) {
                            $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $lists[$i]['sn']);
                            $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $lists[$i]['create_time']);
                            $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $lists[$i]['content']);
                            $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $lists[$i]['dep']);
                            $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $lists[$i]['order_mode_text']);
                            $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $lists[$i]['work_type_mode_text']);
                            $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $lists[$i]['source_type_text']);
                            $objPHPExcel->getActiveSheet()->setCellValue('H' . ($i + 2), $lists[$i]['dep_cate_name']);

                        }
                    }else{
                        if($mode==15){
                            for ($i = 0; $i < count($lists); $i++) {
                                $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $lists[$i]['sn']);
                                $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $lists[$i]['create_time']);
                                $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $lists[$i]['content']);
                                $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $lists[$i]['dep']);
                                $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $lists[$i]['order_mode_text']);
                                $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $lists[$i]['source_type_text']);
                                $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $lists[$i]['dep_cate_name']);
                                $objPHPExcel->getActiveSheet()->setCellValue('H' . ($i + 2), $lists[$i]['quality_cate_name']);

                            }
                        }else{
                            for ($i = 0; $i < count($lists); $i++) {
                                $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $lists[$i]['sn']);
                                $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $lists[$i]['create_time']);
                                $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $lists[$i]['content']);
                                $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $lists[$i]['dep']);
                                $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $lists[$i]['order_mode_text']);
                                $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $lists[$i]['source_type_text']);
                                $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $lists[$i]['dep_cate_name']);

                            }
                        }

                    }
                }
            }
            //设置保存的Excel表格名称
            $filename = $meta_title . '_' . date('YmdHis', time()) . '.xls';
            //设置当前激活的sheet表格名称
            $objPHPExcel->getActiveSheet()->setTitle($meta_title);
            //设置浏览器窗口下载表格
            ob_end_clean();
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
            header('Content-Disposition:inline;filename="' . $filename);
            //生成excel文件
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            //下载文件在浏览器窗口
            return $objWriter->save('php://output');
        }
    }

    public function rejectTodoList(){
        $orderId = input('orderId',0);
        if (request()->isAjax()) {
            $length = input('rows', 10, 'intval');   //每页条数
            $page = input('page', 1, 'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置

            $map[] = ['org_id','=',$this->orgId];
            $map[] = ['del','=',0];
            $map[] = ['todo_mode','=',4];
            $map[] = ['order_id','=',$orderId];
            $lists = Db::name('todo')
                ->where($map)
                ->limit($start,$length)
                ->order('id desc')
                ->select();
            $workTypeMode = [
                '0'=>'一键呼叫',
                '1'=>'报修',
                '2'=>'保洁',
                '3'=>'运送',
                '4'=>'应急',
            ];
            foreach ($lists as $k=>$v){
                $lists[$k]['to_user_name'] = Db::name('user')->where('id',$v['to_user_id'])->value('real_name');
                $lists[$k]['work_type_mode_text'] = $workTypeMode[$v['work_type_mode']];
                $lists[$k]['todo_mode_in_content'] = Db::name('todo_mode')->where('id',$v['todo_mode'])->value('in_content');
                $lists[$k]['todo_mode_color'] = Db::name('todo_mode')->where('id',$v['todo_mode'])->value('color');
            }

            $totalCount = Db::name('todo')
                ->where($map)
                ->count();
            $totalPage = ceil($totalCount / $length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }
        else {
            $this->assign('orderId',$orderId);
            return $this->fetch();
        }
    }

    public function orderRefreshOff(){
        $info = Db::name('config')->where('name','org_order_refresh')
            ->find();
        $orgConfig = Db::name('config_org')
            ->where('config_id',$info['id'])
            ->where('org_id',$this->orgId)
            ->find();
        if($orgConfig){
            $value = $orgConfig['value']==1?0:1;
            $res = Db::name('config_org')
                ->where('config_id',$info['id'])
                ->where('org_id',$this->orgId)
                ->update(['value'=>$value]);
        }else{
            $value = 1;
            $res = Db::name('config_org')
                ->insertGetId([
                    'config_id'=>$info['id'],
                    'org_id'=>$this->orgId,
                    'value'=>$value,
                ]);
        }
        $res?$this->success('操作成功','',['status'=>$value]):$this->error('操作失败');
    }

    public function print1($id){

        $order = Db::name('orders')->where(['id' => $id])->find();

        $depName = Db::name('dep')
            ->where('id',$order['dep_id'])
            ->value('title');
        $info['depName'] = $depName;
        $info['create_time'] = $order['create_time'];
        $users = Db::name('todo')
            ->alias('t')
            ->join('user u','u.id=t.to_user_id')
            ->where('t.order_id',$order['id'])
            ->column('u.real_name');

        $info['users'] = $users?implode(',',$users):'';
        $info['content'] = $order['content'];
        $info['cons'] = [];

        $tList = Db::name('todo')
            ->where('order_id',$order['id'])
            ->select();
        $total = $totalPrice = 0;
        $signs = [];
        foreach ($tList as $k=>$v){
            if($v['sign']){
                $signs[] = $v['sign'];
            }
            $mate = Db::name('todo_mate_item')
                ->alias('tmi')
                ->join('todo_mate tm','tmi.todo_mate_id = tm.id')
                ->join('mate_goods mg','mg.id = tmi.items_id')
                ->field('tmi.items_id,tmi.total,tmi.money,tmi.total_money,mg.title')
                ->where('tm.todo_id',$v['id'])
                ->select();
            if(!empty($mate)){

                foreach ($mate as $kk=>$todo_mate){
                    $info['cons'][] = [
                        'title' =>$todo_mate['title'],
                        'total' =>$todo_mate['total'],
                        'money' =>$todo_mate['money'],
                        'total_money' =>$todo_mate['total_money'],
                    ];
                    $total +=$todo_mate['total'];
                    $totalPrice +=$todo_mate['total_money'];
                }

            }
        }

        $aa = [
            'title'=>'',
            'total'=>'',
            'money'=>'',
            'total_money'=>'',
        ];
        if(empty($info['cons'])){
            for ($i=1;$i<=4;$i++){
                $info['cons'][] = $aa;
            }
        }elseif (count($info['cons']) <4){
            $ii = 4-count($info['cons']);
            for ($i=1;$i<=$ii;$i++){
                $info['cons'][] = $aa;
            }
        }

        $info['total'] = $total;
        $info['totalPrice'] = round($totalPrice,2);

        $info['signs'] = $signs;

        $this->assign('info', $info);
        return $this->fetch();
    }


    public function withdraw(){
        $id = input('id');

        $info = Db::name('orders')
            ->where('id',$id)
            ->where('del',0)
            ->where('order_mode',4)
            ->find();
        if(!$info){
            $this->error('参数错误');
        }

        $saveOrder = Db::name('orders')
            ->where('id',$id)
            ->update(['order_mode'=>1,'withdraw_time'=>getTime()]);

        $saveTodo = Db::name('todo')
            ->where('order_id',$id)
            ->update(['del'=>1]);

        $todoIds = Db::name('todo')
            ->where('order_id',$id)
            ->where('todo_mode',1)
            ->column('id');

        $task = Db::name('task')
            ->where('type',1)
            ->whereIn('bus_id',$todoIds)
            ->delete();

        if(!$saveOrder){
            $this->error('操作失败');
        }

        $this->success('操作成功');

    }


    public function autoSend($id,$form=0) {
        if(request()->isGet() && $form==0){
            $order_type = (new \app\common\model\OrderType())->getList();
            $order_repair = Db::name('order_repair')
                ->where('order_id', $id)
                ->find();
            $this->assign('order_repair', $order_repair);
            $this->assign('order_type_list',$order_type);
            $this->assign('id',$id);
            return $this->fetch();
        }else{
            $type_id = input('type_id/d','');
            if(!empty($type_id)){
                $old = Db::name('order_repair')
                    ->where('order_id', $id)
                    ->find();
                $rData['type_id'] = $type_id;
                if ($old) {
                    $rData['update_time'] = getTime();
                    Db::name('order_repair')
                        ->where('order_id', $id)
                        ->update($rData);
                }
                else {
                    $rData['order_id'] = $id;
                    Db::name('order_repair')
                        ->insert($rData);
                }
            }
            $res = $this->model->autoSend($id);
            if (!$res) {
                $this->error($this->model->getError());
            }
            $this->success('操作成功');
        }

    }

    public function setType($id) {
        if(request()->isGet()){
            $order_type = (new \app\common\model\OrderType())->getList();
            $order_repair = Db::name('order_repair')
                ->where('order_id', $id)
                ->find();
            $this->assign('order_repair', $order_repair);
            $this->assign('order_type_list',$order_type);
            $this->assign('id',$id);
            return $this->fetch();
        }else{
            $type_id = input('type_id/d','');
            if(empty($type_id)){
                $this->error('请选择报修事项');
            }
            $old = Db::name('order_repair')
                ->where('order_id', $id)
                ->find();
            $rData['type_id'] = $type_id;
            if ($old) {
                $rData['update_time'] = getTime();
                $r = Db::name('order_repair')
                    ->where('order_id', $id)
                    ->update($rData);
            }
            else {
                $rData['order_id'] = $id;
                $r =  Db::name('order_repair')
                    ->insert($rData);
            }

            $r?$this->success('操作成功'):$this->error('操作失败');
        }

    }

}