<?php
namespace app\admin\controller;

use app\common\model\Config;
use think\Db;

class Index extends Auth
{

    public function index(){
//        $menus = model('Menu')->getMenuTree($this->rolesId,$this->orgId);
//        $this->assign('menus',$menus);

        $bd = Db::name('org')->where('id',$this->orgId)->value('bd_auth');

        $bdAuth = $bd?explode(',',$bd):[];

        $mapMenu[] = ['enable','=',1];
        $mapMenu[] = ['del','=',0];
        $mapMenu[] = ['is_btn','=',0];
        if($bdAuth){
            $mapMenu[] = ['id','in',$bdAuth];
        }else{
            $mapMenu[] = ['id','in',[148,149,150,151,257]];
        }

        $lists = Db::name('menu')
            ->where($mapMenu)
            ->field('id,title,url,icons,pid')
            ->order('sort asc,id asc')
            ->select();
        $lists = $lists?$lists:[];

        $arr = [];
        foreach ($lists as $k=>$v){
            $v['url'] = model('Menu')->getNavUrl($v['url']);
            $arr[] = $v;
        }

        $curUrl = isset($lists[0])?$lists[0]['url']:'';

        $this->assign('menus',$arr);

        $this->assign('curUrl',$curUrl);

        $userInfo = Db::name('user')
            ->where('id',$this->userId)
            ->find();
        $this->assign('userInfo',$userInfo);

        // 判断用户是否有派单权限
        $isDispatch = 0;

        if(get_dispatch_auth($this->userId)){
            $isDispatch = 1;
        }
        $this->assign('isDispatch',$isDispatch);


        $map[] = ['org_id','=',$this->orgId];
        $map[] = ['del','=',0];
        $map[] = ['order_mode','=',1];

        if(!is_admin($this->userId)){
            $auth = get_dispatch_auth($this->userId);
            if($auth){
                $map[] = ['work_type_mode', 'in', $auth];
                $where[] = ['o.work_type_mode', 'in', $auth];
            }else{
                $map[] = ['work_type_mode', '=', -1];
                $where[] = ['o.work_type_mode', '=', -1];
            }
        }
        $order = Db::name('orders')->where($map)->count();

        //$驳回的订单
        $where[] = ['o.del','=',0];
        $where[] = ['t.del','=',0];
        $bh = Db::name('orders')
            ->alias('o')
            ->join('todo t','t.order_id=o.id')
            ->where('t.todo_mode',4)
            ->where('t.org_id',$this->orgId)
            ->where('o.order_mode',4)
            ->where('o.org_id',$this->orgId)
            ->where($where)
            ->group('o.id')
            ->count();

        $order = $order + $bh;




        $complainCount = Db::name('complain')->where('del',0)->where('org_id',$this->orgId)->where('status',0)->where('order_id',0)->count();
        $hiddendangerCount = Db::name('hiddendanger')->where('del',0)->where('org_id',$this->orgId)->where('status',0)->where('order_id',0)->count();
        $endCount = $order+$complainCount+$hiddendangerCount;

        $this->assign('orderNums',$endCount);

        return $this->fetch();
    }

    public function ocount(){
        $map[] = ['org_id','=',$this->orgId];
        $map[] = ['del','=',0];
        $map[] = ['order_mode','=',1];

        $order = 0;
        $auth = get_dispatch_auth($this->userId);

        if(!is_admin($this->userId)){
//            if(!is_admin($this->userId)){
//                $auth = get_dispatch_auth($this->userId);
//                if($auth){
//                    $map[] = ['work_type_mode', 'in', $auth];
//                    $where[] = ['o.work_type_mode', 'in', $auth];
//                }else{
//                    $map[] = ['work_type_mode', '=', -1];
//                    $where[] = ['work_type_mode', '=', -1];
//                }
//            }
            if($auth){
                $map[] = ['work_type_mode', 'in', $auth];
                $where[] = ['o.work_type_mode', 'in', $auth];
            }else{
                $map[] = ['work_type_mode', '=', -1];
                $where[] = ['work_type_mode', '=', -1];
            }
            $order = Db::name('orders')->where($map)->count();

            //$驳回的订单
            $where[] = ['o.del','=',0];
            $where[] = ['t.del','=',0];
            $bh = Db::name('orders')
                ->alias('o')
                ->join('todo t','t.order_id=o.id')
                ->where('t.todo_mode',4)
                ->where('t.org_id',$this->orgId)
                ->where('o.order_mode',4)
                ->where('o.org_id',$this->orgId)
                ->where($where)
                ->group('o.id')
                ->count();

            $order = $order + $bh;

        }






        $complainCount = Db::name('complain')->where('del',0)->where('org_id',$this->orgId)->where('status',0)->where('order_id',0)->count();
        $hiddendangerCount = Db::name('hiddendanger')->where('del',0)->where('org_id',$this->orgId)->where('status',0)->where('order_id',0)->count();
        $endCount = $order+$complainCount+$hiddendangerCount;

        $this->success('成功','',['count'=>$endCount]);
    }

