<?php

namespace app\admin\controller;
use app\common\util\QrcodeUtil;
use think\App;
use think\Db;

class GreenAddr extends Auth {
    public function __construct(App $app = null) {
        parent::__construct($app);
        $this->model = new \app\common\model\GreenAddr();
    }
    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];
            }
            $map[] = ['org_id', '=', $this->orgId];
            $map[] = ['del', '=', 0];
            $map = empty($map) ? true : $map;
            //数据查询
            $lists = Db::name('green_addr')->where($map)->limit($start, $length)->order($order)->select();

            //数据返回
            $totalCount = Db::name('green_addr')->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()) {
            $model = $this->model;
            $res = $model->updates();
            if ($res) {
                $this->success('操作成功', url('index'));
            }
            else {
                $this->error($model->getError());
            }
        }
        else {
            $meta_title = '新增绿化地点';
            if ($id) {
                $info = Db::name('green_addr')->where('id', $id)->find();
                $this->assign('info', $info);
                $green_user = Db::name('green_user')
                    ->where('green_addr_id',$info['id'])
                    ->column('user_id');

                $info['green_user'] = isset($green_user)?implode(',',$green_user):'';
                $this->assign('info',$info);
                $meta_title = '编辑绿化地点';
            }

            $greenUser = model('WorkTypeMode')->getRolesUser(19,cur_org_id());
            $this->assign('greenUser',$greenUser);
            $this->assign('meta_title', $meta_title);
            return $this->fetch();
        }
    }
    /**
     * 删除记录
     * @param int $id
     */
    public function del($id = 0) {
        if (!$id) {
            $this->error('参数错误');
        }
        $res = Db::name('green_addr')->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('green_addr')->where('id', $id)->update([$fn => $fv]);
        if ($res) {
            $this->success('操作成功');
        }
        else {
            $this->error('操作失败');
        }
    }
    //二维码
    public function qrcode($id = 0) {
        $info = Db::name('green_addr')->where('id', $id)->find();
        if (!$info) {
            exit('数据不存在');
        }
        $code = get_qrcode_str('green', $id);
        $config = config('app.addr_url');
        $code = $config.$code;
        $this->assign('code', $code);
        $this->assign('info', $info);
        return $this->fetch();
    }
    public function allPrint(){
        $ids = input('ids');
        if(!$ids){
            $list = Db::name('green_addr')
                ->where('org_id',cur_org_id())
                ->where('enable',1)
                ->where('del',0)
                ->select();
        }else{
            $ids = explode(',',$ids);
            $list = Db::name('green_addr')
                ->where('org_id',cur_org_id())
                ->where('enable',1)
                ->where('id','in',$ids)
                ->where('del',0)
                ->select();
        }

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

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

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

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

        foreach ($lists as $v1){
            $name = str_replace('/','-',$v1['title']).'('.$v1['id'].')'.'.jpg';
            $filepath = $dir.'/'.$name;
            QrcodeUtil::create($v1['code'],1,$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("打包失败");
        }
    }

}