Gift.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. <?php
  2. namespace app\admin\controller\egg;
  3. use app\common\controller\Backend;
  4. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  5. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  6. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  7. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  8. use think\Exception;
  9. use think\exception\PDOException;
  10. /**
  11. *
  12. *
  13. * @icon fa fa-circle-o
  14. */
  15. class Gift extends Backend
  16. {
  17. protected $searchFields = 'gift_id,gift_name';
  18. /**
  19. * Gift模型对象
  20. * @var \app\admin\model\egg\Gift
  21. */
  22. protected $model = null;
  23. public function _initialize()
  24. {
  25. parent::_initialize();
  26. $this->model = new \app\admin\model\egg\Gift;
  27. $this->view->assign("isUseList", $this->model->getIsUseList());
  28. }
  29. public function import()
  30. {
  31. $file = $this->request->request('file');
  32. if (!$file) {
  33. $this->error(__('Parameter %s can not be empty', 'file'));
  34. }
  35. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  36. if (!is_file($filePath)) {
  37. $this->error(__('No results were found'));
  38. }
  39. //实例化reader
  40. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  41. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  42. $this->error(__('Unknown data format'));
  43. }
  44. if ($ext === 'csv') {
  45. $file = fopen($filePath, 'r');
  46. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  47. $fp = fopen($filePath, "w");
  48. $n = 0;
  49. while ($line = fgets($file)) {
  50. $line = rtrim($line, "\n\r\0");
  51. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  52. if ($encoding != 'utf-8') {
  53. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  54. }
  55. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  56. fwrite($fp, $line . "\n");
  57. } else {
  58. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  59. }
  60. $n++;
  61. }
  62. fclose($file) || fclose($fp);
  63. $reader = new Csv();
  64. } elseif ($ext === 'xls') {
  65. $reader = new Xls();
  66. } else {
  67. $reader = new Xlsx();
  68. }
  69. //加载文件
  70. $insert = [];
  71. try {
  72. if (!$PHPExcel = $reader->load($filePath)) {
  73. $this->error(__('Unknown data format'));
  74. }
  75. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  76. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  77. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  78. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  79. // 获取奖池礼物表最后一条记录的ID
  80. $lastId = $this->model->order('id','desc')->value('id');
  81. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  82. $values = [];
  83. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  84. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  85. $values[] = is_null($val) ? '' : $val;
  86. }
  87. $giftInfo = \app\admin\model\gift\Gift::get($values[1]);
  88. if(!$giftInfo) $this->error('礼物ID:'.$values[1].'未找到对应礼物');
  89. for ($i = 0;$i<$values[2];$i++){
  90. $insert[] = [
  91. 'Jackpot_id' => $values[0],
  92. 'gift_id' => $values[1],
  93. 'image' => $giftInfo['image'],
  94. 'special' => $giftInfo['special'],
  95. 'gift_name' => $giftInfo['name'],
  96. 'price' => $giftInfo['price'],
  97. 'prize_no' => ++$lastId
  98. ];
  99. }
  100. }
  101. } catch (Exception $exception) {
  102. $this->error($exception->getMessage());
  103. }
  104. if (!$insert) {
  105. $this->error(__('No rows were updated'));
  106. }
  107. try {
  108. $this->model->saveAll($insert);
  109. } catch (PDOException $exception) {
  110. $msg = $exception->getMessage();
  111. if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  112. $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  113. };
  114. $this->error($msg);
  115. } catch (Exception $e) {
  116. $this->error($e->getMessage());
  117. }
  118. $this->success();
  119. }
  120. /**
  121. * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
  122. * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
  123. * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
  124. */
  125. /**
  126. * 列表
  127. */
  128. public function index()
  129. {
  130. //设置过滤方法
  131. $this->request->filter(['strip_tags', 'trim']);
  132. if ($this->request->isAjax()) {
  133. //如果发送的来源是Selectpage,则转发到Selectpage
  134. if ($this->request->request('keyField')) {
  135. return $this->selectpage();
  136. }
  137. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  138. $list = $this->model
  139. ->where($where)
  140. ->order($sort, $order)
  141. ->paginate($limit);
  142. $totalMoney = $this->model->where($where)->sum('price');
  143. $result = array("total" => $list->total(), "rows" => $list->items(), "extend" => ['total_price' => $totalMoney]);
  144. return json($result);
  145. }
  146. return $this->view->fetch();
  147. }
  148. }