<?php
namespace app\api\controller\screen;

use app\hander\HelpHander;
use think\Controller;
use think\Db;
use think\helper\Str;
use think\Request;

class Twolevel extends Controller{

    private $orgs = []; //
    private $jgId = 0; //机构id
    private $title = '';
    private $jgTitle = '';
    private $cityId = 0;


    protected function initialize()
    {
        parent::initialize();

//        $dd = think_decrypt(input('id','','trim'));
//        if(!$dd){
//            HelpHander::error('参数错误');
//        }
//
//        $dd = explode('|',$dd);
//        if(count($dd) != 2){
//            HelpHander::error('参数错误');
//        }
//        $jgId = (int)$dd[0];

        $jgId = input('id','');
        if($jgId < 1){
            HelpHander::error('参数错误');
        }
        $this->jgId = (int)$jgId;

//        $jgId = input('id',0);
//        if($jgId < 1){
//              HelpHander::error('参数错误');
//        }
//        $this->jgId = $jgId;

        $org = Db::name('org')->where('del',0)->where('id',$jgId)->find();
        if(!$org){
            HelpHander::error('参数错误');
        }
        $this->cityId = $org['city_id'];

        $this->jgTitle = $org['name'];
        $this->title = $org['name'].'后勤总数据大屏';
        $this->orgs = $this->getAllNextId($jgId);


    }
    public function getTitle(){
        HelpHander::success(['header'=>$this->title,'jgName'=>$this->jgTitle,'cityId'=>$this->cityId]);
    }


    public function todayTodoInfo(){
        $date = date('Ymd');

        $map[] = ['create_yyyymmdd','=',$date];
        $map[] = ['del','=',0];
        $count = Db::name('todo')->where($map)->where('org_id','in',$this->orgs)->count();

        $map[] = ['todo_mode','=',3];
        $overCount = Db::name('todo')->where($map)->where('org_id','in',$this->orgs)->count();
        $list = [0,0,0,0,0,0];
        $overBl = 0;
        if($count > 0){
            $overBl = round($overCount/$count*100,0);
            $len =  strlen($count);
            if($len == 1){
                $count = '00000'.$count;
            }elseif($len == 2){
                $count = '0000'.$count;
            }elseif($len == 3){
                $count = '000'.$count;
            }elseif($len == 4){
                $count = '00'.$count;
            }elseif($len == 5){
                $count = '0'.$count;
            }else{
                $count = '999999';
            }
            $list = str_split($count);
        }

        $data = [
            'list'=>$list,
            'bl'=>$overBl
        ];

        HelpHander::success($data);
    }

