ImportService.php 8.3 KB

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