<?php
namespace app\admin\controller;

use app\common\model\Task;
use app\common\model\User;
use think\App;
use think\Db;
use think\Exception;

class QualityPlan extends Auth
{
    public function index(){
        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;

            $title = input('title','','trim');
            if($title){
                $map[] = ['title','like','%'.$title.'%'];
            }
            $status = input('status','','trim');
            if($status != ''){
                $map[] = ['status','=',$status];
            }
            $map[] = ['org_id','=',$this->orgId];
            $map[] =['del','=',0];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = Db::name('quality_plan')
                ->where($map)
                ->limit($start,$length)
                ->order($order)
                ->select();
            foreach ($lists as $k=>$v){
                $lists[$k]['uname'] = Db::name('user')->where('id',$v['user_id'])->value('real_name');
                $lists[$k]['count'] = Db::name('quality_task')->where('plan_id',$v['id'])->where('del',0)->count();
            }
            //数据返回
            $totalCount = Db::name('quality_plan')->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('meta_title','品控计划列表');
            return $this->fetch();
        }
    }

    /**
     * 新增/编辑
     */
    public function add($id=0){
        if(request()->isPost()){
            $res = model('QualityPlan')->updates($this->userId);
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error(model('QualityPlan')->getError());
            }
        }else{
            if($id > 0){ // 复制计划
                $info = Db::name('quality_plan')->where('id',$id)->find();
                if($info){
                    $info['content'] = json_decode($info['content'],true);
                }
                $this->assign('info',$info);
            }

            $meta_title = '新增品控计划';
            //获取任务内容
            $patrolForm=(new \app\common\model\QualityGroup())->getByModeList();
            $this->assign('patrolForm',$patrolForm);
            $user=(new User())->getPatrolWorker(18);

            $this->assign('user',$user);
//            $this->assign('mode',$mode);
            $this->assign('meta_title',$meta_title);

            return $this->fetch();
        }
    }

    public function detail($id=0){
        $info = Db::name('quality_plan')->where('id',$id)->find();
        if(!$info){
            $this->error('计划不存在');
        }
        $info['uname'] = Db::name('user')->where('id',$info['user_id'])->value('real_name');
        $info['content'] = json_decode($info['content'],true);
//        $info['lines'] = $info['lines']?json_decode($info['lines'],true):[];
        $unames = Db::name('user')->where('id','in',$info['content']['userIds'])->column('real_name');
        $info['unames'] = $unames?implode(',',$unames):'';
        $this->assign('info',$info);
        return $this->fetch();
    }

    /**
     * 关闭计划
     */
    public function close($id=0){
        if(!$id){
            $this->error('参数错误');
        }
        $info = Db::name('quality_plan')->where('org_id',$this->orgId)->where('id',$id)->where('del',0)->find();
        if(!$info){
            $this->error('计划不存在');
        }
        if($info['close'] == 1){
            $this->error('计划已关闭');
        }
        if($info['status'] == 2){
            $this->error('计划已结束');
        }
        Db::startTrans();
        try{
            $res = Db::name('quality_plan')->where('id',$id)->update([
                'status' => 5,
                'close' => 1,
                'close_user_id' => $this->userId,
                'close_time' => getTime(),
            ]);
            if(!$res){
                \exception('操作失败');
            }

            // 关闭任务
            Db::name('quality_task')
                ->where('del',0)
                ->where('plan_id',$id)
                ->where('status','in',[0,1])
                ->update([
                    'status' => 6,
                    'update_time' => getTime(),
                ]);
            // 已经加入任务的,从任务中删除
            $taskIds = Db::name('quality_task')->where('del',0)->where('plan_id',$id)->column('id');
            if($taskIds){
                Db::name('task')
                    ->where('org_id',$this->orgId)
                    ->where('type',5)
                    ->where('bus_id','in',$taskIds)
                    ->delete();
            }

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error('操作失败');
        }

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

    /**
     * 删除计划
     */
    public function del($id=0){
        if(!$id){
            $this->error('参数错误');
        }
        $info = Db::name('quality_plan')->where('org_id',$this->orgId)->where('id',$id)->where('del',0)->find();
        if(!$info){
            $this->error('计划不存在');
        }
        if($info['status'] != 2){
            $this->error('计划未结束');
        }
        Db::startTrans();
        try{
            $res = Db::name('quality_plan')->where('id',$id)->update([
                'del' => 1,
                'del_user_id' => $this->userId,
                'del_time' => getTime(),
            ]);
            if(!$res){
                \exception('操作失败');
            }

            // 已经加入任务的,从任务中删除
            $taskIds = Db::name('quality_task')->where('del',0)->where('plan_id',$id)->column('id');
            if($taskIds){
                Db::name('task')
                    ->where('org_id',$this->orgId)
                    ->where('type',5)
                    ->where('bus_id','in',$taskIds)
                    ->delete();
            }

            // 删除任务
            Db::name('quality_task')
                ->where('del',0)
                ->where('plan_id',$id)
                ->update([
                    'del' => 1,
                    'del_user_id' => $this->userId,
                    'del_time' => getTime(),
                ]);

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error('操作失败');
        }

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

    public function info($id=0,$mode){
//        $modeName = (new \app\common\model\QualityAddrForm())->getModeTitle($mode);
        $meta_title ='品控巡视轨迹';
        if(!$id){
            $this->error('参数错误');
        }
        $info=Db::name('quality_task')
            ->field('id,start_time,end_time,status,title,interrupt_img,interrupt_reson')
            ->where('id',$id)
            ->find();
        $info['start_time']=date('Y-m-d H:i',strtotime($info['start_time']));
        $info['end_time']=date('Y-m-d H:i',strtotime($info['end_time']));
        //获取执行用户
        $task_user=Db::name('quality_task_user')
            ->alias('ptu')
            ->join('user u','u.id=ptu.user_id')
            ->where('ptu.quality_task_id',$info['id'])
            ->column('u.real_name');
        $info['task_user']=implode(',',$task_user);

        $map[] = ['pr.quality_task_id', '=', $info['id']];
        $map[] = ['pr.org_id', '=', $this->orgId];
//        $map[] = ['pr.patrol_mode', '=', $mode];
        //数据查询
        $lists = Db::name('quality_record')
            ->alias('pr')
            ->field('pr.*,pa.title')
            ->Leftjoin('address pa', 'pa.id=pr.quality_addr_id')
            ->where($map)
            ->order('id','desc')
            ->select();
        foreach ($lists as $k => $v) {
            $lists[$k]['task_title'] = Db::name('quality_task')
                ->where('id', $v['quality_task_id'])->value('title');
            $lists[$k]['task_addr_form'] = Db::name('quality_addr_form')
                ->alias('a')
                ->join('quality_task_addr b','a.id = b.quality_form_id')
                ->where('b.id', $v['quality_addr_form_id'])
                ->value('a.title');
            $lists[$k]['task_user'] = Db::name('user')
                ->where('id', $v['user_id'])->value('real_name');
        }

        $this->assign('meta_title',$meta_title);
        $this->assign('info',$info);
        $this->assign('recordList',$lists);
        $this->assign('mode',$mode);
        return $this->fetch();
    }

    public function calendar($mode){
        $this->assign('mode',$mode);
        return $this->fetch();
    }

    //获取正月数据
    public function taskjson(){
        $mode = (int)input('mode');
        $start = input('start');
        $end = input('end');
        $data = array();
        if(!$start||!$end||$start>$end){
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode($data));
        }
        $start = date('Y-m-d H:i:s',strtotime($start));
        $end = date('Y-m-d H:i:s',strtotime($end));
        $map[] = [''];
        $list = (new \app\common\model\QualityTask())->get_list_by_time($this->orgId,$mode,$start,$end);

        foreach ($list as $k=>$v){
            $arr = array(
                'taskid' => $v['id'],
                'title' => "{$v['title']}<br>执行人:{$v['users']}<br>开始时间:{$v['start_time']}<br>结束时间:{$v['end_time']}<br>",
                'status' => $v['status'],
                'start' => $v['start_time'],
                'end' => $v['end_time']
            );
            if($v['status'] == 0){
                $arr['color'] = '#777777';
            }else if($v['status'] == 1){
                $arr['color'] = '#478fca';
            }else if($v['status'] == 2){
                $arr['color'] = '#69aa46';
            }else{
                $arr['color'] = '#dd5a43';
            }
            $data[] = $arr;
        }
        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($data));
    }

    //复制月计划
    public function plan($mode){
        $type = input('type');
        if(request()->isPost()){
            $data = request()->post();
            if($data['from'] == $data['to']){
                $this->error('不能复制同月的任务');
            }
            $ret =  (new \app\common\model\QualityTask())->plan_data($data,$this->orgId);
            if($ret){
                if($type==1){
                    $this->success('操作成功',url('index',['mode'=>$mode]));
                }else{
                    $this->success('操作成功',url('calendar',['mode'=>$mode]));

                }
            }else{
                $this->error((new \app\common\model\QualityTask())->getError());
            }
        }else{
            $from = (new \app\common\model\QualityTask())->get_task_month($this->orgId,$mode);
            //间隔1月往后数11次
            $timenow = new \Datetime();
            $datetin = \DateInterval::createFromDateString('1 month');

            $datePer = new \DatePeriod($timenow, $datetin, 11);
            $to = [];
            foreach ($datePer as $day) {
                $m =  $day->format('Y-m');
                $to[]= $m;
            }

            $this->assign('from',$from);
            $this->assign('to',$to);
            $this->assign('mode',$mode);
            $this->assign('type',$type);
            return $this->fetch();
        }
    }

    public function batch($mode){
        $type = input('type');

        if(request()->isPost()){
            $data = request()->post();
            $minmonth = date('Y-m');
            if($minmonth >= $data['from']){
                $this->error('参数错误');
            }
            $where = array(
                'org_id' => $this->orgId,
                'patrol_mode' => $data['mode'],
                'del' => 0,
                'create_yyyymm' => date('Ym',strtotime($data['from'].'-01'))
            );
            $default['del'] = 1;
            $default['del_user_id'] = $this->userId;
            $default['del_time'] = date('Y-m-d H:i:s');
            $result = Db::name('quality_task')
                ->where($where)
                ->update($default);

            $type = (new Task())::TASK_TYPE_QUALITY;
            // 检查是否存在任务栏数据中
            $dailyIds = Db::name('quality_task_task')
                ->alias('dt')
                ->join('task t','t.bus_id = dt.id')
                ->where('t.type',$type)
                ->where('dt.org_id',$this->orgId)
                ->where('dt.del',0)
                ->where('dt.create_yyyymm',date('Ym',strtotime($data['from'].'-01')))
                ->column('dt.id');
            if($result){
                if($dailyIds){
                    Db::name('task')
                        ->where('bus_id', 'in',implode(',',$dailyIds))
                        ->where('type', $type)
                        ->delete();
                }
                if($type==1){
                    $this->success('操作成功',url('index',['mode'=>$mode]));
                }else{
                    $this->success('操作成功',url('calendar',['mode'=>$mode]));

                }
            }else{
                $this->error('删除失败');
            }

        }else{
            $from = (new \app\common\model\QualityTask())->get_task_month($this->orgId,$mode);
            $minmonth = date('Y-m');
            $aa = [];
            foreach ($from as $k=>$v){
                if($minmonth < $v['create_yyyymm']){
                    $aa[] = $v['create_yyyymm'];
                }
            }
            $this->assign('from',$aa);
            $this->assign('mode',$mode);
            $this->assign('type',$type);
            return $this->fetch();
        }
    }

    public function buslist($idx=0,$type=0){
        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;

            $title = input('title','','trim');
            if($title){
                $map[] = ['title','like','%'.$title.'%'];
            }

            $map[] = ['enable','=',1];
            $map[] = ['org_id','=',$this->orgId];
            $map[] =['del','=',0];
            $table = '';
            if(in_array($type,[1,2,3,4])){
                $table = 'address';
                $map[]=['','exp',Db::raw("FIND_IN_SET(".($type+2).",types)")];
            }else if($type == 5){ // 日常
                $table = 'address';
                $map[]=['','exp',Db::raw("FIND_IN_SET(".(10).",types)")];
            }else if($type == 6){ // 设备
                $table = 'device';
            }
            $map= empty($map) ? true: $map;

            //数据查询
            $lists = Db::name($table)
                ->where($map)
                ->limit($start,$length)
                ->order($order)
                ->select();
            //数据返回
            $totalCount = Db::name($table)->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('idx',$idx);
            $this->assign('type',$type);
            $this->assign('meta_title','关联项列表');
            return $this->fetch();
        }
    }
}