<?php
namespace app\admin\controller;

use think\App;
use think\Db;
use think\Exception;

class FCleanPlanRecord extends Auth
{

    public function __construct(App $app = null) {
        parent::__construct($app);
        $this->model= new \app\common\model\FCleanPlanRecord();
        $this->table= $this->model->table;

    }
    public function index($id=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.'%'];
            }
            $enable = input('enable','','trim');
            if($enable != ''){
                $map[] = ['enable','=',$enable];
            }

            $formId = input('formId','','trim');
            if($formId != ''){
                $map[] = ['form_id','=',$formId];
            }

            $addrId = input('addrId','','trim');
            if($addrId != ''){
                $map[] = ['address_id','=',$addrId];
            }


            $map[] = ['del','=',0];
            $map[] = ['org_id','=',$this->orgId];
            $map[] = ['plan_id','=',$id];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = db($this->table)->where($map)->limit($start,$length)->order($order)->select();
            foreach ($lists as $k=>$v){
                $ftitle = Db::name('f_clean_type')->where('id',$v['form_id'])->value('title');
                $atitle = Db::name('address')->where('id','in',explode(',',$v['address_id']))->select();
                $lists[$k]['form_title'] = $ftitle;
                $lists[$k]['addr_title'] = $atitle?implode(',',array_column($atitle,'title')):"";
            }
            //数据返回
            $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{
            $pinfo = Db::name('f_clean_plan')->where('id',$id)->find();
            $this->assign('pinfo',$pinfo);
            $ptitle = Db::name('f_clean_plan')->where('id',$pinfo['pid'])->value('title');
            $this->assign('m_name','['.$ptitle.']'.$pinfo['month'].'日计划');

            $forms = $pinfo['forms']?explode(',',$pinfo['forms']):[];
            $addrs = $pinfo['addrs']?explode(',',$pinfo['addrs']):[];
            $typs = (new \app\common\model\CleanType())->getList();
            $address = (new \app\common\model\Address())->getListByType(8);
            foreach ($typs as $k=>$v){
                if(!in_array($v['id'],$forms)){
                    unset($typs[$k]);
                }
            }

            foreach ($address as $k=>$v){
                if(!in_array($v['id'],$addrs)){
                    unset($address[$k]);
                }
            }

            $this->assign('type',$typs?$typs:[]);
            $this->assign('address',$address?$address:[]);

            return $this->fetch();
        }
    }


    /**
     * 新增
     */
    public function add($id=0,$plan_id=0){
        if(request()->isPost()){
            $res = $this->model->addSave();
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error($this->model->getError());
            }
        }else{
            $pinfo = Db::name('f_clean_plan')->where('id',$plan_id)->find();
            if($id > 0){
                $info = Db::name($this->table)->where('id',$id)->find();
                if($info){
                    $plan_id = $info['plan_id'];
                }
            }else{
                $info['start'] = $pinfo['month'].'-01';
                $info['end'] = $pinfo['month'].'-01';
            }
            $this->assign('info',$info);
            $this->assign('plan_id',$plan_id);

            $forms = $pinfo['forms']?explode(',',$pinfo['forms']):[];
            $addrs = $pinfo['addrs']?explode(',',$pinfo['addrs']):[];
            $uids = $pinfo['user']?explode(',',$pinfo['user']):[];
            $typs = (new \app\common\model\FCleanType())->getList();
            $address = (new \app\common\model\Address())->getListByType(8);
            foreach ($typs as $k=>$v){
                if(!in_array($v['id'],$forms)){
                    unset($typs[$k]);
                }
            }

            foreach ($address as $k=>$v){
                if(!in_array($v['id'],$addrs)){
                    unset($address[$k]);
                }
            }

            $users = (new \app\common\model\User())->getCleanWorker();
            $nuser = [];
            foreach ($users as $k=>$v){
                if(in_array($v['id'],$uids)){
                    $nuser[] = $v;
                }
            }
            $this->assign('user',$nuser);

            $this->assign('type',$typs?$typs:[]);
            $this->assign('address',$address?$address:[]);
            return $this->fetch();
        }
    }

    /**
     * 新增
     */
    public function edit($id=0){
        if(request()->isPost()){
            $res = $this->model->editSave();
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error($this->model->getError());
            }
        }else{
            if($id > 0){
                $info = Db::name($this->table)->where('id',$id)->find();
                if($info){
                    $plan_id = $info['plan_id'];
                    $uids = Db::name('f_clean_plan_user')->where('record_id',$info['id'])->column('user_id');
                    $info['user'] = $uids?$uids:[];
                    $info['address_id'] = $info['address_id']?explode(',',$info['address_id']):[];
                }
                $this->assign('info',$info);
            }
            $this->assign('plan_id',$plan_id);

            $pinfo = Db::name('f_clean_plan')->where('id',$plan_id)->find();
            $forms = $pinfo['forms']?explode(',',$pinfo['forms']):[];
            $addrs = $pinfo['addrs']?explode(',',$pinfo['addrs']):[];
            $uids = $pinfo['user']?explode(',',$pinfo['user']):[];
            $typs = (new \app\common\model\FCleanType())->getList();
            $address = (new \app\common\model\Address())->getListByType(8);
            foreach ($typs as $k=>$v){
                if(!in_array($v['id'],$forms)){
                    unset($typs[$k]);
                }
            }

            foreach ($address as $k=>$v){
                if(!in_array($v['id'],$addrs)){
                    unset($address[$k]);
                }
            }

            $users = (new \app\common\model\User())->getCleanWorker();
            $nuser = [];
            foreach ($users as $k=>$v){
                if(in_array($v['id'],$uids)){
                    $nuser[] = $v;
                }
            }
            $this->assign('user',$nuser);

            $this->assign('type',$typs?$typs:[]);
            $this->assign('address',$address?$address:[]);
            return $this->fetch();
        }
    }

    /**
     * 删除记录
     * @param int $id
     */
    public function del($id=0){
        if(!$id){
            $this->error('参数错误');
        }
        $res = db($this->table)->where('id',$id)->setField('del',1);
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    /**
     * 改变字段值
     * @param int $fv
     * @param string $fn
     * @param int $fv
     */
    public function changeField($id=0,$fn='',$fv=0){
        if(!$fn||!$id){
            $this->error('参数错误');
        }
        $res = db($this->table)->where('id',$id)->setField($fn,$fv);
        if($res){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }

    public function calendar(){
        $m = input('month','');
        $curMonth = input('month',date('Y-m'));
        $this->assign('curMonth',$curMonth);
        $back = 0;
        $year = '';
        if($m){
            $back = 1;
            list($year,$y1) = explode('-',$m);
        }
        $this->assign('back',$back);
        $this->assign('year',$year);
        return $this->fetch();
    }

    public function calendardata(){
        $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\FCleanPlanRecord())->get_list_by_time($this->orgId,$start,$end);

        foreach ($list as $k=>$v){
            $arr = array(
                'taskid' => $v['id'],
                'title' => "任务项:{$v['ftitle']}<br>地点:{$v['atitle']}<br>开始时间:{$v['start']}<br>结束时间:{$v['end']}<br>",
                'status' => $v['enable'],
                'start' => $v['start'].' 00:00:00',
                'end' => $v['end'].' 23:59:59'
            );
            if($v['enable'] == 0){
                $arr['color'] = '#478fca';
            }else{
                $arr['color'] = '#69aa46';
            }

//            if($v['status'] == 0){
//                $arr['color'] = '#777777';
//            }else if($v['status'] == 1){
//                $arr['color'] = '#478fca';
//            }else if($v['status'] == 2){
//                $arr['color'] = '#69aa46';
//            }else if($v['status'] == 3){
//                $arr['color'] = '#dd5a43';
//            }else if($v['status'] == 5){
//                $arr['color'] = '#53a2a7';
//            }else{
//                $arr['color'] = '#5b53a7';
//            }
            $data[] = $arr;
        }
        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($data));
    }

    public function year(){
        $year = input('year',date('Y'));
        $month = [];
        for ($i=1;$i<=12;$i++){
            if($i>10){
                $a = $i;
            }else{
                $a='0'.$i;
            }
            $month[] = $year.'-'.$a;
        }
        $list = [];
        foreach ($month as $k=>$v){
            $c = $c1 = $c2 = 0;
            $plan =Db::name('f_clean_plan')
                ->where('del',0)
                ->where('enable',1)
                ->where('org_id',$this->orgId)
                ->where('month',$v)
                ->find();
            if($plan){
                $c = Db::name('f_clean_plan_record')
                    ->where('plan_id',$plan['id'])
                    ->where('del',0)->count();
                $c1 = Db::name('f_clean_plan_record')
                    ->where('plan_id',$plan['id'])
                    ->where('del',0)
                    ->where('enable',0)
                    ->count();
                $c2 = Db::name('f_clean_plan_record')
                    ->where('plan_id',$plan['id'])
                    ->where('del',0)
                    ->where('enable',1)
                    ->count();
            }
            $list[] = [
                'title'=>$v,
                'count'=>$c,
                'count1'=>$c1,
                'count2'=>$c2,
            ];
        }

        $this->assign('lists',$list);
        $this->assign('last',$year+1);
        $this->assign('prv',$year-1);
        return $this->fetch();
    }

    public function detail($id = 0){
        $info = $this->model->detail($id,$this->orgId);
        if($info){
            $info['imgs'] = $info['imgs']?explode(',',$info['imgs']):[];
        }
        $this->assign('info',$info);
        return $this->fetch();
    }

    public function rindex(){
        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.'%'];
            }
            $enable = input('enable','','trim');
            if($enable != ''){
                $map[] = ['enable','=',$enable];
            }

            $formId = input('formId','','trim');
            if($formId != ''){
                $map[] = ['form_id','=',$formId];
            }

            $addrId = input('addrId','','trim');
            if($addrId != ''){
                $map[] = ['address_id','=',$addrId];
            }


            $map[] = ['del','=',0];
            $map[] = ['org_id','=',$this->orgId];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = db($this->table)->where($map)->limit($start,$length)->order($order)->select();
            foreach ($lists as $k=>$v){
                $ftitle = Db::name('f_clean_type')->where('id',$v['form_id'])->value('title');
                $atitle = Db::name('address')->where('id','in',explode(',',$v['address_id']))->select();
                $lists[$k]['form_title'] = $ftitle;
                $lists[$k]['addr_title'] = $atitle?implode(',',array_column($atitle,'title')):"";
            }
            //数据返回
            $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{

            $typs = (new \app\common\model\CleanType())->getList();
            $address = (new \app\common\model\Address())->getListByType(8);

            $this->assign('type',$typs?$typs:[]);
            $this->assign('address',$address?$address:[]);

            return $this->fetch();
        }
    }
}