    public function todayTodoType(){
        $date = date('Ymd');

        $map[] = ['create_yyyymmdd','=',$date];
        $map[] = ['del','=',0];

        $count = Db::name('todo')->where($map)->where('work_type_mode',1)->where('org_id','in',$this->orgs)->count();
        $count2 = Db::name('todo')->where($map)->where('work_type_mode',2)->where('org_id','in',$this->orgs)->count();
        $count3 = Db::name('todo')->where($map)->where('work_type_mode',3)->where('org_id','in',$this->orgs)->count();
        $count4 = Db::name('todo')->where($map)->where('work_type_mode',4)->where('org_id','in',$this->orgs)->count();


        $map[] = ['todo_mode','=',3];

        //保修
        $bxCount =  Db::name('todo')->where($map)->where('work_type_mode',1)->where('org_id','in',$this->orgs)->count();
        //保洁
        $bjCount =  Db::name('todo')->where($map)->where('work_type_mode',2)->where('org_id','in',$this->orgs)->count();
        //运送
        $ysCount =  Db::name('todo')->where($map)->where('work_type_mode',3)->where('org_id','in',$this->orgs)->count();
        //隐患
        $yhCount =  Db::name('todo')->where($map)->where('work_type_mode',4)->where('org_id','in',$this->orgs)->count();


        $bxBl = $bjBl = $ysBl = $yhBl =0;
        if($count > 0){
            $bxBl  = round($bxCount/$count*100,0);

        }
        if($count2 >0){
            $bjBl  = round($bjCount/$count2*100,0);
        }
        if($count3 >0){
            $ysBl  = round($ysCount/$count3*100,0);
        }
        if($count4 >0){
            $yhBl  = round($yhCount/$count4*100,0);
        }
        $data = [
            'bx'=>['count'=>$bxCount,'bl'=>$bxBl],
            'bj'=>['count'=>$bjCount,'bl'=>$bjBl],
            'ys'=>['count'=>$ysCount,'bl'=>$ysBl],
            'yh'=>['count'=>$yhCount,'bl'=>$yhBl],
        ];
        HelpHander::success($data);
    }
    public function moduleList(){

        $map[] = ['del','=',0];
        $map[] = ['enable','=',1];
        $map[] = ['type','=',2];

        $orgList = Db::name('org')
            ->field('id,name')
            ->where('id','in',$this->orgs)
            ->where($map)
            ->select();
        $bxCount = $bjCount = $ysCount = $yhCount = $pzCount = $xgCount = $phCount = 0;
        foreach ($orgList as $k=>$v){
            $bx = Db::name('todo')->where('org_id',$v['id'])->where('del',0)->where('work_type_mode',1)->find();
            if($bx){
                $bxCount += 1;
            }
            $bj = Db::name('todo')->where('org_id',$v['id'])->where('del',0)->where('work_type_mode',2)->find();
            if($bj){
                $bjCount += 1;
            }
            $ys = Db::name('todo')->where('org_id',$v['id'])->where('del',0)->where('work_type_mode',3)->find();
            if($ys){
                $ysCount += 1;
            }
            $yh = Db::name('todo')->where('org_id',$v['id'])->where('del',0)->where('work_type_mode',4)->find();
            if($yh){
                $yhCount += 1;
            }
            $pz = Db::name('todo')->where('org_id',$v['id'])->where('del',0)->where('work_type_mode',15)->find();
            if($pz){
                $pzCount += 1;
            }
            $xg = Db::name('patrol_record')->where('org_id',$v['id'])->where('patrol_mode',1)->count();
            if($xg){
                $xgCount += 1;
            }
            $ph = Db::name('ph_todo')->where('org_id',$v['id'])->count();
            if($ph){
                $phCount += 1;
            }
        }
        $data = [
            ['name'=>'保修','value'=>$bxCount],
            ['name'=>'保洁','value'=>$bjCount],
            ['name'=>'运送','value'=>$ysCount],
            ['name'=>'隐患预警','value'=>$yhCount],
            ['name'=>'品质整改','value'=>$pzCount],
            ['name'=>'巡更','value'=>$xgCount],
            ['name'=>'陪护','value'=>$phCount],
        ];


        HelpHander::success($data);

    }

    public function commentComplainList(){
        $date =  [
            date('Y',strtotime('-5 years')),
            date('Y',strtotime('-4 years')),
            date('Y',strtotime('-3 years')),
            date('Y',strtotime('-2 years')),
            date('Y',strtotime('-1 years')),
            date('Y'),
        ];
        $list = $list2 = [];

        foreach ($date as $k=>$v){
            $list[] = Db::name('comment')->where('org_id','in',$this->orgs)->where('create_yyyy',$v)->sum('score');
            $list2[] = Db::name('complain')->where('org_id','in',$this->orgs)->where('create_yyyy',$v)->where('del',0)->count();
        }


        $data = [
            'title'=>$date,
            'list1'=>$list,
            'list2'=>$list2,
        ];

        HelpHander::success($data);

    }

