QrcodeController.php 25.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
<?php

namespace app\ht\modules\device\controllers;

use Yii;
use yii\helpers\Url;
use yii\log\Logger;
use yii\base\Exception;
use yii\data\Pagination;
use app\ht\helpers\QrcodeUtil;
use app\ht\controllers\BaseController;
use common\components\adminlog\AdminLogs;
use common\models\Qrcode            as QrcodeModel;
use common\models\QrcodeBatch       as QrcodeBatchModel;
use common\models\RegionFeeSetting  as RegionFeeSettingModel;
use common\helpers\QrcodeHelper;
use common\exts\wechat\Log as WxLog;
use stdClass;
use ZipArchive;
use function intval;
use function strtoupper;
use function opendir;
use function readdir;
use function date;
use function filemtime;
use function strtotime;
use function round;
use function is_dir;
use function system;
use function unlink;
use function closedir;
use function http_build_query;
use function sizeof;
use function time;
use function range;
use function mt_rand;
use function array_keys;
use function dirname;
use function file_exists;
use function mkdir;
use function set_time_limit;
use function glob;
use function is_file;
use function ini_set;
use function json_encode;

require_once Yii::getAlias('@exts').'/PHPExcel.php';
include Yii::getAlias('@QrcodeLib');

/**
 * 分类管理控制器
 * Class BrandController
 * @package app\ht\modules\catalog\controllers
 */
class QrcodeController extends BaseController
{
    const EXPORT_CHUNK = 100; // 导出数据每页多少个

    public function actionIndex()
    {
        // 每次定期清理二维码临时文件
        self::clearQrcodeTempFiles();

        // 获取地区信息
        $region = RegionFeeSettingModel::find()->where(["status" => 1])->asArray()->all();

        $params = array();
        $params = $this->dataList();
        $params['batchList'] = QrcodeBatchModel::find()->asArray()->all();
        $params['region'] = $region;

        return $this->render("index", $params);
    }

    protected function dataList()
    {
        $req = Yii::$app->request;
        $batch_id = $req->get('batch');
        $qrcode_number = $req->get('qrcode_number');
        $status = $req->get('status');
        $city = $req->get('city');

        $map = array();
        if (!empty($batch_id)) {
            $gets['batch_id'] = $batch_id;
            $map[] = array("=", "q.qrcode_batch_id", intval($batch_id), "I");
        } else {
            $gets['batch_id'] = "";
        }

        if (!empty($qrcode_number)) {
            $gets['qrcode_number'] = $qrcode_number;
            $map[] = array("like", "q.number", "%" . $qrcode_number . "%", "S");
        } else {
            $gets['qrcode_number'] = "";
        }

        if (!empty($status)) {
            $gets['status'] = $status;
            $status = intval($status) == -1 ? 0 : $status;
            $map[] = array("=", "q.status", intval($status), "I");
        } else {
            $gets['status'] = "";
        }

        if (!empty($city)) {
            $gets['city'] = $city;
            $map[] = array("like", "qb.city", "%" . $city . "%", "S");
        } else {
            $gets['city'] = "";
        }

        /**
         * 分页处理
         */
        $qrcodeModel = new QrcodeModel();
        $pageSize = $req->get("pageSize") ? (int)$req->get("pageSize") : 20;
        $pages = new Pagination(['totalCount' => $qrcodeModel->getQrcodeListCount($map), 'pageSize' => $pageSize]);
        $qrcodeList = $qrcodeModel->getQrcodeList($pages->offset, $pages->limit, $map);

        return [
            'gets'       => $gets,
            'qrcodeList' => $qrcodeList,
            'pages'      => $pages
        ];
    }