    public function def(){
        // APP下载二维码
        $download = think_encrypt(url('h5/Index/download','',true,true));
        $this->assign('download',$download);
        // 小程序二维码
        $wxcode = Db::name('org')->where('id',$this->orgId)->value('wxqrcode');
        $this->assign('wxcode',$wxcode);
        // 陪护h5
        $phcode = think_encrypt(config("app.app_host").config('app.ph_url').'?orgId='.$this->orgId);
        $this->assign('phcode',$phcode);
        // 点餐h5
        $shopcode = think_encrypt(config('app.shop_url').'?orgId='.$this->orgId);
        $this->assign('shopcode',$shopcode);

        // 商城h5
        $xshopcode = think_encrypt(config('app.xshop_url').'?orgId='.$this->orgId);
        $this->assign('xshopcode',$xshopcode);

        //本月
        $month = date('Y-m');
        $sMonth = $month.'-1 00:00:00';
        $eMonth = $month.'31 23:59:59';

        //上月
        $tmp_year=substr($month,0,4);
        //切割出月份
        $tmp_mon =substr($month,5,2);

        $tmp_forwardmonth=mktime(0,0,0,$tmp_mon-1,1,$tmp_year);
        $lastMonth=date("Y-m",$tmp_forwardmonth);

        $sLastMonth = $lastMonth.'-1 00:00:00';
        $eLastMonth = $lastMonth.'31 23:59:59';

        $userNums = Db::name('user')
            ->alias('u')
            ->join('user_org uo','uo.user_id=u.id')
            ->where('uo.org_id',$this->orgId)
            ->where('u.del',0)
            ->where('u.enable',1)
            ->count();

        $monthUserNums = Db::name('user')
            ->alias('u')
            ->join('user_org uo','uo.user_id=u.id')
            ->where('uo.org_id',$this->orgId)
            ->where('u.del',0)
            ->where('u.enable',1)
            ->where('u.create_time','>=',$sMonth)
            ->where('u.create_time','<=',$eMonth)
            ->count();
        $lastMonthUserNums = Db::name('user')
            ->alias('u')
            ->join('user_org uo','uo.user_id=u.id')
            ->where('uo.org_id',$this->orgId)
            ->where('u.del',0)
            ->where('u.enable',1)
            ->where('u.create_time','>=',$sLastMonth)
            ->where('u.create_time','<=',$eLastMonth)
            ->count();

        $userLastNums = $monthUserNums-$lastMonthUserNums;
        $userCount = [
            'userNums'=>$userNums,
            'userLastNums'=>$userLastNums,
        ];
        $this->assign('userCount',$userCount);

        $monthOrderNums = Db::name('orders')
            ->where('org_id',$this->orgId)
            ->where('create_yyyymm',date('Ym'))
            ->where('del',0)
            ->count();
        $lastMonthOrderNums = Db::name('orders')
            ->where('org_id',$this->orgId)
            ->where('create_yyyymm',date('Ym',strtotime('-1 month')))
            ->where('del',0)
            ->count();
        $orderLastNums = $monthOrderNums -$lastMonthOrderNums;
        $orderCount = [
            'orderNums'=>$monthOrderNums,
            'orderLastNums'=>$orderLastNums,
        ];
        $this->assign('orderCount',$orderCount);

        $yearOrderNums = Db::name('orders')
            ->where('org_id',$this->orgId)
            ->where('create_yyyy',date('Y'))
            ->where('del',0)
            ->count();
        $lastYearOrderNums = Db::name('orders')
            ->where('org_id',$this->orgId)
            ->where('create_yyyy',date('Y',strtotime('-1 year')))
            ->where('del',0)
            ->count();
        $endYearOrderCount = $yearOrderNums - $lastYearOrderNums;
        if($lastYearOrderNums < 1){
            $orderLastYearNums = 100;
        }else{
            $orderLastYearNums = round($endYearOrderCount/$lastYearOrderNums,2)*100;
        }
        $orderYearCount = [
            'orderYearNums'=>$yearOrderNums,
            'orderLastYearNums'=>$orderLastYearNums,
        ];
        $this->assign('orderYearCount',$orderYearCount);

        $activeUserNums = Db::name('user')
            ->alias('u')
            ->join('user_org uo','uo.user_id=u.id')
            ->where('uo.org_id',$this->orgId)
            ->where('u.del',0)
            ->where('u.enable',1)
            ->where('u.last_login_time','>=',$sMonth)
            ->where('u.last_login_time','<=',$eMonth)
            ->count();
        $lastActiveUserNums = Db::name('user')
            ->alias('u')
            ->join('user_org uo','uo.user_id=u.id')
            ->where('uo.org_id',$this->orgId)
            ->where('u.del',0)
            ->where('u.enable',1)
            ->where('u.last_login_time','>=',$sLastMonth)
            ->where('u.last_login_time','<=',$eLastMonth)
            ->count();
        $activeUserLastNums = $activeUserNums-$lastActiveUserNums;
        $activeUserCount = [
            'activeUserNums'=>$activeUserNums,
            'activeUserLastNums'=>$activeUserLastNums,
        ];
        $this->assign('activeUserCount',$activeUserCount);

        $dayOrderNums1 = Db::name('orders')
            ->where('org_id',$this->orgId)
            ->where('del',0)
            ->where('order_mode',1)
            ->where('create_time','>=',date('Y-m-d').' 00:00:00')
            ->where('create_time','<=',date('Y-m-d').' 23:59:59')
            ->count();
        $dayOrderNums2 = Db::name('orders')
            ->where('org_id',$this->orgId)
            ->where('del',0)
            ->where('order_mode',4)
            ->where('create_time','>=',date('Y-m-d').' 00:00:00')
            ->where('create_time','<=',date('Y-m-d').' 23:59:59')
            ->count();
        $dayOrderNums3 = Db::name('orders')
            ->where('org_id',$this->orgId)
            ->where('del',0)
            ->where('order_mode',5)
            ->where('create_time','>=',date('Y-m-d').' 00:00:00')
            ->where('create_time','<=',date('Y-m-d').' 23:59:59')
            ->count();
        $dayOrderNums4 = Db::name('orders')
            ->where('org_id',$this->orgId)
            ->where('del',0)
            ->where('order_mode',6)
            ->where('create_time','>=',date('Y-m-d').' 00:00:00')
            ->where('create_time','<=',date('Y-m-d').' 23:59:59')
            ->count();
        $dayOrderNums5 = Db::name('orders')
            ->where('org_id',$this->orgId)
            ->where('del',0)
            ->where('order_mode',2)
            ->where('create_time','>=',date('Y-m-d').' 00:00:00')
            ->where('create_time','<=',date('Y-m-d').' 23:59:59')
            ->count();
        $dayOrderNums6 = Db::name('orders')
            ->where('org_id',$this->orgId)
            ->where('del',0)
            ->where('order_mode',3)
            ->where('create_time','>=',date('Y-m-d').' 00:00:00')
            ->where('create_time','<=',date('Y-m-d').' 23:59:59')
            ->count();
        $dayOrderCount =[
            'count1'=> $dayOrderNums1,
            'count2'=> $dayOrderNums2,
            'count3'=> $dayOrderNums3,
            'count4'=> $dayOrderNums4,
            'count5'=> $dayOrderNums5,
            'count6'=> $dayOrderNums6,
        ];
        $this->assign('dayOrderCount',$dayOrderCount);

        $mode = input('mode',1);
        $todoList = Db::name('todo')
            ->where('org_id',$this->orgId)
            ->where('del',0)
            ->where('work_type_mode',$mode)
            ->limit(11)
            ->order('id desc')
            ->select();
        foreach ($todoList as $k=>$v){
            $todoList[$k]['user_name'] = Db::name('user')->where('id',$v['to_user_id'])->value('real_name');
            $todoList[$k]['create_user_name'] = Db::name('user')->where('id',$v['create_user_id'])->value('real_name');
            $todoList[$k]['content'] = Db::name('orders')->where('id',$v['order_id'])->value('content');
        }

        $this->assign('mode',$mode);
        $this->assign('todoList',$todoList);

        $group = Db::name('attendance_group')
            ->where('del',0)
            ->where('org_id',$this->orgId)
            ->select();

        $groupsId = [];
        $groupsId2 = [];
        $week = date('w');
        foreach ($group as $k=>$v){
            $content = json_decode($v['content'],true);
            if($v['type'] == 1){
                foreach ($content['week'] as $kk=>$vv){
                    if($vv['week'] == $week && $vv['class_id'] > 0){
                        $groupsId[] = $v['id'];
                    }
                }
            }
            if($v['type'] == 2){
                $groupClass = Db::name('attendance_group_class')
                    ->where('group_id',$v['id'])
                    ->where('org_id',$this->orgId)
                    ->where('day',date('Y-m-d'))
                    ->find();
                if($groupClass){
                    $groupsId2[] = $v['id'];
                }
            }
        }
        $endGroupIds = array_unique(array_merge($groupsId,$groupsId2));
        $userCount = Db::name('attendance_group_user')
            ->where('org_id',$this->orgId)
            ->whereIn('group_id',$endGroupIds)
            ->count();
        $userIds = Db::name('attendance_group_user')
            ->where('org_id',$this->orgId)
            ->whereIn('group_id',$endGroupIds)
            ->column('user_id');
        $attendanceNums = 0;
        foreach ($userIds as $k=>$v){
            $attendanceRecord = Db::name('attendance_record')
                ->where('user_id',$v)
                ->where('org_id',$this->orgId)
//                ->where('status',1)
                ->where('create_time','>=',date('Y-m-d').' 00:00:00')
                ->where('create_time','<=',date('Y-m-d').' 23:59:59')
                ->select();
            $flag = 0;
            if($attendanceRecord){
                foreach ($attendanceRecord as $kk=>$vv){
                    if($vv['status'] == 1){

                    }else{
                        $flag = 1;
                    }
                }
                if($flag == 0){
                    $attendanceNums +=1;
                }
            }

        }
        $attendanceNums3 = $userCount-$attendanceNums;
        $attendanceCount1 = [
            'count1' => $userCount, //总人数
            'count2' => $attendanceNums, //在职人数
            'count3' => $attendanceNums3>0?$attendanceNums3:0, //缺勤人数
            'bl' => $userCount>0?round($attendanceNums/$userCount,2)*100:0,
            'bl2' => $userCount>0?round($attendanceNums3/$userCount,2)*100:0,
        ];

        $this->assign('attendanceCount1',$attendanceCount1);




        return $this->fetch();
    }