    public function projectCount(){

        $count1 =  Db::name('org')->where('del',0)->where('enable',1)->where('type',2)->whereIn('id',$this->orgs)->count();

        $count2 = Db::name('user')
            ->alias('u')
            ->join('user_org uo','uo.user_id=u.id')
            ->join('org o','o.id=uo.org_id')
            ->where('u.del',0)
            ->where('u.type',0)
            ->where('o.enable',1)
            ->where('o.del',0)
            ->where('o.id','in',$this->orgs)
            ->count();

        $orderCount = Db::name('orders')
            ->where('del',0)
            ->where('org_id','in',$this->orgs)
            ->count();

        $todoCount = Db::name('todo')
            ->where('del',0)
            ->where('org_id','in',$this->orgs)
            ->count();

        $task1 = Db::name('patrol_task')
            ->where('del',0)
            ->where('org_id','in',$this->orgs)
            ->count();

        $task2 = Db::name('device_task')
            ->where('del',0)
            ->where('org_id','in',$this->orgs)
            ->count();

        $taskCount =  $task1 + $task2;

        $commentScore = Db::name('comment')->whereIn('org_id',$this->orgs)->sum('score');


        $data = [
            'count2'=>$count1,
            'count3'=>$count2,
            'count4'=>$orderCount,
            'count5'=>$todoCount,
            'count6'=>$taskCount,
            'count7'=>$commentScore
        ];
        HelpHander::success($data);
    }

    public function cityList(){
        $org = Db::name('org')
            ->where('del',0)
            ->where('enable',1)
            ->where('type',2)
            ->whereIn('id',$this->orgs)
            ->select();
        foreach ($org as $k=>$v){
            $org[$k]['img'] = getSite().'/screen/images/maker.png';
        }
        $data = [
            'list'=>$org,
            'cityId'=>$this->cityId
        ];

        HelpHander::success($data);
    }

    public function quarterScore(){
        $map[] = ['del','=',0];
        $map[] = ['enable','=',1];
        $map[] = ['type','=',2];

        $org = Db::name('org')
            ->field('id,name')
            ->where('del',0)
            ->where('enable',1)
            ->where('type',2)
            ->whereIn('id',$this->orgs)
            ->select();


        //获取当前季度
        $season = ceil((date('n'))/3);
        //当前季度开始时间戳
        $startTime = date('Y-m-d H:i:s', mktime(0,0,0,$season*3-3+1,1,date('Y')));
        //获取当前季度结束时间戳
        $overTime = date('Y-m-d H:i:s', mktime(23,59,59,$season*3,date('t',mktime(0,0,0,$season*3,1,date("Y"))),date('Y')));


        $where[] = ['create_yyyymm','>=',date('Ym',strtotime($startTime))];
        $where[] = ['create_yyyymm','<=',date('Ym',strtotime($overTime))];
        foreach ($org as $k=>$v){
            $org[$k]['score'] = Db::name('comment')->where('org_id',$v['id'])->where($where)->sum('score');

        }
        $list = list_sort_by($org,'score','desc');

        $top1 = isset($list[0])?$list[0]:null;
        $top2 = isset($list[1])?$list[1]:null;
        $top3 = isset($list[2])?$list[2]:null;
        $top4 = isset($list[3])?$list[3]:null;
        $top5 = isset($list[4])?$list[4]:null;


        HelpHander::success(['top1'=>$top1,'top2'=>$top2,'top3'=>$top3,'top4'=>$top4,'top5'=>$top5]);
    }


    public function quarterScore2(){
        $map[] = ['del','=',0];
        $map[] = ['enable','=',1];
        $map[] = ['type','=',2];

        $org = Db::name('org')
            ->field('id,name')
            ->where('del',0)
            ->where('enable',1)
            ->where('type',2)
            ->whereIn('id',$this->orgs)
            ->select();


        //获取当前季度
        $season = ceil((date('n'))/3);
        //当前季度开始时间戳
        $startTime = date('Y-m-d H:i:s', mktime(0,0,0,$season*3-3+1,1,date('Y')));
        //获取当前季度结束时间戳
        $overTime = date('Y-m-d H:i:s', mktime(23,59,59,$season*3,date('t',mktime(0,0,0,$season*3,1,date("Y"))),date('Y')));


        $where[] = ['create_yyyymm','>=',date('Ym',strtotime($startTime))];
        $where[] = ['create_yyyymm','<=',date('Ym',strtotime($overTime))];
        foreach ($org as $k=>$v){
            if($v['id'] == 3){
                $org[$k]['price'] = 5.3;
            }else{
                $org[$k]['price'] = 0;
            }

        }
        $list = list_sort_by($org,'score','desc');

        $top1 = isset($list[0])?$list[0]:null;
        $top2 = isset($list[1])?$list[1]:null;
        $top3 = isset($list[2])?$list[2]:null;
        $top4 = isset($list[3])?$list[3]:null;
        $top5 = isset($list[4])?$list[4]:null;

        HelpHander::success(['top1'=>$top1,'top2'=>$top2,'top3'=>$top3,'top4'=>$top4,'top5'=>$top5]);
    }

