BaseExport.php 45 KB

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