    public function todo(){
        $mode = input('mode',1);
        $todoList = Db::name('todo')
            ->where('org_id',$this->orgId)
            ->where('del',0)
            ->where('work_type_mode',$mode)
            ->limit(11)
            ->order('id desc')
            ->select();
        foreach ($todoList as $k=>$v){
            $todoList[$k]['work_type_mode_text'] = Db::name('work_type_mode')->where('id',$v['work_type_mode'])->value('name');
            $todoList[$k]['to_user_name'] = Db::name('user')->where('id',$v['to_user_id'])->value('real_name');
            $todoList[$k]['user_name'] = Db::name('user')->where('id',$v['create_user_id'])->value('real_name');
            $todoList[$k]['content'] = Db::name('orders')->where('id',$v['order_id'])->value('content');
            $todomode = Db::name('todo_mode')->where('id',$v['todo_mode'])->find();
            $todoList[$k]['todo_mode_text'] = $todomode?$todomode['in_content']:'';
            $todoList[$k]['todo_mode_color'] = $todomode?$todomode['color']:'';
        }

        //数据返回
        $totalCount = count($todoList);
        $totalPage = 1;
        $result['page'] = 1;
        $result['total'] = $totalPage;
        $result['records'] = $totalCount;
        $result['rows'] = $todoList;
        return json($result);
    }

