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("OTA") ->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', '请点击下载导出文件'); /** * 后台操作日志 */ 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("OTA") ->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; } }