    public function actionBatch()
    {
        $req = Yii::$app->request;
        $city = $req->get('city');
        $name = $req->get('name');
        $batch_id = $req->get('batch');

        $map = array();
        if (!empty($city)) {
            $gets['city'] = $city;
            $map[] = array("like", "city", "%" . $city . "%", "S");
        } else {
            $gets['city'] = "";
        }

        if (!empty($batch_id)) {
            $gets['batch_id'] = $batch_id;
            $map[] = array("=", "id", intval($batch_id), "I");
        } else {
            $gets['batch_id'] = "";
        }

        // 获取地区信息
        $region = RegionFeeSettingModel::find()->where(["status" => 1])->asArray()->all();

        $qrcodeBatch = new QrcodeBatchModel();
        /**
         * 分页处理
         */
        $pageSize = $req->get("pageSize") ? (int)$req->get("pageSize") : 20;
        $pages = new Pagination(['totalCount' => $qrcodeBatch->getQrcodeBatchListCount($map), 'pageSize' => $pageSize]);
        $batchList = $qrcodeBatch->getQrcodeBatchList($pages->offset, $pages->limit, $map);

        $params = array();
        $params['gets'] = $gets;
        $params['batchList'] = $batchList;
        $params['pages'] = $pages;
        $params['region'] = $region;
        return $this->render("batch", $params);
    }

    /**
     * 新增批次
     */
    public function actionBatchCreate()
    {
        // 获取地区信息
        $region = RegionFeeSettingModel::find()->where(["status" => 1])->asArray()->all();
        return $this->render("batch-create", array(
            'region' => $region,
        ));

    }

    /**
     * 编辑批次
     */
    public function actionBatchUpdate()
    {
        $post = Yii::$app->request->post();

        // 如果是提交数据,则执行update动作,反之只显示编辑页面
        if ($post) {
            $batch_id = $post['batch_id'];
            $batch_name = $post['batch_name'];
            $city = $post['city'];

            $msg = array();
            if (empty($batch_name) || empty($batch_name)) {
                $msg['status'] = 0;
                $msg['msg'] = "操作失败,丢失数据";
            } else {
                $qrcodeBatch = QrcodeBatchModel::findOne($batch_id);
                $qrcodeBatch->name = $batch_name;
                $qrcodeBatch->city = $city;
                $qrcodeBatch->updated_at = time();
                $result = $qrcodeBatch->update();

                if ($result) {
                    $msg['status'] = 1;
                    $msg['msg'] = "操作成功";
                } else {
                    $msg['status'] = 0;
                    $msg['msg'] = "操作失败";
                }
            }
            return $this->renderJson($msg);
        } else {
            $id = Yii::$app->request->get('batch_id');
            $params = QrcodeBatchModel::find()->where(["id" => $id])->asArray()->one();

            // 获取地区信息
            $region = RegionFeeSettingModel::find()->where(["status" => 1])->asArray()->all();
            return $this->render("batch-update", array(
                'region' => $region,
                'params' => $params
            ));
        }
    }

    /**
     * 新增批次。但是不生成二维码编号。
     * @return string
     * @throws \Exception
     */
    public function actionDoAddBatch()
    {
        $post = Yii::$app->request->post();

        $batch_name = $post['batch_name'];
        $batch_count = empty($post['batch_count']) ? 0 : intval($post['batch_count']);
        $city = $post['city'];

        $msg = array();
        if (empty($batch_count) || empty($batch_count)) {
            $msg['status'] = 0;
            $msg['msg'] = "操作失败,丢失数据";
        } else {
            $qrcodeBatch = new QrcodeBatchModel();
            $qrcodeBatch->name = $batch_name;
            $qrcodeBatch->status = 0;
            $qrcodeBatch->count = $batch_count;
            $qrcodeBatch->city = $city;
            $qrcodeBatch->created_at = time();
            $qrcodeBatch->updated_at = time();
            $result = $qrcodeBatch->insert();

            if ($result) {
                //执行循环写入 二维码编号
                /*
                 $qrcode = null;
                 $time = time();
                 for($i=0;$i<$batch_count;$i++){
                     $qrcode = new Qrcode();
                     $qrcode->number = " ";
                     $qrcode->qrcode_batch_id = $result; //批次写入返回的结果为平新批次id
                     $qrcode->status = 0;
                     $qrcode->created_at = $time;
                     $qrcode->updated_at = $time;
                     $qrcode->insert();
                     $qrcode_id = $qrcode->id;

                     $data = array();
                     $data['number'] = strtoupper(QrcodeHelper::generateQrcodeNumber($qrcode_id));
                     Qrcode::findOne(["id"=>$qrcode_id])->updateAttributes($data);
                 }*/
                $msg['status'] = 1;
                $msg['msg'] = "操作成功";
            } else {
                $msg['status'] = 0;
                $msg['msg'] = "操作失败";
            }
        }

        return $this->renderJson($msg);
    }


