<?php
namespace app\admin\controller;

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

class PatrolForm extends Auth
{

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

    }
    public function index($mode=1){
        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];
            }
            $cate_id = input('cate_id','','trim');
            if($cate_id != ''){
                $map[] = ['cate_id','=',$cate_id];
            }
            $map[] = ['del','=',0];
            $map[] = ['patrol_mode','=',$mode];
            $map[] = ['org_id','=',$this->orgId];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = db($this->table)->where($map)->limit($start,$length)
                ->order(['sort'=>'asc','id'=>'desc'])
                ->select();
            foreach ($lists as $k=>$v){
                $lists[$k]['type'] = $this->model->type[$v['type']];
                $lists[$k]['cateName'] = $v['cate_id']?implode(',',Db::name('patrol_cate')
                    ->where('id','in',explode(',',$v['cate_id']))
                    ->column('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{
            $this->assign('m_name',(new \app\common\model\PatrolAddrForm())->getModeTitle($mode).'检查项');
            $this->assign('mode',$mode);
            $cate = model('PatrolCate')->getByModeList($mode);
            $this->assign('cate',$cate);
            return $this->fetch();
        }
    }

    /**
     * 新增/编辑
     */
    public function add($id=0){
        $mode  =input('mode',1,'trim');
        if(request()->isPost()){
            $res = $this->model->updates();
            if($res){
                $this->success('操作成功',url('index',['mode'=>$mode]));
            }else{
                $this->error($this->model->getError());
            }
        }else{
            if($id){
                $info =db($this->table)->where('id',$id)->find();
                $info['cate_id'] =  $info['cate_id']?explode(',',$info['cate_id']):[];
                $this->assign('info',$info);
            }
            $cate = model('PatrolCate')->getByModeList($mode);
            $this->assign('type',$this->model->type);
            $this->assign('mode',$mode);
            $this->assign('cate',$cate);
            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 getByCate(){
        $cate_id = input('id',[]);
        $mode = input('mode',0);
        if(empty($cate_id)){
            $this->success('操作成功','',[]);

        }
        $where = '';
        foreach ($cate_id as $k=>$v){
            //$map[]=['','exp',Db::raw("FIND_IN_SET($v,cate_id)")];

            if($k>0){
                $where.='or ';
            }
            $where.='FIND_IN_SET('.$v.',cate_id)';
        }
//
//        if($mode==4){
//            $map[] = ['cate_id','=',$cate_id];
//        }
        $list  = Db::name('patrol_addr_form')
            ->where('org_id',$this->orgId)
            ->where('del',0)
            ->where('enable',1)
            ->whereRaw($where)
            ->select();
        $this->success('操作成功','',$list);
    }
    public function getByCateFrom(){
        $cate_id = input('id',[]);
        $mode = input('mode',0);
        if(empty($cate_id)){
            $this->success('操作成功','',[]);

        }
        $where = '';
        foreach ($cate_id as $k=>$v){
            //$map[]=['','exp',Db::raw("FIND_IN_SET($v,cate_id)")];

            if($k>0){
                $where.='or ';
            }
            $where.='FIND_IN_SET('.$v.',cate_id)';
        }

        //
//        if($mode==4){
//            $map[] = ['cate_id','=',$cate_id];
//        }
        $list  = Db::name('patrol_form')
            ->where('org_id',$this->orgId)
            ->where('del',0)
            ->where('enable',1)
            //->where($map)
            ->whereRaw($where)
            ->order(['sort'=>'asc','id'=>'desc'])
            ->select();
        $this->success('操作成功','',$list);
    }

    public function import(){

        $this->assign('mode',input('mode'));
        return $this->fetch();
    }


    public function downloadtem(){
        set_time_limit(0);
        ini_set("memory_limit","512M");
        $mode = input('mode');

        if($mode == 4){
            $header = [
                ['title' => '名称', 'name' => 'title','width'=>'20'],
                ['title' => '分类(多个用英文,分开)', 'name' => 'cate','width'=>'20'],
                ['title' => '类型(0=选择框 1=输入框)', 'name' => 'type','width'=>'20'],
                ['title' => '备注', 'name' => 'remark','width'=>'20'],
            ];
            $lists = [
                [
                    'title' => '检查项',
                    'cate' => '分类1,分类2',
                    'type' => '0',
                    'remark' => '备注',
                ]
            ];
        }else{


            $header = [
                ['title' => '名称', 'name' => 'title','width'=>'20'],
                ['title' => '类型(0=选择框 1=输入框)', 'name' => 'type','width'=>'20'],
                ['title' => '备注', 'name' => 'remark','width'=>'20'],
            ];
            $lists = [
                [
                    'title' => '检查项',
                    'type' => '0',
                    'remark' => '备注',
                ]
            ];
        }

        $modeTitle = Db::name('patrol_mode')->where('id',$mode)->value('name');


        $filename = $modeTitle.'检查项模板';
        ExcelUtil::export($filename,$header,$lists);

    }

    /**
     * 导入
     */
    public function importexcel(){
        set_time_limit(0);
        ini_set("memory_limit", -1);
        ob_flush();//清空缓存
        flush();//刷新缓存

        $mode = input('mode');

        $curTime = date('Y-m-d H:i:s');

        if($mode == 4){

            try{
                $cols = ['title','cate','type','remark'];
                $lists = ExcelUtil::importExcel('file',$cols,2);
                if($lists === false){
                    exit(ExcelUtil::getError());
                }
                if(empty($lists)){
                    exit('文件内容为空');
                }

                foreach ($lists as $k=>$v){
                    if(!$v['title']){
                        echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,名称为空,未导入</font><br />";
                        continue;
                    }

                    $find = Db::name('patrol_form')
                        ->where('del',0)
                        ->where('org_id',$this->orgId)
                        ->where('title',$v['title'])
                        ->where('patrol_mode',$mode)
                        ->find();

                    if($find) {
                        echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第" . ($k + 1) . "行,检查项已存在,未导入</font><br />";
                        continue;
                    }
                    $cateIds = [];
                    if($v['cate']){
                        $cates = explode(',',$v['cate']);

                        foreach ($cates as $kk=>$vv){
                            $cateId = Db::name('patrol_cate')
                                ->where('del',0)
                                ->where('org_id',$this->orgId)
                                ->where('title',$vv)
                                ->where('patrol_mode',$mode)
                                ->value('id');
                            if(!$cateId){
                                $cateData = [
                                    'org_id'=>$this->orgId,
                                    'title'=>$vv,
                                    'patrol_mode'=>$mode,
                                    'create_time'=>date('Y-m-d H:i:s'),
                                ];

                                $cateIds[] = Db::name('patrol_cate')->insertGetId($cateData);
                            }
                        }

                    }

                    $dt = [
                        'org_id'=>$this->orgId,
                        'title'=>$v['title'],
                        'patrol_mode'=>$mode,
                        'remark'=>$v['remark'],
                        'cate_id'=>$cateIds ? implode(',',$cateIds):'',
                        'type'=>!empty($v['type'])?$v['type']:0,
                        'create_time'=>date('Y-m-d H:i:s'),
                    ];
                    $inset = Db::name('patrol_form')->insert($dt);
                    if(!$inset){

                        $msg = "第".($k+2)."行,导入失败";
                        echo "<font color=\"red\">".$msg."</font><br />";
                        continue;
                    }
                }
                echo "<font color=\"green\">导入完成</font><br />";
            }catch (Exception $e){
                trace($e->getMessage(),'error');
                echo $e->getMessage();
                echo "<font color=\"red\">数据异常,已停止导入</font><br />";
            }

        }else{
            try{
                $cols = ['title','type','remark'];
                $lists = ExcelUtil::importExcel('file',$cols,2);
                if($lists === false){
                    exit(ExcelUtil::getError());
                }
                if(empty($lists)){
                    exit('文件内容为空');
                }

                foreach ($lists as $k=>$v){
                    if(!$v['title']){
                        echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,名称为空,未导入</font><br />";
                        continue;
                    }

                    $find = Db::name('patrol_form')
                        ->where('del',0)
                        ->where('org_id',$this->orgId)
                        ->where('title',$v['title'])
                        ->where('patrol_mode',$mode)
                        ->find();

                    if($find) {
                        echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第" . ($k + 1) . "行,检查项已存在,未导入</font><br />";
                        continue;
                    }

                    $dt = [
                        'org_id'=>$this->orgId,
                        'title'=>$v['title'],
                        'patrol_mode'=>$mode,
                        'remark'=>$v['remark'],
                        'type'=>!empty($v['type'])?$v['type']:0,
                        'create_time'=>date('Y-m-d H:i:s'),
                    ];
                    $inset = Db::name('patrol_form')->insert($dt);
                    if(!$inset){

                        $msg = "第".($k+2)."行,导入失败";
                        echo "<font color=\"red\">".$msg."</font><br />";
                        continue;
                    }
                }
                echo "<font color=\"green\">导入完成</font><br />";
            }catch (Exception $e){
                trace($e->getMessage(),'error');
                echo $e->getMessage();
                echo "<font color=\"red\">数据异常,已停止导入</font><br />";
            }
        }


    }
}