BaseExport.php 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. <?php
  2. namespace common\libs\export;
  3. use common\helpers\Cache;
  4. use common\helpers\Cache as CacheHelper;
  5. use common\helpers\Date;
  6. use common\helpers\Form;
  7. use common\helpers\http\RemoteUploadApi;
  8. use common\helpers\LoggerTool;
  9. use common\helpers\Tool;
  10. use common\helpers\user\Info;
  11. use common\libs\dataList\column\DateTime;
  12. use common\libs\dataList\DataList;
  13. use common\models\ApproachOrder;
  14. use common\models\ApproachOrderGoods;
  15. use common\models\Export;
  16. use common\models\Order;
  17. use common\models\OrderGoods;
  18. use common\models\Region;
  19. use common\models\ShopGoods;
  20. use common\models\User;
  21. use mysql_xdevapi\Result;
  22. use Yii;
  23. use yii\base\Exception;
  24. use yii\base\StaticInstanceTrait;
  25. use yii\base\Component;
  26. use yii\data\Pagination;
  27. use yii\db\Query;
  28. class BaseExport extends Component {
  29. use StaticInstanceTrait;
  30. public $moduleId;
  31. /**
  32. * @var string the model class name. This property must be set.
  33. */
  34. public $modelClass;
  35. /**
  36. * @var
  37. */
  38. public $listModelClass;
  39. /**
  40. * @var int
  41. */
  42. public $pageSize = 100;
  43. /**
  44. * @var int
  45. */
  46. public $totalCount = 0;
  47. /**
  48. * @var int
  49. */
  50. public $offset = 0;
  51. /**
  52. * @var int
  53. */
  54. public $limit = 100;
  55. /**
  56. * csv文件名称
  57. * @var null
  58. */
  59. public $fileName = null;
  60. /**
  61. * 保存的基本路径
  62. * @var null
  63. */
  64. public $saveBasePath = null;
  65. /**
  66. * 保存路径
  67. * @var null
  68. */
  69. public $savePath = null;
  70. /**
  71. * 正在导出的id
  72. * 来源于exporting_file表
  73. * @var null
  74. */
  75. public $exportId = null;
  76. /**
  77. * 操作人的id
  78. * @var null
  79. */
  80. public $userId = null;
  81. /**
  82. * 任务id
  83. * @var null
  84. */
  85. public $taskId = null;
  86. /**
  87. * 是否完成
  88. * @var bool
  89. */
  90. public $completed = false;
  91. /**
  92. * @var array
  93. */
  94. public $params = [];
  95. /**
  96. * 文件句柄
  97. * @var null
  98. */
  99. private $_fp = null;
  100. /**
  101. * 是否上传远程
  102. * @var bool
  103. */
  104. public $isRemote = true;
  105. /**
  106. * @var DataList
  107. */
  108. private $_listModel;
  109. public static function factory($taskId) {
  110. return new self([
  111. 'taskId' => $taskId
  112. ]
  113. );
  114. }
  115. /**
  116. *
  117. */
  118. public function init() {
  119. parent::init();
  120. $this->isRemote = \Yii::$app->params['isRemoteUpload'];
  121. }
  122. /**
  123. * 生成复杂的路径
  124. * @return string
  125. */
  126. public function pathCreator(...$params) {
  127. $hash = md5(implode('_', $params));
  128. $first = substr($hash, 0, 3);
  129. $second = substr($hash, 3, 2);
  130. $dir = $first . __DS__ . $second . __DS__;
  131. return $dir;
  132. }
  133. /**
  134. * 获取文件名
  135. * @return string|null
  136. * @throws \Exception
  137. */
  138. public function getFileName($ext = '.csv') {
  139. $this->fileName = date('YmdHis', Date::nowTime()) . random_int(1000, 9999) . $ext;
  140. return $this->fileName;
  141. }
  142. /**
  143. * 获取保存的路径
  144. * @return array|null
  145. */
  146. public function getSavePath() {
  147. $this->savePath = $this->pathCreator(date('Ymd', Date::nowTime()));
  148. return trim($this->savePath, __DS__);
  149. }
  150. /**
  151. * @return bool|string|null
  152. */
  153. public function getSaveBasePath() {
  154. $this->saveBasePath = Yii::getAlias('@backendApi') . __DS__ . 'web' . __DS__ . 'upload' . __DS__ . \Yii::$app->params['excelLocalDir'];
  155. return trim($this->saveBasePath, __DS__);
  156. }
  157. /**
  158. * 创建目录(递归创建)
  159. *
  160. * @param $dir
  161. * @return string|false
  162. */
  163. public function mkdir($dir) {
  164. if (!is_dir($dir)) {
  165. $this->mkdir(dirname($dir));
  166. if (!mkdir($dir, 0777))
  167. return false;
  168. @exec('chown -R www:www /'.$dir);
  169. @exec('chmod -R 777 /'.$dir);
  170. }
  171. return $dir;
  172. }
  173. /**
  174. * @return array|mixed
  175. */
  176. public function getParams() {
  177. $this->params = CacheHelper::getAsyncParams($this->taskId);
  178. return $this->params;
  179. }
  180. /**
  181. * @return mixed|null
  182. */
  183. public function getUserId() {
  184. $this->userId = isset($this->params['userId']) ? $this->params['userId'] : null;
  185. return $this->userId;
  186. }
  187. /**
  188. * @return |null
  189. */
  190. public function getExportId() {
  191. $this->exportId = isset($this->params['exportId']) ? $this->params['exportId'] : null;
  192. return $this->userId;
  193. }
  194. /**
  195. * 生成
  196. * @return bool
  197. * @throws Exception
  198. * @throws \yii\base\InvalidConfigException
  199. * @throws \yii\httpclient\Exception
  200. */
  201. public function generate() {
  202. //Logger::info(date('Y-m-d H:i:s'), 'export');
  203. $this->getParams();
  204. if (!$this->params) {
  205. throw new Exception('无法获取需要的参数');
  206. }
  207. $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  208. $path = __DS__ . $path;
  209. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
  210. $this->completed = false;
  211. $this->getExportId();
  212. $this->getUserId();
  213. $fileNameUpdated = false;
  214. $this->_fp = fopen($realFile, 'w');
  215. @exec('chown -R www:www /'.$realFile);
  216. @exec('chmod -R 777 /'.$realFile);
  217. // 获取列表数据及表头
  218. $this->_listModel = new $this->listModelClass();
  219. $this->_listModel->isExport = true;
  220. if(method_exists($this->_listModel, 'getExportHeaders')){
  221. if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
  222. $this->_listModel->exportPrepare(['condition' => $this->params['condition'], 'params' => $this->params['params'], 'others' => isset($this->params['others']) ? $this->params['others'] : [], 'page' => 0, 'pageSize' => $this->pageSize, 'userId' => $this->userId]);
  223. }
  224. $headers = $this->_listModel->getExportHeaders($this->userId);
  225. fputcsv($this->_fp, $headers);
  226. unset($headers);
  227. $this->_updateFirst($realFile, 1);
  228. } else {
  229. throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
  230. }
  231. $this->_loopWriteData($realFile, $fileNameUpdated);
  232. $this->complete();
  233. return true;
  234. }
  235. /**
  236. * 循环写入数据
  237. * @param $realFile
  238. * @param $fileNameUpdated
  239. * @param int $page
  240. * @param int $counter
  241. * @return string
  242. * @throws Exception
  243. */
  244. private function _loopWriteData($realFile, &$fileNameUpdated, $page = 0, $counter = 0){
  245. if(method_exists($this->_listModel, 'getList')){
  246. $list = $this->_listModel->getList(['condition'=>$this->params['condition'], 'params'=> $this->params['params'] ?? [], 'others'=> $this->params['others'] ?? [], 'page'=>$page, 'pageSize'=>$this->pageSize, 'userId'=>$this->userId]);
  247. } else {
  248. throw new Exception($this->listModelClass.'的getList方法不存在');
  249. }
  250. if($page >= $list['totalPages']){
  251. return 'finish';
  252. }
  253. if(!empty($list['list'])){
  254. foreach($list['list'] as $columnData){
  255. fputcsv($this->_fp, Tool::arrTextConvert($columnData));
  256. $counter++;
  257. if ($list['totalCount'] < $counter) {
  258. // $counter = $list['totalCount'];
  259. return 'finish';
  260. }
  261. $percent = intval(($counter / $list['totalCount']) * 100);
  262. $this->_updatePercent($percent);
  263. // if (!$fileNameUpdated) {
  264. // $this->_updateFirst($realFile, $percent);
  265. // } else {
  266. // $this->_updatePercent($percent);
  267. // }
  268. // $fileNameUpdated = true;
  269. unset($percent, $columnData);
  270. }
  271. $page++;
  272. unset($list);
  273. return $this->_loopWriteData($realFile, $fileNameUpdated, $page, $counter);
  274. }
  275. unset($list);
  276. return 'finish';
  277. }
  278. /**
  279. * 循环写入数据
  280. */
  281. private function _loopWriteDataOrder()
  282. {
  283. $orderQuery = Order::find()
  284. ->alias('O')
  285. ->where($this->params['condition'], $this->params['params'])
  286. ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV,OG.STANDARD_PRICE')
  287. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  288. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  289. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  290. ->orderBy('O.CREATED_AT DESC');
  291. // 订单中间表只查询待支付和支付失败的订单
  292. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  293. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  294. $orderStandardQuery = ApproachOrder::find()
  295. ->alias('O')
  296. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  297. ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV,OG.STANDARD_PRICE')
  298. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  299. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  300. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  301. ->orderBy('O.CREATED_AT DESC');
  302. $queryAll = $orderQuery->union($orderStandardQuery, true);
  303. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  304. $lists = $query->all();
  305. if(!empty($lists)){
  306. $regionConfig = Cache::getRegionConfig();
  307. foreach($lists as $columnData) {
  308. $CREATE_USER_ID = Info::getUserIdByUserName($columnData['CREATE_USER']);
  309. $createUserName = Info::getUserRealNameByUserId($CREATE_USER_ID);
  310. $decUserName = Info::getUserNameByUserId($columnData['DEC_ID']);
  311. $columnAccept = [
  312. 'USER_NAME' => $columnData['USER_NAME'],
  313. 'DEC_USER_NAME' => $decUserName,
  314. 'CREATE_USER' => $columnData['CREATE_USER'],
  315. 'CREATE_USER_NAME' => $createUserName,
  316. 'SN' => $columnData['SN'],
  317. 'STATUS' => \Yii::$app->params['orderStatus'][$columnData['STATUS']]['label'] ?? '',
  318. 'SKU_CODE' => $columnData['SKU_CODE'],
  319. 'GOODS_TITLE' => $columnData['GOODS_TITLE'],
  320. 'BUY_NUMS' => $columnData['BUY_NUMS'],
  321. 'CONSIGNEE' => $columnData['CONSIGNEE'],
  322. 'MOBILE' => "\t{$columnData['MOBILE']}",
  323. 'TEL' => "\t{$columnData['TEL']}",
  324. 'PROVINCE' => $regionConfig[$columnData['PROVINCE']]['REGION_NAME'] ?? '',
  325. 'CITY' => $regionConfig[$columnData['CITY']]['REGION_NAME'] ?? '',
  326. 'COUNTY' => $regionConfig[$columnData['COUNTY']]['REGION_NAME'] ?? '',
  327. 'ADDRESS' => $columnData['ADDRESS'],
  328. 'PERIOD_NUM' => $columnData['PERIOD_NUM'],
  329. 'ORDER_TYPE' => ($columnData['ORDER_TYPE'] == 'ZC') ? 'Welcome pack' : (in_array($columnData['PAY_TYPE'], ['cash', 'pay_stack']) ? 'Repeat Purchase': 'Points'),
  330. // 'WAREHOUSE' => $columnData['WAREHOUSE'],
  331. 'CREATED_AT' => Date('Y-m-d H:i:s', $columnData['CREATED_AT']),
  332. 'PAY_TYPE' => ShopGoods::payTypes()[$columnData['PAY_TYPE']]['name'] ?? ShopGoods::payTypes()['cash']['name'],
  333. 'PAY_AT' => Date('Y-m-d H:i:s', $columnData['PAY_AT']),
  334. 'DELIVERY_AT' => Date('Y-m-d H:i:s', $columnData['DELIVERY_AT']),
  335. 'REAL_PRICE' => $columnData['REAL_PRICE'],
  336. 'REAL_PV' => $columnData['REAL_PV'],
  337. 'STANDARD_PRICE' => $columnData['ORDER_AMOUNT_STANDARD'],
  338. 'PAY_FREIGHT' => $columnData['PAY_FREIGHT'],
  339. 'TAX_RATE' => $columnData['TAX_RATE'],
  340. 'TAX_AMOUNT' => Tool::calculateTax($columnData['REAL_PRICE'], $columnData['TAX_RATE'], $columnData['BUY_NUMS']),
  341. 'EXPRESS_COMPANY' => $columnData['EXPRESS_COMPANY'],
  342. 'ORDER_TRACK_NO' => $columnData['ORDER_TRACK_NO'],
  343. 'EXPRESS_TYPE' => $columnData['EXPRESS_TYPE'] == 0 ? 'mailing ':' auto pick',
  344. 'FRONT_REMARK' => $columnData['FRONT_REMARK'],
  345. 'DELIVERY_STATUS_NAME' => \Yii::$app->params['deliveryStatus'][$columnData['DELIVERY_STATUS']]['label'] ?? '',
  346. 'IS_AUTO' => $columnData['IS_AUTO'] == 1 ? 'Yes' : 'No',
  347. ];
  348. fputcsv($this->_fp, Tool::arrTextConvert($columnAccept));
  349. unset($percent, $columnData, $columnAccept);
  350. }
  351. unset($list);
  352. }
  353. unset($list);
  354. return 'finish';
  355. }
  356. /**
  357. * 完成
  358. * @return bool
  359. * @throws Exception
  360. * @throws \yii\base\InvalidConfigException
  361. * @throws \yii\httpclient\Exception
  362. */
  363. public function complete() {
  364. $this->_updatePercent(100);
  365. if ($this->completed) {
  366. return true;
  367. }
  368. if ($this->_fp) {
  369. fclose($this->_fp);
  370. }
  371. // 把导出的文件上传至静态文件服务器
  372. if ($this->isRemote) {
  373. $realFile = $this->getSaveBasePath() . __DS__ . $this->getSavePath() . __DS__ . $this->getFileName();
  374. $remoteUploadApi = RemoteUploadApi::instance();
  375. if ($uploadResult = $remoteUploadApi->upload($realFile)) {
  376. Export::updateAll(['REMOTE_URL' => $uploadResult['url'], 'IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
  377. } else {
  378. $this->_errorHandle();
  379. throw new Exception('文件远程上传失败');
  380. }
  381. // 删除本地临时文件
  382. unlink($realFile);
  383. } else {
  384. Export::updateAll(['IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
  385. }
  386. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin(100, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
  387. CacheHelper::deleteAsyncParams($this->taskId);
  388. $this->completed = true;
  389. }
  390. /**
  391. * @param $message
  392. */
  393. private function _errorNotice($message) {
  394. Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($this->userId, $message, false);
  395. }
  396. /**
  397. * 首次更新
  398. * @param $exportId
  399. * @param $realName
  400. */
  401. private function _updateFirst($realName, $percent) {
  402. $fileName = str_replace($this->getSaveBasePath() . __DS__, '', $realName);
  403. Export::updateAll([
  404. 'FILE_NAME' => str_replace(__DS__, '/', $fileName),
  405. 'UPDATED_AT' => Date::nowTime(),
  406. 'EXPORT_PERCENT' => $percent,
  407. ], 'ID=:ID', [':ID' => $this->exportId]);
  408. }
  409. /**
  410. * 更新百分比
  411. * @param $exportId
  412. * @param $percent
  413. */
  414. private function _updatePercent($percent) {
  415. // 把数据写入数据库中
  416. Export::updateAll(['EXPORT_PERCENT' => $percent], 'ID=:ID', [':ID' => $this->exportId]);
  417. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
  418. }
  419. /**
  420. * 发生错误处理
  421. * @param $exportId
  422. */
  423. private function _errorHandle() {
  424. Export::updateAll(['IS_EXPORTING' => 0], 'ID=:ID', [':ID' => $this->exportId]);
  425. }
  426. /**
  427. * 导出逻辑
  428. * @param $filter
  429. * @param $listName
  430. * @param null $consoleRouter
  431. * @throws Exception
  432. */
  433. public function exportHandle($filter, $listName, $consoleRouter = null){
  434. $params = [
  435. 'moduleId' => $this->moduleId,
  436. 'listName' => $listName,
  437. 'action' => $consoleRouter ? $consoleRouter : Yii::$app->controller->id.'/'.Yii::$app->controller->action->id, // 这里这么写,是因为调用的异步路由和同步的控制器和方法是一样的,所以,只要不传默认调和同步一样的异步方法
  438. 'userId' => Yii::$app->user->id,
  439. ];
  440. $this->webToAsync($params,$filter);
  441. }
  442. /**
  443. * 页面到异步的请求
  444. * @param $params
  445. * @param array $extend
  446. * @return bool
  447. * @throws Exception
  448. */
  449. public function webToAsync($params, $extend = []) {
  450. $default = [
  451. 'moduleId' => null,
  452. 'listName' => null,
  453. 'remark' => null,
  454. 'action' => null,
  455. 'userId' => null,
  456. ];
  457. $params = Tool::deepParse($params, $default);
  458. if (!$params['moduleId'] || !$params['listName'] || !$params['action']) {
  459. throw new Exception('请设置moduleId,listName和action');
  460. }
  461. // 把文件对应的相关资料存入数据库中
  462. $export = new Export();
  463. $export->EXPORT_NAME = $params['listName'] . '_' . date('Exp_y-m-d H:i:s', Date::nowTime());
  464. $export->MODULE_NAME = $params['moduleId'];
  465. $export->REMARK = $params['remark'];
  466. $export->IS_EXPORTING = 1;
  467. $export->ADMIN_ID = \Yii::$app->user->id;
  468. $export->STARTED_AT = Date::nowTime();
  469. $export->CREATED_AT = Date::nowTime();
  470. $export->EXPORT_PERCENT = 0;
  471. $export->ENDED_AT = 0;
  472. $export->UPDATED_AT = 0;
  473. if (!$export->save()) {
  474. throw new Exception(Form::formatErrorsForApi($export->getErrors()));
  475. }
  476. $extend = array_merge($extend, [
  477. 'exportId' => $export->ID,
  478. 'userId' => $params['userId'],
  479. ]);
  480. // 异步处理添加任务
  481. $taskKey = \Yii::$app->swooleAsyncTimer->asyncHandle($params['action'], $extend);
  482. if($taskKey === false){
  483. // 删除刚刚添加的导出数据
  484. Export::deleteAll(['ID'=>$export->ID]);
  485. throw new Exception('导出失败,请求异步处理服务器失败');
  486. }
  487. return $taskKey;
  488. }
  489. /**
  490. * 生成
  491. * @return bool
  492. * @throws Exception
  493. * @throws \yii\base\InvalidConfigException
  494. * @throws \yii\httpclient\Exception
  495. */
  496. public function generateOrderExcel() {
  497. $this->getParams();
  498. if (!$this->params) {
  499. throw new Exception('无法获取需要的参数');
  500. }
  501. $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  502. $path = __DS__ . $path;
  503. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
  504. $this->completed = false;
  505. $this->getExportId();
  506. $this->getUserId();
  507. $fileNameUpdated = false;
  508. $this->_fp = fopen($realFile, 'w');
  509. @exec('chown -R www:www /'.$realFile);
  510. @exec('chmod -R 777 /'.$realFile);
  511. // 获取列表数据及表头
  512. $this->_listModel = new $this->listModelClass();
  513. $this->_listModel->isExport = true;
  514. if(method_exists($this->_listModel, 'getExportHeaders')){
  515. if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
  516. $this->_listModel->exportPrepare(['condition' => $this->params['condition'], 'params' => $this->params['params'], 'others' => $this->params['others'] ?? [], 'page' => 0, 'pageSize' => 100000, 'userId' => $this->userId]);
  517. }
  518. $headers = $this->_listModel->getExportHeaders($this->userId);
  519. fputcsv($this->_fp, $headers);
  520. unset($headers);
  521. $this->_updateFirst($realFile, 1);
  522. } else {
  523. throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
  524. }
  525. $this->_loopWriteDataOrder();
  526. $this->complete();
  527. return true;
  528. }
  529. /**
  530. * 生成
  531. * @return bool
  532. * @throws Exception
  533. * @throws \yii\base\InvalidConfigException
  534. * @throws \yii\httpclient\Exception
  535. */
  536. public function generateOrderPDF() {
  537. $this->getParams();
  538. if (!$this->params) {
  539. throw new Exception('无法获取需要的参数');
  540. }
  541. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  542. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  543. $this->completed = false;
  544. $this->getExportId();
  545. $this->getUserId();
  546. $fileNameUpdated = false;
  547. // 获取列表数据及表头
  548. $this->_listModel = new $this->listModelClass();
  549. $this->_listModel->isExport = true;
  550. // 查询订单数据
  551. // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
  552. $orderQuery = Order::find()
  553. ->alias('O')
  554. ->where($this->params['condition'], $this->params['params'])
  555. ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
  556. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  557. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  558. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  559. ->orderBy('O.CREATED_AT DESC');
  560. // 订单中间表只查询待支付和支付失败的订单
  561. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  562. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  563. $orderStandardQuery = ApproachOrder::find()
  564. ->alias('O')
  565. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  566. ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
  567. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  568. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  569. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  570. ->orderBy('O.CREATED_AT DESC');
  571. $queryAll = $orderQuery->union($orderStandardQuery, true);
  572. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  573. $oderList = $query->all();
  574. if ($oderList) {
  575. $userId = '';
  576. $userName = '';
  577. $address = '';
  578. $mobile = '';
  579. $orderAt = '';
  580. $orderDetails = '';
  581. $orderSn = '';
  582. $orderAmount = 0; // 合计总额
  583. $orderNums = 0; // 合计总数
  584. $totalTaxAmount = 0; // 合计税额
  585. $totalAmount = 0;
  586. foreach ($oderList as $key => $value) {
  587. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  588. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  589. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  590. $userId = $value['USER_NAME'];
  591. $userName = $value['REAL_NAME'];
  592. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  593. $mobile = $value['MOBILE'];
  594. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  595. $orderSn = $value['SN'];
  596. // 总价
  597. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  598. $orderAmount += $totalAmount;
  599. $orderNums += $value['BUY_NUMS'];
  600. // 税额
  601. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  602. $totalTaxAmount += $taxAmount;
  603. $taxAmount = Tool::formatAmount($taxAmount);
  604. $totalAmount = Tool::formatAmount($totalAmount);
  605. // 订单详情
  606. $orderDetails .= <<<EOT
  607. <tr>
  608. <td>{$value['SKU_CODE']}</td>
  609. <td>{$value['GOODS_TITLE']}</td>
  610. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  611. <td>{$value['BUY_NUMS']}</td>
  612. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  613. <td style="text-align: right;">{$taxAmount}</td>
  614. <td style="text-align: right;">{$totalAmount}</td>
  615. </tr>
  616. EOT;
  617. }
  618. // 订单基本信息
  619. $orderBase = <<<ORDER
  620. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  621. <tr>
  622. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Code</td>
  623. <td width="70%">{$userId}</td>
  624. </tr>
  625. <tr>
  626. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Name</td>
  627. <td width="70%">{$userName}</td>
  628. </tr>
  629. <tr>
  630. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Address</td>
  631. <td width="70%">{$address}</td>
  632. </tr>
  633. <tr>
  634. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Phone</td>
  635. <td width="70%">{$mobile}</td>
  636. </tr>
  637. <tr>
  638. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order Code</td>
  639. <td width="70%">{$orderSn}</td>
  640. </tr>
  641. <tr>
  642. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation Time</td>
  643. <td width="70%">{$orderAt}</td>
  644. </tr>
  645. <tr>
  646. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order Detail</td>
  647. <td class="bg"></td>
  648. </tr>
  649. </table>
  650. ORDER;
  651. $l['a_meta_charset'] = 'UTF-8';
  652. $l['a_meta_dir'] = 'ltr';
  653. $l['a_meta_language'] = 'zh';
  654. $l['w_page'] = '页面';
  655. $orderAmount = Tool::formatAmount($orderAmount);
  656. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  657. $context = <<<ORDER
  658. <!doctype html>
  659. <html lang="en">
  660. <head>
  661. <meta charset="UTF-8" />
  662. <title>Order detail</title>
  663. <style>
  664. table {
  665. border-collapse: collapse;
  666. }
  667. table td, table th {
  668. border: 1px solid #ccc;
  669. padding: 5px 5px;
  670. border-collapse: collapse;
  671. }
  672. /*td {*/
  673. /* padding: 120px;*/
  674. /*}*/
  675. .bg {
  676. background-color: #ccc;
  677. }
  678. </style>
  679. </head>
  680. <body>
  681. <div class="content">
  682. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
  683. <div>
  684. <div style="display: block; width: 100%;">
  685. {$orderBase}
  686. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  687. <tr>
  688. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Code</th>
  689. <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Name</th>
  690. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Price</th>
  691. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
  692. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax Rate</th>
  693. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
  694. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total Amount</th>
  695. </tr>
  696. {$orderDetails}
  697. <tr>
  698. <td colspan="3">Total</td>
  699. <td>{$orderNums}</td>
  700. <td></td>
  701. <td style="text-align: right;">{$totalTaxAmount}</td>
  702. <td style="text-align: right;">{$orderAmount}</td>
  703. </tr>
  704. </table>
  705. </div>
  706. <div style="width: 100%; margin-top: 50px; height: 30px;">
  707. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  708. <tr style="border: none;">
  709. <td width="70%" style="border: none;"></td>
  710. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
  711. </tr>
  712. <tr style="border: none;">
  713. <td width="70%" style="border: none;"></td>
  714. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
  715. </tr>
  716. </table>
  717. </div>
  718. </div>
  719. </div>
  720. </body>
  721. </html>
  722. ORDER;
  723. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  724. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  725. // 设置打印模式
  726. $pdf->SetCreator(PDF_CREATOR);
  727. $pdf->SetAuthor('DaZe');
  728. $pdf->SetTitle($orderSn);
  729. $pdf->SetSubject('TCPDF Tutorial');
  730. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  731. // 是否显示页眉
  732. $pdf->setPrintHeader(false);
  733. // 设置页眉字体
  734. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  735. // 页眉距离顶部的距离
  736. $pdf->SetHeaderMargin('5');
  737. // 是否显示页脚
  738. $pdf->setPrintFooter(false);
  739. // 设置默认等宽字体
  740. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  741. // 设置行高
  742. $pdf->setCellHeightRatio(1);
  743. // 设置左、上、右的间距
  744. $pdf->SetMargins('10', '0', '10');
  745. // 设置是否自动分页 距离底部多少距离时分页
  746. $pdf->SetAutoPageBreak(TRUE, '15');
  747. // 设置图像比例因子
  748. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  749. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  750. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  751. $pdf->setLanguageArray($l);
  752. }
  753. $pdf->setFontSubsetting(true);
  754. $pdf->AddPage();
  755. // 设置字体
  756. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  757. $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
  758. $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
  759. $pdf->writeHTML($context);
  760. $pdf->Output($realFile, 'F');
  761. $this->_updateFirst($realFile, 1);
  762. }
  763. $this->complete();
  764. return true;
  765. }
  766. /**
  767. * 生成
  768. * @return bool
  769. * @throws Exception
  770. * @throws \yii\base\InvalidConfigException
  771. * @throws \yii\httpclient\Exception
  772. */
  773. public function generateDecOrderPDF() {
  774. $this->getParams();
  775. if (!$this->params) {
  776. throw new Exception('无法获取需要的参数');
  777. }
  778. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  779. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  780. $this->completed = false;
  781. $this->getExportId();
  782. $this->getUserId();
  783. $fileNameUpdated = false;
  784. // 获取列表数据及表头
  785. $this->_listModel = new $this->listModelClass();
  786. $this->_listModel->isExport = true;
  787. // 查询订单数据
  788. // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
  789. $orderQuery = Order::find()
  790. ->alias('O')
  791. ->where($this->params['condition'], $this->params['params'])
  792. ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
  793. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  794. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  795. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  796. ->orderBy('O.CREATED_AT DESC');
  797. // 订单中间表只查询待支付和支付失败的订单
  798. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  799. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  800. $orderStandardQuery = ApproachOrder::find()
  801. ->alias('O')
  802. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  803. ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
  804. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  805. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  806. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  807. ->orderBy('O.CREATED_AT DESC');
  808. $queryAll = $orderQuery->union($orderStandardQuery, true);
  809. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  810. $oderList = $query->all();
  811. if ($oderList) {
  812. $userId = '';
  813. $userName = '';
  814. $address = '';
  815. $mobile = '';
  816. $orderAt = '';
  817. $orderDetails = '';
  818. $orderSn = '';
  819. $orderAmount = 0; // 合计总额
  820. $orderNums = 0; // 合计总数
  821. $totalTaxAmount = 0; // 合计税额
  822. $totalAmount = 0;
  823. foreach ($oderList as $key => $value) {
  824. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  825. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  826. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  827. $userId = $value['USER_NAME'];
  828. $userName = $value['REAL_NAME'];
  829. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  830. $mobile = $value['MOBILE'];
  831. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  832. $orderSn = $value['SN'];
  833. // 总价
  834. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  835. $orderAmount += $totalAmount;
  836. $orderNums += $value['BUY_NUMS'];
  837. // 税额
  838. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  839. $totalTaxAmount += $taxAmount;
  840. $taxAmount = Tool::formatAmount($taxAmount);
  841. $totalAmount = Tool::formatAmount($totalAmount);
  842. // 订单详情
  843. $orderDetails .= <<<EOT
  844. <tr>
  845. <td>{$value['SKU_CODE']}</td>
  846. <td>{$value['GOODS_TITLE']}</td>
  847. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  848. <td>{$value['BUY_NUMS']}</td>
  849. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  850. <td style="text-align: right;">{$taxAmount}</td>
  851. <td style="text-align: right;">{$totalAmount}</td>
  852. </tr>
  853. EOT;
  854. }
  855. // 订单基本信息
  856. $orderBase = <<<ORDER
  857. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  858. <tr>
  859. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Code</td>
  860. <td width="70%">{$userId}</td>
  861. </tr>
  862. <tr>
  863. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Name</td>
  864. <td width="70%">{$userName}</td>
  865. </tr>
  866. <tr>
  867. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Address</td>
  868. <td width="70%">{$address}</td>
  869. </tr>
  870. <tr>
  871. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Phone</td>
  872. <td width="70%">{$mobile}</td>
  873. </tr>
  874. <tr>
  875. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order Code</td>
  876. <td width="70%">{$orderSn}</td>
  877. </tr>
  878. <tr>
  879. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation Time</td>
  880. <td width="70%">{$orderAt}</td>
  881. </tr>
  882. <tr>
  883. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order Detail</td>
  884. <td class="bg"></td>
  885. </tr>
  886. </table>
  887. ORDER;
  888. $l['a_meta_charset'] = 'UTF-8';
  889. $l['a_meta_dir'] = 'ltr';
  890. $l['a_meta_language'] = 'zh';
  891. $l['w_page'] = '页面';
  892. $orderAmount = Tool::formatAmount($orderAmount);
  893. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  894. $context = <<<ORDER
  895. <!doctype html>
  896. <html lang="en">
  897. <head>
  898. <meta charset="UTF-8" />
  899. <title>Order detail</title>
  900. <style>
  901. table {
  902. border-collapse: collapse;
  903. }
  904. table td, table th {
  905. border: 1px solid #ccc;
  906. padding: 5px 5px;
  907. border-collapse: collapse;
  908. }
  909. /*td {*/
  910. /* padding: 120px;*/
  911. /*}*/
  912. .bg {
  913. background-color: #ccc;
  914. }
  915. </style>
  916. </head>
  917. <body>
  918. <div class="content">
  919. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
  920. <div>
  921. <div style="display: block; width: 100%;">
  922. {$orderBase}
  923. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  924. <tr>
  925. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Code</th>
  926. <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Name</th>
  927. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Price</th>
  928. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
  929. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax Rate</th>
  930. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
  931. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total Amount</th>
  932. </tr>
  933. {$orderDetails}
  934. <tr>
  935. <td colspan="3">Total</td>
  936. <td>{$orderNums}</td>
  937. <td></td>
  938. <td style="text-align: right;">{$totalTaxAmount}</td>
  939. <td style="text-align: right;">{$orderAmount}</td>
  940. </tr>
  941. </table>
  942. </div>
  943. <div style="width: 100%; margin-top: 50px; height: 30px;">
  944. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  945. <tr style="border: none;">
  946. <td width="70%" style="border: none;"></td>
  947. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
  948. </tr>
  949. <tr style="border: none;">
  950. <td width="70%" style="border: none;"></td>
  951. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
  952. </tr>
  953. </table>
  954. </div>
  955. </div>
  956. </div>
  957. </body>
  958. </html>
  959. ORDER;
  960. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  961. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  962. // 设置打印模式
  963. $pdf->SetCreator(PDF_CREATOR);
  964. $pdf->SetAuthor('DaZe');
  965. $pdf->SetTitle($orderSn);
  966. $pdf->SetSubject('TCPDF Tutorial');
  967. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  968. // 是否显示页眉
  969. $pdf->setPrintHeader(false);
  970. // 设置页眉字体
  971. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  972. // 页眉距离顶部的距离
  973. $pdf->SetHeaderMargin('5');
  974. // 是否显示页脚
  975. $pdf->setPrintFooter(false);
  976. // 设置默认等宽字体
  977. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  978. // 设置行高
  979. $pdf->setCellHeightRatio(1);
  980. // 设置左、上、右的间距
  981. $pdf->SetMargins('10', '10', '10');
  982. // 设置是否自动分页 距离底部多少距离时分页
  983. $pdf->SetAutoPageBreak(TRUE, '15');
  984. // 设置图像比例因子
  985. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  986. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  987. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  988. $pdf->setLanguageArray($l);
  989. }
  990. $pdf->setFontSubsetting(true);
  991. $pdf->AddPage();
  992. // 设置字体
  993. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  994. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  995. $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
  996. $pdf->Image('@' . $image, 165, 5, 20, 10, 'JPG');
  997. $pdf->writeHTML($context);
  998. $pdf->Output($realFile, 'F');
  999. $this->_updateFirst($realFile, 1);
  1000. }
  1001. $this->complete();
  1002. return true;
  1003. }
  1004. /**
  1005. * 循环写入数据
  1006. * @param $realFile
  1007. * @param $fileNameUpdated
  1008. * @param int $page
  1009. * @param int $counter
  1010. * @return array
  1011. * @throws Exception
  1012. */
  1013. private function _loopWriteDataPDF($realFile, &$fileNameUpdated, $page = 0, $counter = 0){
  1014. if(method_exists($this->_listModel, 'getList')){
  1015. $list = $this->_listModel->getList(['condition'=>$this->params['condition'], 'params'=>isset($this->params['params']) ? $this->params['params'] : [], 'others'=>isset($this->params['others']) ? $this->params['others'] : [], 'page'=>$page, 'pageSize'=>$this->pageSize, 'userId'=>$this->userId]);
  1016. } else {
  1017. throw new Exception($this->listModelClass.'的getList方法不存在');
  1018. }
  1019. return $list['list'];
  1020. }
  1021. }