    /**
     * 执行生成 二维码编号
     */
    public function actionDoGenerateQrcode()
    {
        $post = Yii::$app->request->post();
        $batch_id = $post['batch_id'];

        // 根据batch_id 读取批次信息。
        $batchModel = QrcodeBatchModel::findOne(["id" => $batch_id])->toArray();

        $msg = array();
        //存在批次,且批次的生成状态 不为 1
        if (!empty($batchModel) && $batchModel['status'] != 1) {
            $batch_count = $batchModel['count'];
            //执行循环写入 二维码编号
            $transaction = Yii::$app->getDb()->beginTransaction();
            try {
                $qrcode = null;
                $time = time();
                for ($i = 0; $i < $batch_count; $i++) {
                    $qrcode = new QrcodeModel();
                    $qrcode->number = " ";
                    $qrcode->qrcode_batch_id = $batch_id; //批次写入返回的结果为平新批次id
                    $qrcode->status = 0;
                    $qrcode->created_at = $time;
                    $qrcode->updated_at = $time;
                    $qrcode->insert();
                    $qrcode_id = $qrcode->id;

                    $mQrcode = QrcodeModel::findOne(["id" => $qrcode_id]);
                    $mQrcode->number = strtoupper(QrcodeHelper::generateQrcodeNumber($qrcode_id));
                    $result = $mQrcode->save();
                    if ($result == 0) {
                        $transaction->rollBack();
                        $msg['status'] = 0;
                        $msg['msg'] = "生成失败";
                        return $this->renderJson($msg);
                    }
                }

                //修改批次的更新时间(应该增加一个状态,提示是否已经生成过。。)
                $mQrcodeBatch = QrcodeBatchModel::findOne(["id" => $batch_id]);
                $mQrcodeBatch->status = 1;
                $mQrcodeBatch->updated_at = time();
                $result = $mQrcodeBatch->save();
                if ($result == 0) {
                    $transaction->rollBack();
                    $msg['status'] = 0;
                    $msg['msg'] = "生成失败";
                    return $this->renderJson($msg);
                }
                // 提交事务
                $transaction->commit();
            } catch (Exception $exception) {
                $transaction->rollBack();
                Yii::getLogger()->log($exception->getTraceAsString(), Logger::LEVEL_ERROR);
            }

            $msg['status'] = 1;
            $msg['msg'] = "操作成功";
        } else {
            $msg['status'] = 0;
            $msg['msg'] = "操作失败";
        }

        return $this->renderJson($msg);
    }


    /**
     * @param $size
     * @return array
     * 以随机洗牌的形式去处理, 当有重复会过滤掉,重新洗一次牌面
     *
     * 暂时废弃使用
     */
    private function getBatchNum($result, $size)
    {
        // 计算前缀
        $result = $result > 10 ? "0" . $result : "00" . $result;

        $letters = range('a', 'z');
        $generator = function ($prefix) use ($letters) {
            $ret = $prefix;
            for ($i = 0; $i < 5; $i++) {
                $ret .= $letters[mt_rand(0, 25)];
            }
            return $ret;
        };

        $buffer = [];
        for ($i = 0; $i < $size; ++$i) {
            $current = $generator($result);
            if (!isset($buffer[$current])) {
                $buffer[$current] = 0;
            } else {
                --$i;
            }
        }
        $ret = array_keys($buffer);

        return $ret;
    }

    /**
     * 下载二维码
     * @return $this|string
     */
    public function actionDownload()
    {
        $res = Yii::$app->request;

        $qrcode_id = $res->get("id");

        if (empty($qrcode_id)) {
            return $this->renderFile("");
        }

        $qrcodeResult = QrcodeModel::findOne(["id" => $qrcode_id])->toArray();
        if (empty($qrcodeResult)) {
            return $this->renderFile("");
        }

        $qrcode = new \QRcode();
        $filename = $qrcodeResult['number'] . ".png";

        // 确保文件夹已创建
        $path = Yii::getAlias('@webroot') . QrcodeUtil::DOWNLOAD_DIR;
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }

        $file = $path . $filename;
        $qrcodeUrl = QrcodeHelper::getQrcodeUrl($qrcodeResult['number']);
        $qrcode::png($qrcodeUrl, $file, "H", 7, 2);

        /**
         * 后台操作日志
         */
        AdminLogs::doExport('单个二维码', 1);

        return Yii::$app->response->sendFile($file);
    }

    /**
     * 预览二维码
     * @return $this|string
     */
    public function actionPreview()
    {
        $res = Yii::$app->request;
        $qrcode_id = $res->get("id");

        if (empty($qrcode_id)) {
            return $this->renderFile("");
        }

        $qrcodeResult = QrcodeModel::findOne(["id" => $qrcode_id])->toArray();
        if (empty($qrcodeResult)) {
            return $this->renderFile("");
        }

        $qrcode = new \QRcode();

        $qrcodeUrl = QrcodeHelper::getQrcodeUrl($qrcodeResult['number']);
        $qrcode::png($qrcodeUrl, false, "H", 7, 2);

        //return Yii::$app->response->sendFile($file);
    }

    /**
     * 导出名片
     * @return $this|string
     */
    public function actionZip()
    {
        // 避免超时(建议改为分页导出方式)
        set_time_limit(0);

        $res = Yii::$app->request;
        $batch_id = $res->get("batch_id");
        if (empty($batch_id)) {
            return $this->renderJson("标识异常");
        }
        $qrcodeResult = QrcodeModel::find()->where(["qrcode_batch_id" => $batch_id])->asArray()->all();
        if (empty($qrcodeResult)) {
            return $this->renderJson("没有对应的二维码信息");
        }
        // 确保文件夹已创建
        $path = QrcodeUtil::ROOT_DIR . $batch_id . '/';
        $targetPath = QrcodeUtil::ROOT_DIR . "qrcode_" . $batch_id;
        // 清理二维码
        if (file_exists($path)) {
            $files = glob($path . '/*');
            foreach ($files as $f) {
                if (is_file($f)) {
                    unlink($f);
                }
            }
            // 清理二维码名片
            if (file_exists($targetPath)) {
                $targetFiles = glob($targetPath . '/*');
                foreach ($targetFiles as $f) {
                    if (is_file($f)) {
                        unlink($f);
                    }
                }
            }
            // 删除压缩包
            if (file_exists($targetPath . ".zip")) {
                unlink($targetPath . ".zip");
            }
        } else {
            mkdir($path, 0777, true);
        }

        // 生成基础二维码,然后进行二维码追加到名片
        $webRoot = Yii::getAlias('@webroot');
        $qrcode = new \QRcode();
        foreach ($qrcodeResult as $key => $val) {
            $filename = $val['number'] . ".jpeg";
            $file = $path . $filename;
            $qrcodeUrl = QrcodeHelper::getQrcodeUrl($val['number']);
            $qrcode::png($qrcodeUrl, $file, "L", 3, 0);

            $qrcodePath = $path . $filename;
            QrcodeHelper::generateTagImage($qrcodePath, $webRoot, $targetPath, $val['number']);
        }
        //导出xlsx
        $this->exportQrcode($batch_id, "qrcode_" . $batch_id, $qrcodeResult);
        $zip = new ZipArchive();
        $filename = QrcodeUtil::ROOT_DIR . "qrcode_" . $batch_id . ".zip";
        if ($zip->open($filename, ZipArchive::CREATE) === TRUE) {
            $this->addFileToZip2($targetPath . "/", $zip);
        }
        $zip->close();

        return Yii::$app->response->sendFile($filename);
    }

    /**
     * 导出设备名片xlsx
     * @param $batch_id
     * @param $title
     * @param $data
     * @return string
     */
    public function exportQrcode($batch_id, $title, $data)
    {
        ini_set('memory_limit', '256M');
        //得到PHPexcel 操作对象
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->getProperties()->setCreator("极办公")
            ->setTitle($title)
            ->setCreated(Date("Ymd H:i:s", time()));
        //设置列名
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', "二维码图片");

        $num = 1;
        $xls = $objPHPExcel->setActiveSheetIndex(0);
        foreach ($data as $key => $v) {
            $num++;
            $xls->setCellValue('A' . $num, $v['number'] . ".jpeg");
        }
        unset($data);

        $objPHPExcel->getActiveSheet()->setTitle($title);
        $objPHPExcel->setActiveSheetIndex(0);
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); // xlsx , 如果需要xls 则指定格式为:Excel5, 需要csv :CSV
        $filename = QrcodeUtil::ROOT_DIR . "qrcode_" . $batch_id . "/" . $title . ".xlsx";
        $objWriter->save($filename);

        return $filename;
    }

    /**
     * 分批次导出
     */
    public function actionExportZipBatch()
    {
        $get = Yii::$app->request->get();

        $count = QrcodeModel::find()->where(["qrcode_batch_id" => $get['batch_id']])->count();
        $pageCount = ceil($count / self::EXPORT_CHUNK);

        $html = $this->renderPartial("export-qrcode-batch", [
            'get' => http_build_query($get),
            'pageNo' => 1,
            'pageSize' => self::EXPORT_CHUNK,
            'pageCount' => $pageCount,
            'totalNum' => $count,
        ]);

        // 本地操作ID
        //$session = Yii::$app->session;
        //$session['exportID'] = md5(time());

        Yii::$app->session->setFlash('success', '请点击<a href="' . Url::toRoute(['/device/qrcode/download-zip-batch', 'id' => $get['batch_id']]) . '">下载</a>导出文件');

        /**
         * 后台操作日志
         */
        AdminLogs::doExport('二维码批次', $count);

        return json_encode([
            'success'   => true,
            'html'      => $html,
            'get'       => http_build_query($get),
            'pageNo'    => 1,
            'pageSize'  => self::EXPORT_CHUNK,
            'pageCount' => $pageCount,
            'totalNum'  => $count,
        ]);
    }

    /**
     * 分批次导出数据
     */
    public function actionExportQrcodeBatch()
    {
        ini_set('memory_limit', '1024M');
        $post = $this->request->post();
        $pageNo = $post['pageNo'];
        $pageSize = self::EXPORT_CHUNK;

        $batch_id = $post['batch_id'];
        //$title = @iconv('utf-8', 'gbk', "设备批次");
        $title = "设备批次";
        $num = 1;
        $path = QrcodeUtil::ROOT_DIR . $batch_id . '/';
        $targetPath = QrcodeUtil::ROOT_DIR . "qrcode_" . $batch_id;
        $filename = $title . ".xlsx";

        if (empty($batch_id)) {
            return $this->renderJson("标识异常");
        }

        $offset = ($pageNo - 1) * $pageSize;
        $qrcodeResult = QrcodeModel::find()->where(["qrcode_batch_id" => $batch_id])->offset($offset)->limit($pageSize)->asArray()->all();
        if (empty($qrcodeResult)) {
            return $this->renderJson("没有对应的二维码信息");
        }

        ini_set('memory_limit', '256M');
        $PHPExcel = null;
        if ($pageNo == 1) {
            $PHPExcel = new \PHPExcel();
            $PHPExcel->getProperties()->setCreator("极办公")
                ->setTitle($title)
                ->setCreated(Date("Ymd H:i:s", time()));

            //$objPHPExcel->getActiveSheet()->setTitle($title);
            //设置列名
            $PHPExcel->setActiveSheetIndex(0)->setCellValue('A1', "二维码图片");

            //-----------page=1 的时候完成xlsx创建 文件夹创建工作
            //确保文件夹已创建
            //清理二维码
            if (file_exists($path)) {
                $files = glob($path . '/*');
                foreach ($files as $f) {
                    if (is_file($f)) {
                        unlink($f);
                    }
                }
                //清理二维码名片
                if (file_exists($targetPath)) {
                    $targetFiles = glob($targetPath . '/*');
                    foreach ($targetFiles as $f) {
                        if (is_file($f)) {
                            unlink($f);
                        }
                    }
                }
                //删除压缩包
                if (file_exists($targetPath . ".zip")) {
                    unlink($targetPath . ".zip");
                }
            } else {
                mkdir($path, 0777, true);
            }
        } else {
            $num = ($pageNo - 1) * $pageSize + 1;
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            $PHPExcel = $objReader->load($targetPath . "/" . $filename); // 文档名称
        }

        // 生成基础二维码,然后进行二维码追加到名片
        $webRoot = Yii::getAlias('@webroot');
        $qrcode = new \QRcode();
        foreach ($qrcodeResult as $key => $val) {
            $fileImgName = $val['number'] . ".jpeg";
            $file = $path . $fileImgName;
            $qrcodeUrl = QrcodeHelper::getQrcodeUrl($val['number']);
            $qrcode::png($qrcodeUrl, $file, "L", 3, 0);

            $qrcodePath = $path . $fileImgName;
            QrcodeHelper::generateTagImage($qrcodePath, $webRoot, $targetPath, $val['number']);
        }

        // 得到PHPexcel 操作对象
        $xls = $PHPExcel->setActiveSheetIndex(0);
        foreach ($qrcodeResult as $key => $v) {
            $num++;
            $xls->setCellValue('A' . $num, $v['number'] . ".jpeg");
        }

        //if ($pageNo == 1){
        $objWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007'); // xlsx , 如果需要xls 则指定格式为:Excel5, 需要csv :CSV
        $objWriter->save($targetPath . "/" . $filename);
        //}else{

        //}

        /**
         * 后台操作日志
         */
        AdminLogs::doExport('二维码贴牌图片', $num);

        $result = new stdClass();
        $result->success = true;
        $result->params = http_build_query($post);
        $result->datas = sizeof($qrcodeResult);

        return json_encode($result);

    }

    public function addFileToZip2($path, $zip)
    {
        $handler = opendir($path);
        while (($filename = readdir($handler)) !== false) {
            if ($filename != "." && $filename != "..") {
                if (is_dir($path . "/" . $filename)) {
                    $this->addFileToZip2($path . "/" . $filename, $zip);
                } else { //将文件加入zip对象
                    $zip->addFile($path . "/" . $filename);
                    $zip->renameName($path . "/" . $filename, $filename);
                }
            }
        }
        @closedir($path);
    }


    /**
     * 执行下载
     */
    public function actionDownloadZipBatch($id)
    {
        // 查看下载链接是否生成,且数据完整
        //$dir = Yii::getAlias('@download') . '/qrcode/qrcode_'.$id;
        $dir = QrcodeUtil::ROOT_DIR . "qrcode_" . $id;
        $path = QrcodeUtil::ROOT_DIR;
        if (file_exists($dir)) {
            $zip = new ZipArchive();
            $filename = 'qrcode_' . $id . '.zip';
            if ($zip->open($path . $filename, ZipArchive::CREATE) === TRUE) {
                $this->addFileToZip2($dir, $zip);
            }
            $zip->close();
            return Yii::$app->response->sendFile($path . $filename);
        }
    }

    /**
     * 清理二维码临时文件
     * @return string
     */
    private function clearQrcodeTempFiles()
    {
        $qrcodeRootDir = QrcodeUtil::ROOT_DIR;
        if (!is_dir($qrcodeRootDir)) {
            return false;
        }

        WxLog::init();
        $handle = opendir($qrcodeRootDir);
        if ($handle) {
            while (($file = readdir($handle)) !== false) {
                if ($file != '.' && $file != '..') {
                    $fullpath = $qrcodeRootDir . $file;
                    $filedate = date("Y-m-d", filemtime($fullpath));
                    $currentTime = strtotime(date("Y-m-d"));
                    $fileModifiedTime = strtotime($filedate);
                    $Days = round(($currentTime - $fileModifiedTime) / 3600 / 24);
                    // 超过缓存时间删除
                    if ($Days > QrcodeUtil::CACHE_FILE_DAYS) {
                        if (is_dir($fullpath)) { // 目录删除
                            system('rm -rf ' . $fullpath);
                            WxLog::DEBUG('二维码临时文件夹删除=>' . $fullpath . ', 创建' . $Days . '天');
                        } else { // 文件删除
                            unlink($fullpath);
                            WxLog::DEBUG('二维码临时文件删除=>' . $fullpath . ', 创建' . $Days . '天');
                        }
                    }
                }
            }

            // 关闭句柄
            closedir($handle);
        }

        return true;
    }
}