| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373 |
- <?php
- // +----------------------------------------------------------------------
- // | likeshop100%开源免费商用商城系统
- // +----------------------------------------------------------------------
- // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
- // | 开源版本可自由商用,可去除界面版权logo
- // | 商业版本务必购买商业授权,以免引起法律纠纷
- // | 禁止对系统程序代码以任何目的,任何形式的再发布
- // | gitee下载:https://gitee.com/likeshop_gitee
- // | github下载:https://github.com/likeshop-github
- // | 访问官网:https://www.likeshop.cn
- // | 访问社区:https://home.likeshop.cn
- // | 访问手册:http://doc.likeshop.cn
- // | 微信公众号:likeshop技术社区
- // | likeshop团队 版权所有 拥有最终解释权
- // +----------------------------------------------------------------------
- // | author: likeshopTeam
- // +----------------------------------------------------------------------
- namespace app\adminapi\lists\gift_card;
- use app\adminapi\{
- lists\BaseAdminDataLists,
- };
- use app\common\{
- lists\ListsExcelInterface,
- lists\ListsExtendInterface,
- model\GiftCardInfo};
- use app\common\service\FileService;
- use app\common\service\GiftCardQrCodeService;
- use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
- use app\common\lists\ListsExcelTrait;
- use app\common\lists\ListsSearchTrait; // 修正命名空间
- /**
- * 批次礼品卡信息列表接口
- * Class GoodsLists
- * @package app\adminapi\lists\goods
- */
- class GiftCardInfoLists extends BaseAdminDataLists implements ListsExcelInterface
- {
- // ... existing code ...
- use ListsSearchTrait;
- use ListsExcelTrait;
- /**
- * 批量生成二维码
- * @return array
- */
- public function batchGenerateQrCode()
- {
- $giftCards = GiftCardInfo::where($this->setSearch())
- ->field('id,card_no,card_pass')
- ->select()
- ->toArray();
- return GiftCardQrCodeService::batchGenerateQrCode($giftCards);
- }
- // ... existing code ...
- /**
- * @notes 搜索条件
- * @return array
- * @author cjhao
- * @date 2021/7/22 10:51
- */
- public function setSearch(): array
- {
- $where = [];
- $params = $this->params;
- //下单时间
- if (isset($params['start_time']) && $params['start_time'] != '') {
- $where[] = ['create_time', '>=', strtotime($params['start_time'])];
- }
- if (isset($params['end_time']) && $params['end_time'] != '') {
- $where[] = ['create_time', '<=', strtotime($params['end_time'])];
- }
- $where[]=['gc_id','=',$params['id']];
- if(isset($params['card_no'])){
- $where[] = ['card_no', 'like', '%' . $params['card_no'] . '%'];
- }
- if(isset($params['is_used'])){
- $where[] = ['is_used', '=', $params['is_used']];
- }
- return $where;
- }
- /**
- * @notes 统计信息
- * @return array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- * @author cjhao
- * @date 2021/7/22 10:51
- */
- public function extend(): array
- {
- return [];
- }
- /**
- * @notes 礼品卡列表
- * @return array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- * @author cjhao
- * @date 2021/7/21 18:31
- */
- public function lists(): array
- {
- $field = 'id,gc_id,card_no,card_pass,card_money,is_used,user_id,used_time,create_time,qr_code_path';
- $lists = GiftCardInfo::field($field)->where($this->setSearch())
- ->with(['user'])
- ->append(['is_used_desc','used_user_name','batch_no','qr_code_url'])
- ->limit($this->limitOffset, $this->limitLength)
- ->order('id', 'desc')
- ->select()
- ->toArray();
- //
- // foreach ($lists as &$list) {
- // $list['qr_code_url'] = 'https://nongfa.sdshengyuekeji.cn/'.$list['qr_code_path'];
- // }
- return $lists;
- }
- /**
- * @notes 总数
- * @return int
- * @author cjhao
- * @date 2021/7/21 18:32
- */
- public function count(): int
- {
- return GiftCardInfo::where($this->setSearch())->count();
- }
- /**
- * @notes 设置excel表名
- * @return string
- * @author cjhao
- * @date 2021/9/23 9:52
- */
- public function setFileName(): string
- {
- return '礼品卡列表';
- }
- /**
- * @notes 设置导出字段
- * @return array
- * @author cjhao
- * @date 2021/9/23 9:59
- */
- public function setExcelFields(): array
- {
- return [
- 'batch_no' => '批次',
- 'card_no' => '礼品卡卡号',
- 'card_pass' => '礼品卡密码',
- 'card_money' => '礼品卡价值',
- 'is_used_desc' => '是否使用',
- 'used_user_name' => '使用人',
- 'used_time' => '使用时间',
- 'create_time'=> '创建时间',
- 'qr_code_url' => '小程序码', // 添加小程序码字段
- ];
- }
- /**
- * @notes 创建包含图片的excel
- * @param $excelFields
- * @param $lists
- * @return string
- * @throws \PhpOffice\PhpSpreadsheet\Exception
- * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
- */
- public function createExcel($excelFields, $lists)
- {
- $title = array_values($excelFields);
- $letter_column = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
- $data = [];
- foreach ($lists as $row) {
- $temp = [];
- foreach ($excelFields as $key => $excelField) {
- $fieldData = $row[$key];
- if(is_numeric($fieldData) && strlen($fieldData) >= 11){
- $fieldData.="\t";
- }
- $temp[$key] = $fieldData;
- }
- $data[] = $temp;
- }
- $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
- $sheet = $spreadsheet->getActiveSheet();
- //设置单元格内容
- foreach ($title as $key => $value) {
- // 单元格内容写入
- $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
- }
- //设置行高
- $spreadsheet->getActiveSheet()->getRowDimension(1)->setRowHeight(25);
- $row = 2; //从第二行开始
- $qrCodeColumnIndex = array_search('qr_code_url', array_keys($excelFields)); // 获取二维码列的索引
- // 创建临时目录
- $tempDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'excel_qr_codes';
- if (!is_dir($tempDir)) {
- mkdir($tempDir, 0755, true);
- }
- foreach ($data as $rowIndex => $item) {
- $column = 1;
- foreach ($item as $key => $value) {
- $columnIndex = $column - 1;
- // 如果是二维码列且有URL,插入图片
- if ($key === 'qr_code_url' && !empty($value)) {
- try {
- // 设置单元格为空,为图片腾出空间
- $sheet->setCellValueByColumnAndRow($column, $row, '');
- // 创建临时文件路径
- $tempFile = $tempDir . DIRECTORY_SEPARATOR . 'qr_' . $rowIndex . '_' . time() . '_' . mt_rand(1000, 9999) . '.png';
- // 下载图片到临时文件
- $context = stream_context_create([
- 'http' => [
- 'timeout' => 10,
- 'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
- ]
- ]);
- $imageContent = @file_get_contents($value, false, $context);
- if ($imageContent !== false && strlen($imageContent) > 0) {
- // 写入临时文件
- if (file_put_contents($tempFile, $imageContent) !== false && file_exists($tempFile)) {
- // 验证是否为有效图片
- $imageInfo = @getimagesize($tempFile);
- if ($imageInfo !== false) {
- // 创建图片对象
- $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
- $drawing->setName('QR Code');
- $drawing->setDescription('小程序码');
- $drawing->setPath($tempFile);
- $drawing->setHeight(60); // 设置图片高度
- $drawing->setWidth(60); // 设置图片宽度
- // 设置图片位置
- $cellCoordinate = $letter_column[$columnIndex] . $row;
- $drawing->setCoordinates($cellCoordinate);
- $drawing->setOffsetX(5); // X轴偏移
- $drawing->setOffsetY(5); // Y轴偏移
- // 将图片添加到工作表
- $drawing->setWorksheet($sheet);
- // 设置行高以适应图片
- $spreadsheet->getActiveSheet()->getRowDimension($row)->setRowHeight(70);
- } else {
- // 图片无效,显示URL
- $sheet->setCellValueByColumnAndRow($column, $row, '图片无效');
- @unlink($tempFile);
- }
- } else {
- // 文件写入失败,显示URL
- $sheet->setCellValueByColumnAndRow($column, $row, '文件写入失败');
- }
- } else {
- // 如果图片下载失败,显示提示
- $sheet->setCellValueByColumnAndRow($column, $row, '图片下载失败');
- }
- } catch (\Exception $e) {
- // 如果图片插入失败,显示错误信息
- $sheet->setCellValueByColumnAndRow($column, $row, '图片处理失败: ' . $e->getMessage());
- }
- } else {
- // 普通文本数据
- $value = strpos($value, '=') === 0 ? " " . $value : $value;
- $sheet->setCellValueByColumnAndRow($column, $row, $value);
- }
- // 设置列宽
- $columnWidth = ($key === 'qr_code_url') ? 15 : max([strlen($value) * 1.2, 15]);
- $spreadsheet->getActiveSheet()->getColumnDimension($letter_column[$columnIndex])->setWidth($columnWidth);
- $column++;
- }
- // 设置默认行高
- if (!isset($qrCodeColumnIndex) || empty($data[$rowIndex]['qr_code_url'])) {
- $spreadsheet->getActiveSheet()->getRowDimension($row)->setRowHeight(25);
- }
- $row++;
- }
- $getHighestRowAndColumn = $sheet->getHighestRowAndColumn();
- $HighestRow = $getHighestRowAndColumn['row'];
- $columnLetter = $getHighestRowAndColumn['column'];
- $titleScope = 'A1:' . $columnLetter . '1';//第一(标题)范围
- // 设置标题样式
- $sheet->getStyle($titleScope)
- ->getFill()
- ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
- ->getStartColor()
- ->setARGB('26956d');
- $sheet->getStyle($titleScope)->getFont()->getColor()
- ->setARGB('FFFFFF');
- $allScope = 'A1:' . $columnLetter . $HighestRow;
- // 设置居中对齐
- $styleArray = [
- 'alignment' => [
- 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
- 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
- ],
- ];
- $sheet->getStyle($allScope)->applyFromArray($styleArray);
- // 设置边框
- $sheet->getStyle($allScope)->getBorders()->getAllBorders()
- ->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
- $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
- //创建excel文件
- $exportCache = new \app\common\cache\ExportCache();
- $src = $exportCache->getSrc();
- if (!file_exists($src)) {
- mkdir($src, 0775, true);
- }
- $writer->save($src . $this->fileName);
- // 清理临时文件
- $this->cleanupTempFiles($tempDir);
- //设置本地excel缓存并返回下载地址
- return (string)(url('index/download/export', ['file' => $exportCache->setFile($this->fileName)], true, true));
- }
- /**
- * @notes 清理临时文件
- * @param string $tempDir
- */
- private function cleanupTempFiles($tempDir)
- {
- if (is_dir($tempDir)) {
- $files = glob($tempDir . DIRECTORY_SEPARATOR . '*');
- foreach ($files as $file) {
- if (is_file($file)) {
- @unlink($file);
- }
- }
- @rmdir($tempDir);
- }
- }
- }
|