<?php
namespace app\admin\controller;

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

class Device extends Auth
{
    public function __construct(App $app = null) {
        parent::__construct($app);
        $this->model = new \app\common\model\Device();
    }
    public function index(){
        if(request()->isAjax()){
            //分页参数
            $length = input('rows',10,'intval');   //每页条数
            $page = input('page',1,'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx','sort','trim');      //排序列
            $sort = input('sord','asc','trim');        //排序方式
            $order = $sortRow.' '.$sort.' ,id desc';

            $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[] = ['org_id','=',$this->orgId];
            $map[] = ['del','=',0];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = Db::name('device')
                ->where($map)->limit($start,$length)
                ->order($order)->select();
            foreach ($lists as $k=>$v){
                $lists[$k]['user_name']=implode(',',$this->model->getByIdUserName($v['id']));
                $info = Db::name('device_cate')
                    ->where('id',$v['cate_id'])
                    ->find();
                $lists[$k]['cate_name'] = $info?$info['title']:'';
            }

            //数据返回
            $totalCount = db('device')->where($map)->count();
            $totalPage = ceil($totalCount/$length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }else{
            $cate = model('DeviceCate')->list();
            $this->assign('cate',$cate);
            $this->assign('meta_title','设备管理列表');
            return $this->fetch();
        }
    }

    /**
     * 新增/编辑
     */
    public function add($id=0){
        $model = $this->model;
        if(request()->isPost()){
            $res = $model->updates();
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error($model->getError());
            }
        }else{
            $meta_title = '新增设备';
            $formModel = new \app\common\model\DeviceForm();
            if($id){
                $info = Db::name('device')->where('id',$id)->find();
                $info['device_form']=explode(',',$info['device_form']);
                $info['user']=$model->getDeviceUserList($info['id']);
                $this->assign('info',$info);
                $meta_title = '编辑设备';
                $deviceForm= $formModel->byCateList($info['cate_id']);
                $this->assign('device_form',$deviceForm);

            }
            //用户
            $user= (new User())->getDeviceWorker();
            $this->assign('device_user',$user);
            $this->assign('meta_title',$meta_title);
            $cate = model('DeviceCate')->list();
            $this->assign('cate',$cate);
            return $this->fetch();
        }
    }

    /**
     * 删除记录
     * @param int $id
     */
    public function del($id=0){
        if(!$id){
            $this->error('参数错误');
        }
        $res = Db::name('device')->where('id',$id)->update(['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::name('device')->where('id',$id)->update([$fn => $fv]);
        if($res){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    //二维码
    public function qrcode($id=0)
    {
        $info=Db::name('device')->where('id',$id)->find();
        if (!$info) {
            exit('数据不存在');
        }
        $code = get_qrcode_str('device', $id);
        $this->assign('code',$code);
        $this->assign('info',$info);
        return $this->fetch();
    }

    public function allPrint(){
        $ids = input('ids/array');
        $colNum = input('colNum',4);

        $deviceList = Db::name('device')
            ->where('org_id',cur_org_id())
            ->where('enable',1)
            ->where('del',0)
            ->select();

        if($ids){
            $list = Db::name('device')
                ->where('org_id',cur_org_id())
                ->where('enable',1)
                ->where('id','in',$ids)
                ->where('del',0)
                ->select();
        }else{
            $list = $deviceList;
        }


        foreach ($list as $k=>$v){
            $list[$k]['qCode'] = get_qrcode_str('device',$v['id']);

        }

        $this->assign('deviceList',$deviceList);
        $this->assign('list',$list);
        $this->assign('ids',$ids);
        $this->assign('colNum',$colNum);
        return $this->fetch();

    }
    public function addrdown(){
        $orgid = $this->orgId;
        $map[] = ['del','=',0];
        $map[] = ['org_id','=',$this->orgId];
        $map= empty($map) ? true: $map;
        //数据查询
        $lists = db('device')->where($map)->select();

        foreach ($lists as $k=>$v){
            $lists[$k]['code'] = get_qrcode_str('device',$v['id']);
        }
        $path = date('Ymd').'_'.$orgid.'_'.time().mt_rand(1000,9999);
        $dir = './uploads/qrcodeimg/'.$path.'/';

        foreach ($lists as $v1){
            $name = $v1['title'].'('.$v1['id'].')'.'.jpg';
            $filepath = $dir.'/'.$name;
            create_qrcode($v1['code'],$filepath);
        }

        $zippath = './uploads/qrcodeimg/'.$path.'.zip';
        $spath = $dir;
        @unlink($zippath);
        $zip = new \ZipArchive();
        if($zip->open($zippath, \ZipArchive::CREATE)=== TRUE){
            add_file_to_zip($spath,$zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法
            $zip->close(); //关闭处理的zip文件
            if(!file_exists($zippath)){
                $this->error("打包失败"); //即使创建,仍有可能失败。。。。
            }

            deldir($dir); // 删除生成的目录

            $downname = session('orgName').'设备维保二维码.zip';
            header("Cache-Control: public");
            header("Content-Description: File Transfer");
            header('Content-disposition: attachment; filename='.$downname); //文件名
            header("Content-Type: application/zip"); //zip格式的
            header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件
            header('Content-Length: '. filesize($zippath)); //告诉浏览器,文件大小
            @readfile($zippath);

        }else{
            $this->error("打包失败");
        }
    }

    public function getByCate(){
        $cate_id = input('id/d',0);
        if($cate_id==0){
            $this->success('操作成功','',[]);

        }
        $list  = Db::name('device_form')
            ->where('org_id',$this->orgId)
            ->where('del',0)
            ->where('enable',1)
            ->where('cate_id',$cate_id)
            ->select();
        $this->success('操作成功','',$list);
    }
}