    public function fcompanyList(){
        $map[] = ['del','=',0];
        $map[] = ['enable','=',1];
        $map[] = ['type','=',2];

        $org = Db::name('org')
            ->field('id,name')
            ->where('del',0)
            ->where('enable',1)
            ->where('type',2)
            ->whereIn('id',$this->orgs)
            ->select();
        $host = request()->domain(true);
        foreach ($org as $k=>$v){
            if($v['id'] == 3){
                $org[$k]['day'] = 256;
                $org[$k]['nums'] = 1;
                $org[$k]['nums2'] = 1;
                $org[$k]['bl'] = 100;
                $org[$k]['imgs'] = [
                    $host.'/screen/images/nh1.png',
                    $host.'/screen/images/nh2.png',
                    $host.'/screen/images/nh3.png',
                ];
            }else{
                $org[$k]['day'] = 0;
                $org[$k]['nums'] = 0;
                $org[$k]['nums2'] = 0;
                $org[$k]['bl'] = 0;
                $org[$k]['imgs'] = [];
            }

        }

        HelpHander::success($org);
    }

    public function nlxhList(){

        $org = Db::name('org')
            ->field('id,name')
            ->where('del',0)
            ->where('enable',1)
            ->where('type',2)
            ->whereIn('id',$this->orgs)
            ->select();

        foreach ($org as $k=>$v){
            if($v['id'] == 3){
                $org[$k]['value'] =  325;
            }else{
                $org[$k]['value'] =  0;
            }

        }

        //获取当前季度
        $season = ceil((date('n'))/3);
        //当前季度开始时间戳
        $startTime = date('Y-m-d H:i:s', mktime(0,0,0,$season*3-3+1,1,date('Y')));
        //获取当前季度结束时间戳
        $overTime = date('Y-m-d H:i:s', mktime(23,59,59,$season*3,date('t',mktime(0,0,0,$season*3,1,date("Y"))),date('Y')));


        $list = array_slice(list_sort_by($org,'value','desc'),0,5);

        HelpHander::success($list);

    }


    //巡查图片
    public function patrolImg(){

        $data = Db::name('patrol_record')
            ->where('images','<>','')
            ->whereIn('org_id',$this->orgs)
            ->limit(20)
            ->order('id desc')
            ->select();

        foreach ($data as $k=>$v){
            $img = explode(',',$v['images']);
            if($img){
                $data[$k]['images'] = $img[0];
            }
        }
        if(count($data)>2){
            $key = array_rand($data,3);
            $list[] = $data[$key[0]];
            $list[] = $data[$key[1]];
            $list[] = $data[$key[2]];
        }
        $eList = isset($list)?$list:$data;
        HelpHander::success($eList);
    }


