ImportService.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. <?php
  2. namespace App\Service;
  3. use App\Exports\TableHeadExport;
  4. use App\Import\ImportAll;
  5. use App\Model\Freight;
  6. use App\Model\Product;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Log;
  9. use Maatwebsite\Excel\Facades\Excel;
  10. use PhpOffice\PhpSpreadsheet\IOFactory;
  11. use PhpOffice\PhpSpreadsheet\Shared\Date;
  12. class ImportService extends Service
  13. {
  14. public static $type = [
  15. 'product', //存货
  16. 'freight', //运费设置
  17. ];
  18. public function getTableTitleXls($data,$user){
  19. if(empty($data['type'])) return [false,'缺少类型'];
  20. if(! in_array($data['type'],self::$type)) return [false,'类型不存在'];
  21. //获取配置文件
  22. $fuc = $data['type'];
  23. list($status,$return) = $this->$fuc($data,$user);
  24. list($msg,$filename) = $return;
  25. if(! $status) return [false, $msg];
  26. $headers = array_column($msg,'value');
  27. Excel::store(new TableHeadExport([], $headers),"/public/export/{$filename}", null, 'Xlsx', []);
  28. return [true, ['file' => $filename]];
  29. }
  30. private function getTableConfig($type = ""){
  31. if(empty($type)) return [];
  32. //获取配置文件
  33. $config = "excel." . $type . "Table";
  34. return config($config) ?? [];
  35. }
  36. private function product($data,$user){
  37. $config_array = $this->getTableConfig($data['type']);
  38. if(empty($config_array)) return [false, ['导入配置表头文件不存在','']];
  39. //生成下载文件
  40. $filename = "存货导入模板_" . time() . '.' . 'xlsx';
  41. return [true, [$config_array, $filename]];
  42. }
  43. private function freight($data,$user){
  44. $config_array = $this->getTableConfig($data['type']);
  45. if(empty($config_array)) return [false, ['导入配置表头文件不存在','']];
  46. //生成下载文件
  47. $filename = "运费设置导入模板_" . time() . '.' . 'xlsx';
  48. return [true, [$config_array, $filename]];
  49. }
  50. //导入入口
  51. public function importAll($data,$user){
  52. // //不超时
  53. // ini_set('max_execution_time', 0);
  54. // //内存设置
  55. // ini_set('memory_limit', -1);
  56. // $reader = IOFactory::createReader('Xlsx');
  57. // $reader->setReadDataOnly(true); // 只读取有数据的单元格
  58. // $spreadsheet = $reader->load($data['file']);
  59. // dd($spreadsheet);
  60. // // 创建一个Reader对象
  61. // $reader = IOFactory::createReader('Xlsx'); // 根据你的文件格式选择合适的reader
  62. //
  63. //// 加载Excel文件
  64. // $spreadsheet = $reader->load($data['file']);
  65. //
  66. //// 获取第一个工作表
  67. // $worksheet = $spreadsheet->getActiveSheet();
  68. //
  69. //// 获取总行数
  70. // $totalRows = $worksheet->getHighestRow();dd($totalRows);
  71. if(empty($data['type'])) return [false,'缺少导入类型,导入失败'];
  72. if(! in_array($data['type'],self::$type)) return [false,'导入类型不存在,导入失败'];
  73. if(empty($data['file'])) return [false,'导入文件不能为空'];
  74. try {
  75. $import = new ImportAll();
  76. //设置导入人id
  77. $import->setCrt($user['id']);
  78. $import->setUser($user);
  79. $import->setType($data['type']);
  80. $other = $data;
  81. unset($other['file']);
  82. $import->setOtherParam($other);
  83. //导入
  84. \Maatwebsite\Excel\Facades\Excel::import($import,$data['file']);
  85. if($import->getMsg()) {
  86. $bool = $import->getIsLongText();
  87. if($bool) {
  88. return [0, $import->getMsg()];
  89. }else{
  90. return [false, $import->getMsg()];
  91. }
  92. }
  93. }catch (\Throwable $exception) {
  94. return [false, $exception->getMessage() . ' (Code: ' . $exception->getCode() . ', Line: ' . $exception->getLine() . ')'];
  95. }
  96. return [true, ''];
  97. }
  98. public function productImport($array, $user, $other_param){
  99. $upload = $array[0];
  100. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  101. if(! $status) return [false, $msg];
  102. $table_config = $msg;
  103. // 去除表头
  104. unset($array[0]);
  105. if(empty($array)) return [false, '导入数据不能为空'];
  106. list($array, $error) = $this->checkCommon($array, $table_config);
  107. if(! empty($error)) return [0, $error];
  108. if(empty($array)) return [false, '导入数据不能为空'];
  109. //查找产品
  110. $product_map = Product::whereIn("code", array_column($array,0))
  111. ->where('del_time',0)
  112. ->pluck('id','code')
  113. ->toArray();
  114. $time = time();
  115. $insert = $update = [];
  116. foreach ($array as $value){
  117. $tmp = [];
  118. foreach ($value as $k => $val){
  119. $field = $table_config[$k]['key'];
  120. $tmp[$field] = $val;
  121. }
  122. if(isset($product_map[$tmp['code']])){
  123. $product_id = $product_map[$tmp['code']];
  124. //产品主表
  125. $update[$product_id] = $tmp;
  126. }else{
  127. $tmp['crt_id'] = $user['id'];
  128. $tmp['crt_time'] = $time;
  129. //产品主表
  130. $insert[$tmp['code']] = $tmp;
  131. }
  132. }
  133. try{
  134. //新增
  135. if(! empty($insert)){
  136. Product::insert($insert);
  137. }
  138. //编辑
  139. if(! empty($update)){
  140. foreach ($update as $p_id => $value){
  141. Product::where('id',$p_id)
  142. ->update($value);
  143. }
  144. }
  145. DB::commit();
  146. }catch (\Exception $e){
  147. DB::rollBack();
  148. return [false, $e->getMessage() . $e->getLine() . $e->getCode()];
  149. }
  150. return [true, ''];
  151. }
  152. public function freightImport($array, $user, $other_param){
  153. $upload = $array[0];
  154. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  155. if(! $status) return [false, $msg];
  156. $table_config = $msg;
  157. // 去除表头
  158. unset($array[0]);
  159. if(empty($array)) return [false, '导入数据不能为空'];
  160. list($array, $error) = $this->checkCommon($array, $table_config);
  161. if(! empty($error)) return [0, $error];
  162. if(empty($array)) return [false, '导入数据不能为空'];
  163. $time = time();
  164. $insert = [];
  165. foreach ($array as $value){
  166. $tmp = [];
  167. foreach ($value as $k => $val){
  168. $field = $table_config[$k]['key'];
  169. $tmp[$field] = $val;
  170. }
  171. $tmp['crt_id'] = $user['id'];
  172. $tmp['crt_time'] = $time;
  173. //产品主表
  174. $insert[] = $tmp;
  175. }
  176. try{
  177. Freight::where('del_time',0)
  178. ->update(['del_time' => $time]);
  179. //新增
  180. if(! empty($insert)) Freight::insert($insert);
  181. DB::commit();
  182. }catch (\Exception $e){
  183. DB::rollBack();
  184. return [false, $e->getMessage() . $e->getLine() . $e->getCode()];
  185. }
  186. return [true, ''];
  187. }
  188. //公共校验
  189. private function checkCommon($array, $table_config){
  190. $error = [];
  191. $uniqueValues = []; // 用于存储需要唯一性检查的值
  192. // 第一次遍历:收集所有唯一字段的值
  193. foreach ($array as $key => $value) {
  194. foreach ($value as $k => $v) {
  195. if (isset($table_config[$k]) && ! empty($table_config[$k]['unique'])) {
  196. $uniqueValues[$k][] = [
  197. 'value' => trim($v),
  198. 'line' => $key
  199. ];
  200. }
  201. }
  202. }
  203. // 检查唯一性
  204. foreach ($uniqueValues as $column => $values) {
  205. $valueCount = [];
  206. foreach ($values as $item) {
  207. $valueCount[$item['value']][] = $item['line'];
  208. }
  209. foreach ($valueCount as $value => $lines) {
  210. if (count($lines) > 1) {
  211. $lineNumbers = implode(',', $lines);
  212. $error[] = $table_config[$column]['value'] . "重复,在第{$lineNumbers}行出现重复值:{$value}";
  213. }
  214. }
  215. }
  216. // 第二次遍历:进行其他验证
  217. foreach ($array as $key => $value){
  218. $line = '第' . $key . '行';
  219. $rowData = array_filter($value);
  220. if (empty($rowData)) {
  221. unset($array[$key]);
  222. } else{
  223. foreach ($value as $k => $v){
  224. $row = '第' . $k . '列';
  225. $tmp_v = trim($v);
  226. if(! isset($table_config[$k])){
  227. $error[] = $line . $row . "数据不存在";
  228. }else{
  229. $table_tmp = $table_config[$k] ?? [];
  230. if(! empty($table_tmp['required'])){
  231. if ($tmp_v === '' || ! isset($tmp_v)) {
  232. $error[] = $line . $table_tmp['value'] . "必填";
  233. }
  234. }
  235. }
  236. if(empty($tmp_v) && isset($table_tmp['default'])) $tmp_v = $table_tmp['default'];
  237. $value[$k] = $tmp_v;
  238. }
  239. $array[$key] = $value;
  240. }
  241. }
  242. $error_string = "";
  243. if(! empty($error)) $error_string = implode('|', $error);
  244. return [$array, $error_string];
  245. }
  246. //模板校验
  247. private function compareTableAndReturn($upload, $param){
  248. if(empty($upload)) return [false, '表头不能为空'];
  249. $config_array = $this->getTableConfig($param['type']);
  250. if(empty($config_array)) return [false, '导入配置表头文件不存在'];
  251. foreach ($config_array as $key => $value){
  252. $key_position = $key + 1;
  253. if(! isset($upload[$key])) return [false, "第" . $key_position . "列表头缺失"];
  254. $tmp_v = trim($upload[$key]);
  255. if($tmp_v != $value['value']) return [false, "第" . $key_position . "列表头与模板不符合,请重新下载模板"];
  256. }
  257. return [true, $config_array];
  258. }
  259. }