<?php
namespace app\admin\controller;

use app\common\util\ExcelUtil;
use think\App;
use think\Db;
use think\Exception;

class CleanPlan extends Auth
{

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

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

            $map[] = ['del','=',0];
            $map[] = ['org_id','=',$this->orgId];
            $map[] = ['pid','=',0];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = Db::name($this->table)->where($map)->limit($start,$length)->order($order)->select();
            foreach ($lists as $k=>$v){
                $ids = Db::name($this->table)->where('del',0)->where('pid',$v['id'])->column('id');
                $lists[$k]['count'] = 0;
                $lists[$k]['finish'] = 0;
                $lists[$k]['notFinish'] = 0;
                if($ids){
                    $lists[$k]['count'] = Db::name('clean_plan_record')->where('del',0)->where('plan_id','in',$ids)->count();
                    $lists[$k]['finish'] = Db::name('clean_plan_record')->where('del',0)->where('enable',1)->where('plan_id','in',$ids)->count();
                    $lists[$k]['notFinish'] = Db::name('clean_plan_record')->where('del',0)->where('enable',0)->where('plan_id','in',$ids)->count();
                }
            }
            //数据返回
            $totalCount = Db::name($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{
            $this->assign('m_name','专项年计划');
            return $this->fetch();
        }
    }


    /**
     * 新增/编辑
     */
    public function add($id=0){
        if(request()->isPost()){
            $res = $this->model->updates();
            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){
                    $info['forms'] = $info['forms']?explode(',',$info['forms']):[];
                    $info['addrs'] = $info['addrs']?explode(',',$info['addrs']):[];
                    $info['user'] = $info['user']?explode(',',$info['user']):[];
                }
                $this->assign('info',$info);
            }

            $users = (new \app\common\model\User())->getCleanWorker();
            $this->assign('user',$users);

            $this->assign('type',(new \app\common\model\CleanType())->getList());
            $this->assign('address',(new \app\common\model\Address())->getListByType(8));
            return $this->fetch();
        }
    }

    /**
     * 删除记录
     * @param int $id
     */
    public function del($id=0){
        if(!$id){
            $this->error('参数错误');
        }
        $info = Db::name($this->table)->where('id',$id)->where('del',0)->find();
        if(!$info){
            $this->error('记录不存在或已删除');
        }
        if($info['pid'] == 0){ // 年计划
            $planIds = Db::name($this->table)->where('pid',$id)->where('del',0)->column('id');

            //删除年下面的月计划
            Db::name($this->table)->where('pid',$id)->where('del',0)->setField('del',1);
            //删除日计划
            if(!empty($planIds)){
                Db::name('clean_plan_record')->whereIn('plan_id',$planIds)->setField('del',1);
            }

        }else{
             Db::name('clean_plan_record')->where('plan_id',$id)->setField('del',1);
        }
        $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 month($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];
            }

            $map[] = ['pid','=',$id];
            $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){
                $lists[$k]['count'] = Db::name('clean_plan_record')->where('plan_id',$v['id'])->where('del',0)->count();
                $lists[$k]['finish'] = Db::name('clean_plan_record')->where('plan_id',$v['id'])->where('del',0)->where('enable',1)->count();
                $lists[$k]['notFinish'] = Db::name('clean_plan_record')->where('plan_id',$v['id'])->where('del',0)->where('enable',0)->count();

            }
            //数据返回
            $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{
            $this->assign('id',$id);
            $info = Db::name('clean_plan')->where('id',$id)->find();
            $this->assign('m_name','['.$info['title'].']月计划');
            return $this->fetch();
        }
    }

    public function madd($id=0,$pid=0){
        if(request()->isPost()){
            $res = $this->model->mupdates();
            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){
                    $info['forms'] = $info['forms']?explode(',',$info['forms']):[];
                    $info['addrs'] = $info['addrs']?explode(',',$info['addrs']):[];
                    $pid = $info['pid'];
                    $info['user'] = $info['user']?explode(',',$info['user']):[];
                }
                $this->assign('info',$info);
            }
            $pinfo = Db::name($this->table)->where('id',$pid)->find();

            $months = [];
            for ($i=1;$i<=12;$i++){
                $months[] = [
                    'id' => $i>9?$pinfo['year'].'-'.$i:$pinfo['year'].'-0'.$i,
                    'title' => $i.'月'
                ];
            }
            $this->assign('months',$months);

            $forms = $pinfo['forms']?explode(',',$pinfo['forms']):[];
            $addrs = $pinfo['addrs']?explode(',',$pinfo['addrs']):[];
            $uids = $pinfo['user']?explode(',',$pinfo['user']):[];
            $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]);
                }
            }

            $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:[]);
            $this->assign('pid',$pid);
            return $this->fetch();
        }
    }

    public function export($id = 0){
        set_time_limit(0);
        ini_set("memory_limit","3000M");
        $info = Db::name('clean_plan')->where('id',$id)->where('pid',0)->where('del',0)->find();
        if(!$info){
            $this->error('记录不存在');
        }
        $lists = Db::name('clean_plan')->where('pid',$id)->where('del',0)->order('month asc,id asc')->select();
        if(!$lists){
            $this->error('未设置月计划');
        }
        $sheets = [];
        $data = [];
        foreach ($lists as $k=>$v){
            $sheets[] = $v['month'];
            $record = Db::name('clean_plan_record')
                ->alias('a')
                ->join('clean_type b','b.id = a.form_id')
                ->join('address c','c.id = a.address_id')
                ->where('a.plan_id',$v['id'])
                ->where('a.del',0)
                ->field('a.start,a.end,a.remark,b.title as btitle,c.title as atitle,a.create_time,a.enable,a.finish_user_id,a.finish_time,a.id,a.content')
                ->order('a.start asc,a.id asc')
                ->select();
            $record = $record?$record:[];
            foreach ($record as $kk=>$vv){
                $users = Db::name('clean_plan_user')
                    ->alias('a')
                    ->join('user b','a.user_id = b.id')
                    ->where('a.record_id',$vv['id'])
                    ->column('b.real_name');
                $record[$kk]['users'] = $users?implode(',',$users):'';
                $record[$kk]['finish_user'] = '';
                if($vv['finish_user_id'] > 0){
                    $record[$kk]['finish_user'] = Db::name('user')->where('id',$vv['finish_user_id'])->value('real_name');
                }

                if($vv['enable'] == 0){
                    $record[$kk]['enable_text'] = '未完成';
                }else{
                    $record[$kk]['enable_text'] = '已完成';
                }

            }
            $data[] = $record;
        }
        $filename = $info['year'].'_'.$info['title'];
        $header = [ // header格式,title和name必须存在
            ['title' => '任务项', 'name' => 'btitle','width'=>'20'],
            ['title' => '地点', 'name' => 'atitle','width'=>'20'],
            ['title' => '开始时间', 'name' => 'start','width'=>'20'],
            ['title' => '结束时间', 'name' => 'end','width'=>'20'],
            ['title' => '备注', 'name' => 'remark','width'=>'20'],
            ['title' => '人员', 'name' => 'users','width'=>'20'],
            ['title' => '状态', 'name' => 'enable_text','width'=>'20'],
            ['title' => '汇报人', 'name' => 'finish_user','width'=>'20'],
            ['title' => '汇报内容', 'name' => 'content','width'=>'20'],
            ['title' => '汇报时间', 'name' => 'finish_time','width'=>'20'],
        ];
        ExcelUtil::exportBySheet($filename,$header,$sheets,$data);
    }
}