BaseExport.php 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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. fputcsv($this->_fp, Tool::arrTextConvert($columnAccept));
  346. unset($percent, $columnData, $columnAccept);
  347. }
  348. unset($list);
  349. }
  350. unset($list);
  351. return 'finish';
  352. }
  353. /**
  354. * 完成
  355. * @return bool
  356. * @throws Exception
  357. * @throws \yii\base\InvalidConfigException
  358. * @throws \yii\httpclient\Exception
  359. */
  360. public function complete() {
  361. $this->_updatePercent(100);
  362. if ($this->completed) {
  363. return true;
  364. }
  365. if ($this->_fp) {
  366. fclose($this->_fp);
  367. }
  368. // 把导出的文件上传至静态文件服务器
  369. if ($this->isRemote) {
  370. $realFile = $this->getSaveBasePath() . __DS__ . $this->getSavePath() . __DS__ . $this->getFileName();
  371. $remoteUploadApi = RemoteUploadApi::instance();
  372. if ($uploadResult = $remoteUploadApi->upload($realFile)) {
  373. Export::updateAll(['REMOTE_URL' => $uploadResult['url'], 'IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
  374. } else {
  375. $this->_errorHandle();
  376. throw new Exception('文件远程上传失败');
  377. }
  378. // 删除本地临时文件
  379. unlink($realFile);
  380. } else {
  381. Export::updateAll(['IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
  382. }
  383. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin(100, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
  384. CacheHelper::deleteAsyncParams($this->taskId);
  385. $this->completed = true;
  386. }
  387. /**
  388. * @param $message
  389. */
  390. private function _errorNotice($message) {
  391. Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($this->userId, $message, false);
  392. }
  393. /**
  394. * 首次更新
  395. * @param $exportId
  396. * @param $realName
  397. */
  398. private function _updateFirst($realName, $percent) {
  399. $fileName = str_replace($this->getSaveBasePath() . __DS__, '', $realName);
  400. Export::updateAll([
  401. 'FILE_NAME' => str_replace(__DS__, '/', $fileName),
  402. 'UPDATED_AT' => Date::nowTime(),
  403. 'EXPORT_PERCENT' => $percent,
  404. ], 'ID=:ID', [':ID' => $this->exportId]);
  405. }
  406. /**
  407. * 更新百分比
  408. * @param $exportId
  409. * @param $percent
  410. */
  411. private function _updatePercent($percent) {
  412. // 把数据写入数据库中
  413. Export::updateAll(['EXPORT_PERCENT' => $percent], 'ID=:ID', [':ID' => $this->exportId]);
  414. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
  415. }
  416. /**
  417. * 发生错误处理
  418. * @param $exportId
  419. */
  420. private function _errorHandle() {
  421. Export::updateAll(['IS_EXPORTING' => 0], 'ID=:ID', [':ID' => $this->exportId]);
  422. }
  423. /**
  424. * 导出逻辑
  425. * @param $filter
  426. * @param $listName
  427. * @param null $consoleRouter
  428. * @throws Exception
  429. */
  430. public function exportHandle($filter, $listName, $consoleRouter = null){
  431. $params = [
  432. 'moduleId' => $this->moduleId,
  433. 'listName' => $listName,
  434. 'action' => $consoleRouter ? $consoleRouter : Yii::$app->controller->id.'/'.Yii::$app->controller->action->id, // 这里这么写,是因为调用的异步路由和同步的控制器和方法是一样的,所以,只要不传默认调和同步一样的异步方法
  435. 'userId' => Yii::$app->user->id,
  436. ];
  437. $this->webToAsync($params,$filter);
  438. }
  439. /**
  440. * 页面到异步的请求
  441. * @param $params
  442. * @param array $extend
  443. * @return bool
  444. * @throws Exception
  445. */
  446. public function webToAsync($params, $extend = []) {
  447. $default = [
  448. 'moduleId' => null,
  449. 'listName' => null,
  450. 'remark' => null,
  451. 'action' => null,
  452. 'userId' => null,
  453. ];
  454. $params = Tool::deepParse($params, $default);
  455. if (!$params['moduleId'] || !$params['listName'] || !$params['action']) {
  456. throw new Exception('请设置moduleId,listName和action');
  457. }
  458. // 把文件对应的相关资料存入数据库中
  459. $export = new Export();
  460. $export->EXPORT_NAME = $params['listName'] . '_' . date('Exp_y-m-d H:i:s', Date::nowTime());
  461. $export->MODULE_NAME = $params['moduleId'];
  462. $export->REMARK = $params['remark'];
  463. $export->IS_EXPORTING = 1;
  464. $export->ADMIN_ID = \Yii::$app->user->id;
  465. $export->STARTED_AT = Date::nowTime();
  466. $export->CREATED_AT = Date::nowTime();
  467. $export->EXPORT_PERCENT = 0;
  468. $export->ENDED_AT = 0;
  469. $export->UPDATED_AT = 0;
  470. if (!$export->save()) {
  471. throw new Exception(Form::formatErrorsForApi($export->getErrors()));
  472. }
  473. $extend = array_merge($extend, [
  474. 'exportId' => $export->ID,
  475. 'userId' => $params['userId'],
  476. ]);
  477. // 异步处理添加任务
  478. $taskKey = \Yii::$app->swooleAsyncTimer->asyncHandle($params['action'], $extend);
  479. if($taskKey === false){
  480. // 删除刚刚添加的导出数据
  481. Export::deleteAll(['ID'=>$export->ID]);
  482. throw new Exception('导出失败,请求异步处理服务器失败');
  483. }
  484. return $taskKey;
  485. }
  486. /**
  487. * 生成
  488. * @return bool
  489. * @throws Exception
  490. * @throws \yii\base\InvalidConfigException
  491. * @throws \yii\httpclient\Exception
  492. */
  493. public function generateOrderExcel() {
  494. $this->getParams();
  495. if (!$this->params) {
  496. throw new Exception('无法获取需要的参数');
  497. }
  498. $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  499. $path = __DS__ . $path;
  500. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
  501. $this->completed = false;
  502. $this->getExportId();
  503. $this->getUserId();
  504. $fileNameUpdated = false;
  505. $this->_fp = fopen($realFile, 'w');
  506. @exec('chown -R www:www /'.$realFile);
  507. @exec('chmod -R 777 /'.$realFile);
  508. // 获取列表数据及表头
  509. $this->_listModel = new $this->listModelClass();
  510. $this->_listModel->isExport = true;
  511. if(method_exists($this->_listModel, 'getExportHeaders')){
  512. if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
  513. $this->_listModel->exportPrepare(['condition' => $this->params['condition'], 'params' => $this->params['params'], 'others' => $this->params['others'] ?? [], 'page' => 0, 'pageSize' => 100000, 'userId' => $this->userId]);
  514. }
  515. $headers = $this->_listModel->getExportHeaders($this->userId);
  516. fputcsv($this->_fp, $headers);
  517. unset($headers);
  518. $this->_updateFirst($realFile, 1);
  519. } else {
  520. throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
  521. }
  522. $this->_loopWriteDataOrder();
  523. $this->complete();
  524. return true;
  525. }
  526. /**
  527. * 生成
  528. * @return bool
  529. * @throws Exception
  530. * @throws \yii\base\InvalidConfigException
  531. * @throws \yii\httpclient\Exception
  532. */
  533. public function generateOrderPDF() {
  534. $this->getParams();
  535. if (!$this->params) {
  536. throw new Exception('无法获取需要的参数');
  537. }
  538. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  539. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  540. $this->completed = false;
  541. $this->getExportId();
  542. $this->getUserId();
  543. $fileNameUpdated = false;
  544. // 获取列表数据及表头
  545. $this->_listModel = new $this->listModelClass();
  546. $this->_listModel->isExport = true;
  547. // 查询订单数据
  548. // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
  549. $orderQuery = Order::find()
  550. ->alias('O')
  551. ->where($this->params['condition'], $this->params['params'])
  552. ->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')
  553. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  554. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  555. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  556. ->orderBy('O.CREATED_AT DESC');
  557. // 订单中间表只查询待支付和支付失败的订单
  558. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  559. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  560. $orderStandardQuery = ApproachOrder::find()
  561. ->alias('O')
  562. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  563. ->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')
  564. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  565. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  566. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  567. ->orderBy('O.CREATED_AT DESC');
  568. $queryAll = $orderQuery->union($orderStandardQuery, true);
  569. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  570. $oderList = $query->all();
  571. if ($oderList) {
  572. $userId = '';
  573. $userName = '';
  574. $address = '';
  575. $mobile = '';
  576. $orderAt = '';
  577. $orderDetails = '';
  578. $orderSn = '';
  579. $orderAmount = 0; // 合计总额
  580. $orderNums = 0; // 合计总数
  581. $totalTaxAmount = 0; // 合计税额
  582. $totalAmount = 0;
  583. foreach ($oderList as $key => $value) {
  584. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  585. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  586. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  587. $userId = $value['USER_NAME'];
  588. $userName = $value['REAL_NAME'];
  589. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  590. $mobile = $value['MOBILE'];
  591. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  592. $orderSn = $value['SN'];
  593. // 总价
  594. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  595. $orderAmount += $totalAmount;
  596. $orderNums += $value['BUY_NUMS'];
  597. // 税额
  598. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  599. $totalTaxAmount += $taxAmount;
  600. $taxAmount = Tool::formatAmount($taxAmount);
  601. $totalAmount = Tool::formatAmount($totalAmount);
  602. // 订单详情
  603. $orderDetails .= <<<EOT
  604. <tr>
  605. <td>{$value['SKU_CODE']}</td>
  606. <td>{$value['GOODS_TITLE']}</td>
  607. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  608. <td>{$value['BUY_NUMS']}</td>
  609. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  610. <td style="text-align: right;">{$taxAmount}</td>
  611. <td style="text-align: right;">{$totalAmount}</td>
  612. </tr>
  613. EOT;
  614. }
  615. // 订单基本信息
  616. $orderBase = <<<ORDER
  617. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  618. <tr>
  619. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member code</td>
  620. <td width="70%">{$userId}</td>
  621. </tr>
  622. <tr>
  623. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member name</td>
  624. <td width="70%">{$userName}</td>
  625. </tr>
  626. <tr>
  627. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member address</td>
  628. <td width="70%">{$address}</td>
  629. </tr>
  630. <tr>
  631. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member phone</td>
  632. <td width="70%">{$mobile}</td>
  633. </tr>
  634. <tr>
  635. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order code</td>
  636. <td width="70%">{$orderSn}</td>
  637. </tr>
  638. <tr>
  639. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation time</td>
  640. <td width="70%">{$orderAt}</td>
  641. </tr>
  642. <tr>
  643. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order detail</td>
  644. <td class="bg"></td>
  645. </tr>
  646. </table>
  647. ORDER;
  648. $l['a_meta_charset'] = 'UTF-8';
  649. $l['a_meta_dir'] = 'ltr';
  650. $l['a_meta_language'] = 'zh';
  651. $l['w_page'] = '页面';
  652. $orderAmount = Tool::formatAmount($orderAmount);
  653. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  654. $context = <<<ORDER
  655. <!doctype html>
  656. <html lang="en">
  657. <head>
  658. <meta charset="UTF-8" />
  659. <title>Order detail</title>
  660. <style>
  661. table {
  662. border-collapse: collapse;
  663. }
  664. table td, table th {
  665. border: 1px solid #ccc;
  666. padding: 5px 5px;
  667. border-collapse: collapse;
  668. }
  669. /*td {*/
  670. /* padding: 120px;*/
  671. /*}*/
  672. .bg {
  673. background-color: #ccc;
  674. }
  675. </style>
  676. </head>
  677. <body>
  678. <div class="content">
  679. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
  680. <div>
  681. <div style="display: block; width: 100%;">
  682. {$orderBase}
  683. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  684. <tr>
  685. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Code</th>
  686. <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Name</th>
  687. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Price</th>
  688. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
  689. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax Rate</th>
  690. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
  691. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total Amount</th>
  692. </tr>
  693. {$orderDetails}
  694. <tr>
  695. <td colspan="3">Total</td>
  696. <td>{$orderNums}</td>
  697. <td></td>
  698. <td style="text-align: right;">{$totalTaxAmount}</td>
  699. <td style="text-align: right;">{$orderAmount}</td>
  700. </tr>
  701. </table>
  702. </div>
  703. <div style="width: 100%; margin-top: 50px; height: 30px;">
  704. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  705. <tr style="border: none;">
  706. <td width="70%" style="border: none;"></td>
  707. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
  708. </tr>
  709. <tr style="border: none;">
  710. <td width="70%" style="border: none;"></td>
  711. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
  712. </tr>
  713. </table>
  714. </div>
  715. </div>
  716. </div>
  717. </body>
  718. </html>
  719. ORDER;
  720. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  721. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  722. // 设置打印模式
  723. $pdf->SetCreator(PDF_CREATOR);
  724. $pdf->SetAuthor('DaZe');
  725. $pdf->SetTitle($orderSn);
  726. $pdf->SetSubject('TCPDF Tutorial');
  727. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  728. // 是否显示页眉
  729. $pdf->setPrintHeader(false);
  730. // 设置页眉字体
  731. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  732. // 页眉距离顶部的距离
  733. $pdf->SetHeaderMargin('5');
  734. // 是否显示页脚
  735. $pdf->setPrintFooter(false);
  736. // 设置默认等宽字体
  737. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  738. // 设置行高
  739. $pdf->setCellHeightRatio(1);
  740. // 设置左、上、右的间距
  741. $pdf->SetMargins('10', '0', '10');
  742. // 设置是否自动分页 距离底部多少距离时分页
  743. $pdf->SetAutoPageBreak(TRUE, '15');
  744. // 设置图像比例因子
  745. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  746. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  747. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  748. $pdf->setLanguageArray($l);
  749. }
  750. $pdf->setFontSubsetting(true);
  751. $pdf->AddPage();
  752. // 设置字体
  753. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  754. $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
  755. $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
  756. $pdf->writeHTML($context);
  757. $pdf->Output($realFile, 'F');
  758. $this->_updateFirst($realFile, 1);
  759. }
  760. $this->complete();
  761. return true;
  762. }
  763. /**
  764. * 生成
  765. * @return bool
  766. * @throws Exception
  767. * @throws \yii\base\InvalidConfigException
  768. * @throws \yii\httpclient\Exception
  769. */
  770. public function generateDecOrderPDF() {
  771. $this->getParams();
  772. if (!$this->params) {
  773. throw new Exception('无法获取需要的参数');
  774. }
  775. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  776. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  777. $this->completed = false;
  778. $this->getExportId();
  779. $this->getUserId();
  780. $fileNameUpdated = false;
  781. // 获取列表数据及表头
  782. $this->_listModel = new $this->listModelClass();
  783. $this->_listModel->isExport = true;
  784. // 查询订单数据
  785. // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
  786. $orderQuery = Order::find()
  787. ->alias('O')
  788. ->where($this->params['condition'], $this->params['params'])
  789. ->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')
  790. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  791. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  792. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  793. ->orderBy('O.CREATED_AT DESC');
  794. // 订单中间表只查询待支付和支付失败的订单
  795. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  796. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  797. $orderStandardQuery = ApproachOrder::find()
  798. ->alias('O')
  799. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  800. ->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')
  801. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  802. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  803. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  804. ->orderBy('O.CREATED_AT DESC');
  805. $queryAll = $orderQuery->union($orderStandardQuery, true);
  806. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  807. $oderList = $query->all();
  808. if ($oderList) {
  809. $userId = '';
  810. $userName = '';
  811. $address = '';
  812. $mobile = '';
  813. $orderAt = '';
  814. $orderDetails = '';
  815. $orderSn = '';
  816. $orderAmount = 0; // 合计总额
  817. $orderNums = 0; // 合计总数
  818. $totalTaxAmount = 0; // 合计税额
  819. $totalAmount = 0;
  820. foreach ($oderList as $key => $value) {
  821. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  822. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  823. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  824. $userId = $value['USER_NAME'];
  825. $userName = $value['REAL_NAME'];
  826. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  827. $mobile = $value['MOBILE'];
  828. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  829. $orderSn = $value['SN'];
  830. // 总价
  831. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  832. $orderAmount += $totalAmount;
  833. $orderNums += $value['BUY_NUMS'];
  834. // 税额
  835. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  836. $totalTaxAmount += $taxAmount;
  837. $taxAmount = Tool::formatAmount($taxAmount);
  838. $totalAmount = Tool::formatAmount($totalAmount);
  839. // 订单详情
  840. $orderDetails .= <<<EOT
  841. <tr>
  842. <td>{$value['SKU_CODE']}</td>
  843. <td>{$value['GOODS_TITLE']}</td>
  844. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  845. <td>{$value['BUY_NUMS']}</td>
  846. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  847. <td style="text-align: right;">{$taxAmount}</td>
  848. <td style="text-align: right;">{$totalAmount}</td>
  849. </tr>
  850. EOT;
  851. }
  852. // 订单基本信息
  853. $orderBase = <<<ORDER
  854. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  855. <tr>
  856. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member code</td>
  857. <td width="70%">{$userId}</td>
  858. </tr>
  859. <tr>
  860. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member name</td>
  861. <td width="70%">{$userName}</td>
  862. </tr>
  863. <tr>
  864. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member address</td>
  865. <td width="70%">{$address}</td>
  866. </tr>
  867. <tr>
  868. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member phone</td>
  869. <td width="70%">{$mobile}</td>
  870. </tr>
  871. <tr>
  872. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order code</td>
  873. <td width="70%">{$orderSn}</td>
  874. </tr>
  875. <tr>
  876. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation time</td>
  877. <td width="70%">{$orderAt}</td>
  878. </tr>
  879. <tr>
  880. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order detail</td>
  881. <td class="bg"></td>
  882. </tr>
  883. </table>
  884. ORDER;
  885. $l['a_meta_charset'] = 'UTF-8';
  886. $l['a_meta_dir'] = 'ltr';
  887. $l['a_meta_language'] = 'zh';
  888. $l['w_page'] = '页面';
  889. $orderAmount = Tool::formatAmount($orderAmount);
  890. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  891. $context = <<<ORDER
  892. <!doctype html>
  893. <html lang="en">
  894. <head>
  895. <meta charset="UTF-8" />
  896. <title>Order detail</title>
  897. <style>
  898. table {
  899. border-collapse: collapse;
  900. }
  901. table td, table th {
  902. border: 1px solid #ccc;
  903. padding: 5px 5px;
  904. border-collapse: collapse;
  905. }
  906. /*td {*/
  907. /* padding: 120px;*/
  908. /*}*/
  909. .bg {
  910. background-color: #ccc;
  911. }
  912. </style>
  913. </head>
  914. <body>
  915. <div class="content">
  916. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
  917. <div>
  918. <div style="display: block; width: 100%;">
  919. {$orderBase}
  920. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  921. <tr>
  922. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Code</th>
  923. <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Name</th>
  924. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Price</th>
  925. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
  926. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax Rate</th>
  927. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
  928. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total Amount</th>
  929. </tr>
  930. {$orderDetails}
  931. <tr>
  932. <td colspan="3">Total</td>
  933. <td>{$orderNums}</td>
  934. <td></td>
  935. <td style="text-align: right;">{$totalTaxAmount}</td>
  936. <td style="text-align: right;">{$orderAmount}</td>
  937. </tr>
  938. </table>
  939. </div>
  940. <div style="width: 100%; margin-top: 50px; height: 30px;">
  941. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  942. <tr style="border: none;">
  943. <td width="70%" style="border: none;"></td>
  944. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
  945. </tr>
  946. <tr style="border: none;">
  947. <td width="70%" style="border: none;"></td>
  948. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
  949. </tr>
  950. </table>
  951. </div>
  952. </div>
  953. </div>
  954. </body>
  955. </html>
  956. ORDER;
  957. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  958. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  959. // 设置打印模式
  960. $pdf->SetCreator(PDF_CREATOR);
  961. $pdf->SetAuthor('DaZe');
  962. $pdf->SetTitle($orderSn);
  963. $pdf->SetSubject('TCPDF Tutorial');
  964. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  965. // 是否显示页眉
  966. $pdf->setPrintHeader(false);
  967. // 设置页眉字体
  968. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  969. // 页眉距离顶部的距离
  970. $pdf->SetHeaderMargin('5');
  971. // 是否显示页脚
  972. $pdf->setPrintFooter(false);
  973. // 设置默认等宽字体
  974. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  975. // 设置行高
  976. $pdf->setCellHeightRatio(1);
  977. // 设置左、上、右的间距
  978. $pdf->SetMargins('10', '10', '10');
  979. // 设置是否自动分页 距离底部多少距离时分页
  980. $pdf->SetAutoPageBreak(TRUE, '15');
  981. // 设置图像比例因子
  982. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  983. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  984. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  985. $pdf->setLanguageArray($l);
  986. }
  987. $pdf->setFontSubsetting(true);
  988. $pdf->AddPage();
  989. // 设置字体
  990. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  991. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  992. $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
  993. $pdf->Image('@' . $image, 165, 5, 20, 10, 'JPG');
  994. $pdf->writeHTML($context);
  995. $pdf->Output($realFile, 'F');
  996. $this->_updateFirst($realFile, 1);
  997. }
  998. $this->complete();
  999. return true;
  1000. }
  1001. /**
  1002. * 循环写入数据
  1003. * @param $realFile
  1004. * @param $fileNameUpdated
  1005. * @param int $page
  1006. * @param int $counter
  1007. * @return array
  1008. * @throws Exception
  1009. */
  1010. private function _loopWriteDataPDF($realFile, &$fileNameUpdated, $page = 0, $counter = 0){
  1011. if(method_exists($this->_listModel, 'getList')){
  1012. $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]);
  1013. } else {
  1014. throw new Exception($this->listModelClass.'的getList方法不存在');
  1015. }
  1016. return $list['list'];
  1017. }
  1018. }