Areas.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. *
  100. * @param $ids
  101. * @return void
  102. * @throws DbException
  103. * @throws DataNotFoundException
  104. * @throws ModelNotFoundException
  105. */
  106. public function del($ids = null)
  107. {
  108. if (false === $this->request->isPost()) {
  109. $this->error(__("Invalid parameters"));
  110. }
  111. $ids = $ids ?: $this->request->post("ids");
  112. if (empty($ids)) {
  113. $this->error(__('Parameter %s can not be empty', 'ids'));
  114. }
  115. $pk = $this->model->getPk();
  116. $adminIds = $this->getDataLimitAdminIds();
  117. if (is_array($adminIds)) {
  118. $this->model->where($this->dataLimitField, 'in', $adminIds);
  119. }
  120. $list = $this->model->where($pk, 'in', $ids)->select();
  121. $count = 0;
  122. if(in_array(0, array_column( $list, 'status')) ==true) $this->error(__('已出售区域不能删除', 'ids'));
  123. Db::startTrans();
  124. try {
  125. foreach ($list as $item) {
  126. $count += $item->delete();
  127. }
  128. Db::commit();
  129. } catch (PDOException|Exception $e) {
  130. Db::rollback();
  131. $this->error($e->getMessage());
  132. }
  133. if ($count) {
  134. $this->success();
  135. }
  136. $this->error(__('No rows were deleted'));
  137. }
  138. /**
  139. * 导入产品地区
  140. * @param $ids
  141. * @return string
  142. * @throws DbException
  143. * @throws \think\Exception
  144. */
  145. public function exports(Importregion $importregion, Importlog $Importlog){
  146. if (false === $this->request->isPost()) {
  147. $this->assignconfig('areaData', []);
  148. return $this->view->fetch();
  149. }
  150. $params = $this->request->post('row/a');
  151. if (empty($params)) {
  152. $this->error(__('Parameter %s can not be empty', ''));
  153. }
  154. $params = $this->preExcludeFields($params);
  155. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  156. $params[$this->dataLimitField] = $this->auth->id;
  157. }
  158. $params['product_id'] = $this->request->param('ids');
  159. $file = $params['export'];
  160. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  161. if (!is_file($filePath)) {
  162. $this->error(__('No results were found'));
  163. }
  164. //实例化reader
  165. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  166. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  167. $this->error(__('Unknown data format'));
  168. }
  169. $reader = ($ext === 'xls')? new Xls(): new Xlsx();
  170. $result = false;
  171. Db::startTrans();
  172. try {
  173. if (!$PHPExcel = $reader->load($filePath)) {
  174. $this->error(__('Unknown data format'));
  175. }
  176. $PHPExcel = $reader->load($filePath);
  177. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  178. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  179. //读取第二行字段名
  180. $data = [];
  181. $fields = [];
  182. $k = 0;
  183. $i = 0;
  184. $time = time();
  185. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  186. $values = [];
  187. //列字段
  188. for ($currentColumn = 2; $currentColumn <= 5; $currentColumn++) {
  189. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  190. $values[] = is_null($val) ? '' : $val;
  191. }
  192. if(empty($values[0])) continue;
  193. $field = implode('-', $values);
  194. $row = $importregion::where('name', $field)->find();
  195. if(!empty($row)){
  196. if($this->model::where('product_id',$params['product_id'])->where('address',$row['name'])->count() > 0) continue;
  197. $data = self::importData($data, $k, $params['product_id'], $row->com_id, $time);
  198. $data[$k]['address'] = $row['name'];
  199. $k +=1;
  200. }else{
  201. $fields = self::importData($fields, $i, $params['product_id'], $field, $time);
  202. $i += 1;
  203. }
  204. }
  205. if(!empty($data)) $result= $this->model::insertAll($data);
  206. //错误日志
  207. if(!empty($fields)) $Importlog::insertAll($fields);
  208. Db::commit();
  209. } catch (ValidateException|PDOException|Exception $e) {
  210. Db::rollback();
  211. $this->error($e->getMessage());
  212. }
  213. if ($result === false) {
  214. $this->error(__('No rows were inserted'));
  215. }
  216. $this->success();
  217. }
  218. /**
  219. * 导入数据
  220. * @return array
  221. */
  222. private static function importData(array $data, int $k, int $product_id, string $ids, $time): array
  223. {
  224. //$data = array();
  225. $arr = explode('-', $ids); //分割ID
  226. $data[$k]['product_id'] = $product_id;
  227. $data[$k]['province'] = $arr[0]??0;
  228. $data[$k]['city'] = $arr[1]??0 ;
  229. $data[$k]['area'] = $arr[2]??0;
  230. $data[$k]['county'] = $arr[3]??0;
  231. $data[$k]['create_time'] = $time;
  232. return $data;
  233. }
  234. }