BaseExport.php 45 KB

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