    public function patrolRecordList(){
        $dlist = [
            date('Y-m-d',strtotime('-6 days')),
            date('Y-m-d',strtotime('-5 days')),
            date('Y-m-d',strtotime('-4 days')),
            date('Y-m-d',strtotime('-3 days')),
            date('Y-m-d',strtotime('-2 days')),
            date('Y-m-d',strtotime('-1 days')),
            date('Y-m-d'),
        ];
        $date = [];
        $yCount = [];
        $y2Count = [];
        $y3Count = [];
        $y4Count = [];
        foreach ($dlist as $k=>$v){
            $tt = date('Ymd',strtotime($v));
            $count = Db::name('patrol_record')
                ->whereIn('org_id',$this->orgs)
                ->where('create_yyyymmdd',$tt)
                ->where('patrol_mode',1)
                ->count();
            $count2 = Db::name('patrol_record')
                ->whereIn('org_id',$this->orgs)
                ->where('create_yyyymmdd',$tt)
                ->where('patrol_mode',2)
                ->count();
            $count3 = Db::name('patrol_record')
                ->whereIn('org_id',$this->orgs)
                ->where('create_yyyymmdd',$tt)
                ->where('patrol_mode',3)
                ->count();
            $count4 = Db::name('patrol_record')
                ->whereIn('org_id',$this->orgs)
                ->where('create_yyyymmdd',$tt)
                ->where('patrol_mode',4)
                ->count();
            $date[] =  date('m-d',strtotime($v));
            $yCount[] = $count;
            $y2Count[] = $count2;
            $y3Count[] = $count3;
            $y4Count[] = $count4;
        }
        $data = [
            'date'=>$date,
            'count1'=>$yCount,
            'count2'=>$y2Count,
            'count3'=>$y3Count,
            'count4'=>$y4Count,
        ];
        HelpHander::success($data);
    }

    // 获取所有下级的id集合
    public function getAllNextId($id,$data=[]){
        $pids = DB::name('org')->where('parent_id',$id)->column('id');
        if(count($pids)>0){
            foreach($pids as $v){
                $data[] = $v;
                $data = $this->getAllNextId($v,$data); //注意写$data 返回给上级
            }
        }
        if(count($data)>0){
            return $data;
        }else{
            return [];
        }
    }

    public function dailyData(){

        $lists = Db::name('org')
            ->field('id,name as title')
            ->where('enable',1)
            ->where('del',0)
            ->where('type',2)
            ->where('id','in',$this->orgs)
            ->limit(5)
            ->select();

        $orgs = [];
        $pzdata = [];
        $rwdata = [];
        $max = 0;
        foreach ($lists as $k=>$v){
            $orgs[] = $v['title'];
            $pzcount = Db::name('daily_record')->where('org_id',$v['id'])->where('order_id','>',0)->count();
            $pzdata[] = $pzcount;

            $rwcount = Db::name('daily_record')->where('org_id',$v['id'])->count();
            if($rwcount > $max){
                $max = $rwcount;
            }
            $rwdata[] = $rwcount;
        }

        HelpHander::success([
            'orgs'=>$orgs,
            'pzdata'=>$pzdata,
            'rwdata'=>$rwdata,
        ]);
    }

    public function todoData(){
        $lists = Db::name('org')
            ->field('id,name as title')
            ->where('enable',1)
            ->where('del',0)
            ->where('type',2)
            ->where('id','in',$this->orgs)
            ->limit(5)
            ->select();

        $orgs = [];
        $y1 = [];
        $y2 = [];
        $max1 = 0;
        $max2 = 0;
        foreach ($lists as $k=>$v){
            $orgs[] = $v['title'];
            $pzcount = Db::name('todo')->where('org_id',$v['id'])->where('todo_mode',3)->where('del',0)->count();
            $xycount = Db::name('todo')->where('org_id',$v['id'])->where('todo_mode',3)->where('del',0)->sum('xy_time');
            $wccount = Db::name('todo')->where('org_id',$v['id'])->where('todo_mode',3)->where('del',0)->sum('wc_time');
            $y2c = $pzcount>0?round(($xycount/60)/$pzcount,1):0;
            $y2[] = $y2c;

            if($y2c > $max2){
                $max2 = $y2c;
            }
            $y1c = $pzcount>0?round(($wccount/60)/$pzcount,1):0;
            $y1[] = $y1c;
            if($y1c > $max1){
                $max1 = $y1c;
            }
        }

        HelpHander::success([
            'orgs'=>$orgs,
            'y1'=>$y1,
            'y2'=>$y2,
        ]);
    }

