BaseExport.php 45 KB

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