    public function attendanceCount1(){
        $group = Db::name('attendance_group')
            ->where('del',0)
            ->where('org_id',$this->orgId)
            ->select();

        $groupsId = [];
        $groupsId2 = [];
        $week = date('w');
        foreach ($group as $k=>$v){
            $content = json_decode($v['content'],true);
            if($v['type'] == 1){
                foreach ($content['week'] as $kk=>$vv){
                    if($vv['week'] == $week && $vv['class_id'] > 0){
                        $groupsId[] = $v['id'];
                    }
                }
            }
            if($v['type'] == 2){
                $groupClass = Db::name('attendance_group_class')
                    ->where('group_id',$v['id'])
                    ->where('org_id',$this->orgId)
                    ->where('day',date('Y-m-d'))
                    ->find();
                if($groupClass){
                    $groupsId2[] = $v['id'];
                }
            }
        }
        $endGroupIds = array_unique(array_merge($groupsId,$groupsId2));
        $userCount = Db::name('attendance_group_user')
            ->where('org_id',$this->orgId)
            ->whereIn('group_id',$endGroupIds)
            ->count();
        $userIds = Db::name('attendance_group_user')
            ->where('org_id',$this->orgId)
            ->whereIn('group_id',$endGroupIds)
            ->column('user_id');
        $attendanceNums = 0;
        foreach ($userIds as $k=>$v){
            $attendanceRecord = Db::name('attendance_record')
                ->where('user_id',$v)
                ->where('org_id',$this->orgId)
//                ->where('status',1)
                ->where('create_time','>=',date('Y-m-d').' 00:00:00')
                ->where('create_time','<=',date('Y-m-d').' 23:59:59')
                ->select();
            $flag = 0;
            if($attendanceRecord){
                foreach ($attendanceRecord as $kk=>$vv){
                    if($vv['status'] == 1){

                    }else{
                        $flag = 1;
                    }
                }
                if($flag == 0){
                    $attendanceNums +=1;
                }
            }
        }
        $attendanceNums3 = $userCount-$attendanceNums;
        $attendanceCount1 = [
            'count1' => $userCount, //总人数
            'count2' => $attendanceNums, //在职人数
            'count3' => $attendanceNums3>0?$attendanceNums3:0, //缺勤人数
            'bl' => $userCount>0?round($attendanceNums/$userCount,2)*100:0,
            'bl2' => $userCount>0?round($attendanceNums3/$userCount,2)*100:0,
        ];

        $this->success('','',$attendanceCount1);
    }

