Areas.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. <?php
  2. namespace app\admin\controller\product;
  3. use app\common\controller\Backend;
  4. use Exception;
  5. use think\Db;
  6. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  7. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  8. use app\admin\model\Importregion;
  9. use app\admin\model\Importlog;
  10. use think\exception\DbException;
  11. use think\exception\PDOException;
  12. use think\exception\ValidateException;
  13. /**
  14. * 商品地区
  15. *
  16. * @icon fa fa-circle-o
  17. */
  18. class Areas extends Backend
  19. {
  20. /**
  21. * Areas模型对象
  22. * @var \app\common\model\ProductArea
  23. */
  24. protected $model = null;
  25. public function _initialize()
  26. {
  27. parent::_initialize();
  28. $this->model = new \app\common\model\ProductArea;
  29. $this->assignconfig('ids', $this->request->param('ids'));
  30. }
  31. /**
  32. * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
  33. * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
  34. * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
  35. */
  36. public function index()
  37. {
  38. //设置过滤方法
  39. $this->request->filter(['strip_tags', 'trim']);
  40. if (false === $this->request->isAjax()) {
  41. return $this->view->fetch();
  42. }
  43. //如果发送的来源是 Selectpage,则转发到 Selectpage
  44. if ($this->request->request('keyField')) {
  45. return $this->selectpage();
  46. }
  47. [$where, $sort, $order, $offset, $limit] = $this->buildparams();
  48. $product_id = $this->request->param('ids');
  49. $list = $this->model//->with('products')
  50. ->where($where)->where('product_id', $product_id)
  51. ->order($sort, $order)
  52. ->paginate($limit);
  53. $result = ['total' => $list->total(), 'rows' => $list->items()];
  54. return json($result);
  55. }
  56. /**
  57. * 添加
  58. *
  59. * @return string
  60. * @throws \think\Exception
  61. */
  62. public function add()
  63. {
  64. if (false === $this->request->isPost()) {
  65. return $this->view->fetch();
  66. }
  67. $params = $this->request->post('row/a');
  68. if (empty($params) || empty($params['province'])) {
  69. $this->error(__('Parameter %s can not be empty', ''));
  70. }
  71. $params = $this->preExcludeFields($params);
  72. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  73. $params[$this->dataLimitField] = $this->auth->id;
  74. }
  75. $result = false;
  76. Db::startTrans();
  77. try {
  78. //是否采用模型验证
  79. if ($this->modelValidate) {
  80. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  81. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  82. $this->model->validateFailException()->validate($validate);
  83. }
  84. $params['product_id'] = $this->request->param('ids');
  85. if($this->model::where('product_id', $params['product_id'])->where('address', $params['address'])->count() > 0) throw new ValidateException('商品关联区域已存在');
  86. $result = $this->model->allowField(true)->save($params);
  87. Db::commit();
  88. } catch (ValidateException|PDOException|Exception $e) {
  89. Db::rollback();
  90. $this->error($e->getMessage());
  91. }
  92. if ($result === false) {
  93. $this->error(__('No rows were inserted'));
  94. }
  95. $this->success();
  96. }
  97. /**
  98. * 导入产品地区
  99. * @param $ids
  100. * @return string
  101. * @throws DbException
  102. * @throws \think\Exception
  103. */
  104. public function exports(Importregion $importregion, Importlog $Importlog){
  105. if (false === $this->request->isPost()) {
  106. $this->assignconfig('areaData', []);
  107. return $this->view->fetch();
  108. }
  109. $params = $this->request->post('row/a');
  110. if (empty($params)) {
  111. $this->error(__('Parameter %s can not be empty', ''));
  112. }
  113. $params = $this->preExcludeFields($params);
  114. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  115. $params[$this->dataLimitField] = $this->auth->id;
  116. }
  117. $params['product_id'] = $this->request->param('ids');
  118. $file = $params['export'];
  119. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  120. if (!is_file($filePath)) {
  121. $this->error(__('No results were found'));
  122. }
  123. //实例化reader
  124. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  125. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  126. $this->error(__('Unknown data format'));
  127. }
  128. $reader = ($ext === 'xls')? new Xls(): new Xlsx();
  129. $result = false;
  130. Db::startTrans();
  131. try {
  132. if (!$PHPExcel = $reader->load($filePath)) {
  133. $this->error(__('Unknown data format'));
  134. }
  135. $PHPExcel = $reader->load($filePath);
  136. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  137. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  138. //读取第二行字段名
  139. $data = [];
  140. $fields = [];
  141. $k = 0;
  142. $i = 0;
  143. $time = time();
  144. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  145. $values = [];
  146. //列字段
  147. for ($currentColumn = 2999; $currentColumn <= 5; $currentColumn++) {
  148. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  149. $values[] = is_null($val) ? '' : $val;
  150. }
  151. if(empty($values[0])) continue;
  152. $field = implode('-', $values);
  153. $row = $importregion::where('name', $field)->find();
  154. if(!empty($row)){
  155. if($this->model::where('product_id',$params['product_id'])->where('address',$row['name'])->count() > 0) continue;
  156. $data = self::importData($data, $k, $params['product_id'], $row->com_id, $time);
  157. $data[$k]['address'] = $row['name'];
  158. $k +=1;
  159. }else{
  160. $fields = self::importData($fields, $i, $params['product_id'], $field, $time);
  161. $i += 1;
  162. }
  163. }
  164. if(!empty($data)) $result= $this->model::insertAll($data);
  165. //错误日志
  166. if(!empty($fields)) $Importlog::insertAll($fields);
  167. Db::commit();
  168. } catch (ValidateException|PDOException|Exception $e) {
  169. Db::rollback();
  170. $this->error($e->getMessage());
  171. }
  172. if ($result === false) {
  173. $this->error(__('No rows were inserted'));
  174. }
  175. $this->success();
  176. }
  177. /**
  178. * 导入数据
  179. * @return array
  180. */
  181. private static function importData(array $data, int $k, int $product_id, string $ids, $time): array
  182. {
  183. //$data = array();
  184. $arr = explode('-', $ids); //分割ID
  185. $data[$k]['product_id'] = $product_id;
  186. $data[$k]['province'] = $arr[0]??0;
  187. $data[$k]['city'] = $arr[1]??0 ;
  188. $data[$k]['area'] = $arr[2]??0;
  189. $data[$k]['county'] = $arr[3]??0;
  190. $data[$k]['create_time'] = $time;
  191. return $data;
  192. }
  193. }