    public function getOrgs(){
        $img1 = getSite().'/screen/images/hz01.png';
        $img2 = getSite().'/screen/images/hz02.png';


        $lists1 = Db::name('org')
            ->field('id,name as title,area_screen_img as img')
            ->where('del',0)
            ->where('enable',1)
            ->where('type',2)
            ->where('id','in',$this->orgs)
            ->order('id asc')
            ->limit(6)
            ->select();
        foreach ($lists1 as $k=>$v){
            if(!$v['img']){
                $lists1[$k]['img'] = $img2;
            }
        }

        $endArea = $lists1 ? end($lists1):[];

        $endAreaId = $endArea ?$endArea['id']:'';

        $lists3 = [];
        if(count($lists1)== 6 && $endAreaId){
            $lists3 = Db::name('org')
                ->field('id,name as title,area_screen_img as img')
                ->where('del',0)
                ->where('enable',1)
                ->where('type',1)
                ->where('id','>',$endAreaId)
                ->where('id','in',$this->orgs)
                ->order('id asc')
                ->limit(6)
                ->select();
            foreach ($lists3 as $k=>$v){
                if(!$v['img']){
                    $lists3[$k]['img'] = $img2;
                }
            }
        }
        $endArea2 = $lists3 ? end($lists3):[];
        $endAreaId2 = $endArea2 ? $endArea2['id'] : '';

        $lists2 = [];
        if(count($lists3) == 6 && $endAreaId2){
            $lists2 = Db::name('org')
                ->field('id,name as title,area_screen_img as img')
                ->where('del',0)
                ->where('enable',1)
                ->where('type',1)
                ->where('id','>',$endAreaId2)
                ->where('id','in',$this->orgs)
                ->order('id asc')
                ->limit(6)
                ->select();
            foreach ($lists2 as $k=>$v){
                if(!$v['img']){
                    $lists2[$k]['img'] = $img2;
                }
            }
        }

        HelpHander::success([
            'lists1'=>$lists1,
            'lists2'=>$lists3,
            'lists3'=>$lists2,
            'lists4'=>$lists2,
        ]);
    }


    public function mateTypeCount(){

        $rk = Db::name('company_dispatch')
            ->alias('cd')
            ->join('company_dispatch_goods cdg','cdg.dispatch_id = cd.id')
            ->where('cd.type',0)
            ->where('cd.status',1)
            ->where('cd.org_id','in',$this->orgs)
            ->count();

        $xh = Db::name('todo_mate_item')
            ->alias('tmi')
            ->join('mate_goods mi','mi.id=tmi.items_id')
            ->where('mi.del',0)
            ->where('mi.org_id','in',$this->orgs)
            ->sum('tmi.total');

        $cz = Db::name('mate_goods_log')
            ->where('type',1)
            ->where('org_id','in',$this->orgs)
            ->sum('nums');

        $orderxh = Db::name('todo_mate')
            ->alias('tm')
            ->join('todo_mate_item tmi','tmi.todo_mate_id=tm.id')
            ->where('tm.org_id','in',$this->orgs)
            ->sum('tmi.total');

        $data = [
            'rk'=>$rk,
            'xh'=>$xh,
            'cz'=>$cz,
            'orderxh'=>$orderxh,

        ];
        HelpHander::success($data);
    }


    public function deviceTaskList(){
        $list = [];
        for ($i=1;$i<=12;$i++){
            $list[] = $i;
        }
        $x = $y = $y1 = [];
        foreach ($list as $k=>$v){
            $month = $v;
            if($month < 10){
                $month = '0'.$v;
            }

            $x[] = $v.'月';
            $y[] = Db::name('device_task')
                ->where('del',0)
                ->where('org_id','in',$this->orgs)
                ->where('create_yyyymm',date('Y').$month)
                ->count();

            $y1[] = Db::name('device_task_delay')
                ->where('create_time','>=',date('Y').'-'.$month.'-01 00:00:00')
                ->where('create_time','<=',date('Y').'-'.$month.'-31 23:59:59')
                ->where('status',1)
                ->where('org_id','in',$this->orgs)
                ->count();
        }

        HelpHander::success(['x'=>$x,'y'=>$y,'y1'=>$y1]);
    }
}