    public function changeOrg(){
        if(request()->isAjax()){
            $id = input('id/d');
            $info = Db::name('org')->where('id',$id)->find();
            if($info['type'] != 2){
                $this->error('管理机构不能切换');
            }

            session('orgId',$info['id']);
            session('orgName',$info['name']);
            $this->success('切换成功');

        }else{
            $tree = model('Org')->getTreeByRoles($this->rolesId,$this->userId);
            $this->assign('tree',$tree);
            return $this->fetch();
        }
    }

    public function order(){
        // 判断用户是否是调度
        $level = get_dispatch_auth($this->userId);

        if(!$level){
            $this->error('无权限');
        }
        $map[] = ['org_id','=',$this->orgId];
        $map[] = ['del','=',0];
        $map[] = ['order_mode','=',1];
        $order = 0;
        if(!is_admin($this->userId)){
            $auth = get_dispatch_auth($this->userId);
            if($auth){
                $map[] = ['work_type_mode', 'in', $auth];
                $where[] = ['o.work_type_mode', 'in', $auth];
            }else{
                $map[] = ['work_type_mode', '=', -1];
                $where[] = ['o.work_type_mode', '=', -1];
            }
            $order = Db::name('orders')->where($map)->count();

            //$驳回的订单
            $where[] = ['o.del','=',0];
            $where[] = ['t.del','=',0];
            $bh = Db::name('orders')
                ->alias('o')
                ->join('todo t','t.order_id=o.id')
                ->where('t.todo_mode',4)
                ->where('t.org_id',$this->orgId)
                ->where('o.order_mode',4)
                ->where('o.org_id',$this->orgId)
                ->where($where)
                ->group('o.id')
                ->count();

            $order = $order + $bh;
        }





        $complainCount = Db::name('complain')->where('del',0)->where('org_id',$this->orgId)->where('status',0)->where('order_id',0)->count();
        $hiddendangerCount = Db::name('hiddendanger')->where('del',0)->where('org_id',$this->orgId)->where('status',0)->where('order_id',0)->count();
        $endCount = $order+$complainCount+$hiddendangerCount;

        if(!empty($endCount)){
            $this->success('','',$endCount);
        }else{
            $this->error('无订单');
        }
    }

