BaseExport.php 45 KB

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