    public function ordersList() {
        $orderType = input('orderType',1);
        $mode = input('mode', 0);
//        $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;

            if($orderType == 1){
                $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', 1);
                $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($type != ''){
                    if($oids){
                        $map[] = ['id', 'in', $oids];
                    }else{
                        $map[] = ['id', '=', 0];
                    }
                }

                if($mode == 15){ // 品质检查,单独处理
                    $map[] = ['work_type_mode','=',$mode];
                }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];
                            }
                        }
                    }
                }


                $map = empty($map) ? true : $map;
                //数据查询
                $lists = db('orders')->where($map)
                    ->whereOr($map6)
                    ->limit($start, $length)->order($order)->select();

                foreach ($lists as $k => $v) {

                    $lists[$k] = model('orders')->formatOrder($v);

                    $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('orders')->where($map)->count();
            }elseif($orderType == 2){

                $map[] = ['del','=',0];
                $map[] = ['org_id','=',$this->orgId];

                $hour = (new Config())->getConfig('org_complain_hour',$this->orgId);
                $hour = $hour>0?$hour:0;
                $endTime = date('Y-m-d H:i:s',time() - $hour*60*60);
                $type = input('type/d',0);
                if($hour > 0 && $type == 1){
                    $map[] = ['create_time','<',$endTime];
                    $map[] = ['status','=',0];
                }
                $from = input('from', '', 'trim');
                if ($from!='') {
                    $map[] = ['from','=',$from];
                }
                $map[] = ['status','=',0];
                $map[] = ['order_id','=',0];
                $map= empty($map) ? true: $map;
                //数据查询
                $lists = db('complain')->where($map)
                    ->limit($start,$length)->order($order)->select();

                foreach ($lists as $k=>$v){
                    $lists[$k]['depName'] = Db::name('dep')
                        ->where('id',$v['dep_id'])
                        ->value('title');
//                    $lists[$k]['fromName'] = model('Complain')->from[$v['from']];

                    $lists[$k]['fromName'] = '';
                    if($v['order_id'] > 0  && $v['bus_type'] != 0){
                        if($v['to_from']){
                            $lists[$k]['fromName'] = '一键呼叫';
                        }else{
                            $lists[$k]['fromName'] = '隐患';
                        }
                    }

                    $lists[$k]['worktypemode'] = '';
                    if($v['order_id'] > 0 && in_array($v['bus_type'],[0,1])){
                        $worktype = Db::name('orders')
                            ->alias('o')
                            ->join('work_type_mode w','o.work_type_mode = w.id')
                            ->where('o.id',$v['order_id'])
                            ->value('w.name');
                        $lists[$k]['worktypemode'] = $worktype?$worktype:'';
                    }

                    if($v['hide'] == 1){
                        $lists[$k]['realName'] = '匿名';
                    }else{
                        $lists[$k]['realName'] = Db::name('user')
                            ->where('id',$v['create_user_id'])
                            ->value('real_name');
                    }

                    $orderMode = 0;
                    if($v['order_id'] > 0){
                        $orderMode = Db::name('orders')->where('id',$v['order_id'])->value('order_mode');
                    }

                    $lists[$k]['statusTxt'] = model('Complain')->formatStatus($v['status'],$v['order_id'],$v['id']);
                    $lists[$k]['order_mode'] = $orderMode;

                    if($v['create_time'] < $endTime && $v['status']==0){
                        $lists[$k]['statusTxt'] = $lists[$k]['statusTxt'].'<span style="color:red;">(已超时)</span>';
                    }

                }
                //数据返回
                $totalCount = db('complain')->where($map)->count();
            }elseif ($orderType == 3){
                $map[] = ['del','=',0];
                $map[] = ['org_id','=',$this->orgId];
                $map[] = ['status','=',0];
                $map[] = ['order_id','=',0];
                $from = input('from', '', 'trim');
                if ($from!='') {
                    $map[] = ['from','=',$from];
                }
                $map= empty($map) ? true: $map;
                //数据查询
                $lists = db('hiddendanger')->where($map)
                    ->limit($start,$length)->order($order)->select();
                foreach ($lists as $k=>$v){
                    $lists[$k]['depName'] = Db::name('dep')
                        ->where('id',$v['dep_id'])
                        ->value('title');
//                    $lists[$k]['fromName'] = model('Hiddendanger')->from[$v['from']];
                    $lists[$k]['fromName'] = '';
                    if($v['order_id'] > 0 && $v['bus_type'] != 0){
                        if($v['to_from']){
                            $lists[$k]['fromName'] = '一键呼叫';
                        }else{
                            $lists[$k]['fromName'] = '投诉';
                        }
                    }
                    $lists[$k]['worktypemode'] = '';
                    if($v['order_id'] > 0 && in_array($v['bus_type'],[0,1])){
                        $worktype = Db::name('orders')
                            ->alias('o')
                            ->join('work_type_mode w','o.work_type_mode = w.id')
                            ->where('o.id',$v['order_id'])
                            ->value('w.name');
                        $lists[$k]['worktypemode'] = $worktype?$worktype:'';
                    }
                    $lists[$k]['realName'] = Db::name('user')
                        ->where('id',$v['create_user_id'])
                        ->value('real_name');
//                $lists[$k]['statusTxt'] = $v['status']==1?'已处理':"未处理";
                    $orderMode = 0;
                    if($v['order_id'] > 0){
                        $orderMode = Db::name('orders')->where('id',$v['order_id'])->value('order_mode');
                    }

                    $lists[$k]['statusTxt'] = model('Hiddendanger')->formatStatus($v['status'],$v['order_id'],$v['id']);
                    $lists[$k]['order_mode'] = $orderMode;
                }
                //数据返回
                $totalCount = db('hiddendanger')->where($map)->count();
            }elseif($orderType == 4){

                $order_mode = input('order_mode', 4);
                $map6 = [];
                if ($order_mode != '') {

                    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];
                    }
                }
                $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($type != ''){
                    if($oids){
                        $map[] = ['id', 'in', $oids];
                    }else{
                        $map[] = ['id', '=', 0];
                    }
                }
                if($mode == 15){ // 品质检查,单独处理
                    $map[] = ['work_type_mode','=',$mode];
                }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];
                            }
                        }
                    }
                }

                $orderIds = Db::name('todo')
                    ->where('todo_mode',4)
                    ->where('org_id',$this->orgId)
                    ->where('del',0)
                    ->group('order_id')
                    ->column('order_id');

                $map[] = ['id','in',$orderIds];
                $map = empty($map) ? true : $map;
                //数据查询
                $lists = db('orders')
                    ->where($map)
//                    ->whereOr($map6)
                    ->limit($start, $length)
                    ->order($order)
                    ->select();

                foreach ($lists as $k => $v) {

                    $lists[$k] = model('orders')->formatOrder($v);

                    $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('orders')->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 = '';
            }

            $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('orderType',$orderType);
            return $this->fetch('index/orders');
        }
    }

    //调度查看订单详情
    public function ordersDetail2($id) {
        if (!$id) {
            $this->error('参数错误');
        }
        $type = input('type/d',0);
        $this->assign('type', $type);
        $order = Db::name('orders')->where(['id' => $id])->find();
        $order = model('Orders')->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();
    }
}