ImportService.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. <?php
  2. namespace App\Service;
  3. use App\Exports\TableHeadExport;
  4. use App\Import\ImportAll;
  5. use App\Model\Device;
  6. use App\Model\Employee;
  7. use App\Model\Fee;
  8. use App\Model\Item;
  9. use App\Model\ItemDetails;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Log;
  12. use Maatwebsite\Excel\Facades\Excel;
  13. use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\F;
  14. use PhpOffice\PhpSpreadsheet\IOFactory;
  15. use PhpOffice\PhpSpreadsheet\Shared\Date;
  16. class ImportService extends Service
  17. {
  18. public static $type = [
  19. 'device', // 设备
  20. 'item', // 项目
  21. 'fee', // 费用
  22. ];
  23. public function getTableTitleXls($data,$user){
  24. if(empty($data['type'])) return [false,'缺少类型'];
  25. if(! in_array($data['type'],self::$type)) return [false,'类型不存在'];
  26. //获取配置文件
  27. $fuc = $data['type'];
  28. list($status,$return) = $this->$fuc($data,$user);
  29. list($msg,$filename) = $return;
  30. if(! $status) return [false, $msg];
  31. $headers = array_column($msg,'value');
  32. $comments = $enums = [];
  33. foreach ($msg as $value){
  34. if(! empty($value['comments'])) $comments[$value['value']] = $value['comments'];
  35. if(! empty($value['enums'])) $enums[$value['value']] = $value['enums'];
  36. }
  37. Excel::store(new TableHeadExport([], $headers, $comments, $enums),"/public/export/{$filename}", null, 'Xlsx', []);
  38. return [true, ['file' => $filename]];
  39. }
  40. private function getTableConfig($type = ""){
  41. if(empty($type)) return [];
  42. //获取配置文件
  43. $config = "excel." . $type;
  44. return config($config) ?? [];
  45. }
  46. private function device($data,$user){
  47. $config = $this->getTableConfig($data['type']);
  48. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  49. $config_array = $config['array'] ?? [];
  50. //生成下载文件
  51. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  52. return [true, [$config_array, $filename]];
  53. }
  54. private function item($data,$user){
  55. $config = $this->getTableConfig($data['type']);
  56. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  57. $config_array = $config['array'] ?? [];
  58. //生成下载文件
  59. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  60. return [true, [$config_array, $filename]];
  61. }
  62. private function fee($data,$user){
  63. $config = $this->getTableConfig($data['type']);
  64. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  65. $config_array = $config['array'] ?? [];
  66. //生成下载文件
  67. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  68. return [true, [$config_array, $filename]];
  69. }
  70. //导入入口
  71. public function importAll($data,$user){
  72. // //不超时
  73. // ini_set('max_execution_time', 0);
  74. // //内存设置
  75. // ini_set('memory_limit', -1);
  76. // $reader = IOFactory::createReader('Xlsx');
  77. // $reader->setReadDataOnly(true); // 只读取有数据的单元格
  78. // $spreadsheet = $reader->load($data['file']);
  79. // dd($spreadsheet);
  80. // // 创建一个Reader对象
  81. // $reader = IOFactory::createReader('Xlsx'); // 根据你的文件格式选择合适的reader
  82. //
  83. //// 加载Excel文件
  84. // $spreadsheet = $reader->load($data['file']);
  85. //
  86. //// 获取第一个工作表
  87. // $worksheet = $spreadsheet->getActiveSheet();
  88. //
  89. //// 获取总行数
  90. // $totalRows = $worksheet->getHighestRow();dd($totalRows);
  91. if(empty($data['type'])) return [false,'缺少导入类型,导入失败'];
  92. if(! in_array($data['type'],self::$type)) return [false,'导入类型不存在,导入失败'];
  93. if(empty($data['file'])) return [false,'导入文件不能为空'];
  94. try {
  95. $import = new ImportAll();
  96. //设置导入人id
  97. $import->setCrt($user['id']);
  98. $import->setUser($user);
  99. $import->setType($data['type']);
  100. $other = $data;
  101. unset($other['file']);
  102. $import->setOtherParam($other);
  103. //导入
  104. \Maatwebsite\Excel\Facades\Excel::import($import,$data['file']);
  105. if($import->getMsg()) {
  106. $bool = $import->getIsLongText();
  107. if($bool) {
  108. return [0, $import->getMsg()];
  109. }else{
  110. return [false, $import->getMsg()];
  111. }
  112. }
  113. }catch (\Throwable $exception) {
  114. return [false, $exception->getMessage() . ' (Code: ' . $exception->getCode() . ', Line: ' . $exception->getLine() . ')'];
  115. }
  116. return [true, ''];
  117. }
  118. // 设备 ------------------------------------
  119. public function deviceImport($array, $user, $other_param){
  120. $upload = $array[0];
  121. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  122. if(!$status) return [false, $msg];
  123. $table_config = $msg;
  124. unset($array[0]);
  125. if(empty($array)) return [false, '导入数据不能为空'];
  126. // 公共校验
  127. list($array, $error) = $this->checkCommon($array, $table_config);
  128. if(!empty($error)) return [0, $error];
  129. // 详细校验 (这里 $array 传引用,内部会转换日期)
  130. list($error, $update_map) = $this->deviceCheck($array, $user, $table_config);
  131. if(!empty($error)) return [0, $error];
  132. $time = time();
  133. $insert = [];
  134. $update = [];
  135. foreach ($array as $key => $value){
  136. $main_tmp = [];
  137. foreach ($value as $k => $val){
  138. if(!empty($table_config[$k]['is_main'])){
  139. $main_tmp[$table_config[$k]['key']] = $val;
  140. }
  141. }
  142. if(isset($update_map[$key])){
  143. // 存入待更新数组
  144. $update[] = array_merge($main_tmp, ['id' => $update_map[$key]]);
  145. } else {
  146. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  147. $main_tmp['crt_id'] = $user['id'];
  148. $main_tmp['crt_time'] = $time;
  149. $insert[] = $main_tmp;
  150. }
  151. }
  152. DB::beginTransaction();
  153. try {
  154. // 1. 批量新增
  155. if(!empty($insert)){
  156. foreach(array_chunk($insert, 500) as $chunkInsert){
  157. Device::insert($chunkInsert);
  158. }
  159. }
  160. // 批量更新
  161. foreach (array_chunk($update, 100) as $chunk) {
  162. foreach ($chunk as $item) {
  163. $id = $item['id'];
  164. unset($item['id']);
  165. Device::where('id', $id)->update($item);
  166. }
  167. }
  168. DB::commit();
  169. } catch (\Exception $e) {
  170. DB::rollBack();
  171. return [false, "错误:" . $e->getMessage() . " 行:" . $e->getLine()];
  172. }
  173. return [true, ''];
  174. }
  175. private function deviceCheck(&$array, $user, $table_config)
  176. {
  177. // 动态获取关键列的索引
  178. $codeIdx = array_search('code', array_column($table_config, 'key'));
  179. $dateIdx = array_search('in_time', array_column($table_config, 'key'));
  180. $typeIdx = array_search('type', array_column($table_config, 'key'));
  181. $type2Idx = array_search('is_use', array_column($table_config, 'key'));
  182. $code_map = $this->getDeviceList($array, $user, $codeIdx);
  183. $errors = [];
  184. $update = [];
  185. $map_type = array_flip(Device::$type);
  186. $map_type_2 = array_flip(Device::Use);
  187. foreach ($array as $rowIndex => $value) {
  188. $valCode = $value[$codeIdx] ?? '';
  189. // 记录更新 ID
  190. if(isset($code_map[$valCode])){
  191. $update[$rowIndex] = $code_map[$valCode];
  192. }
  193. if(empty($map_type[$value[$typeIdx]])){
  194. $errors[] = "第{$rowIndex}行固定资产类型错误";
  195. }else{
  196. $array[$rowIndex][$typeIdx] = $map_type[$value[$typeIdx]];
  197. }
  198. if(empty($map_type_2[$value[$type2Idx]])){
  199. $errors[] = "第{$rowIndex}行是否启用错误";
  200. }else{
  201. $array[$rowIndex][$type2Idx] = $map_type_2[$value[$type2Idx]];
  202. }
  203. // 日期处理
  204. if($dateIdx !== false && !empty($value[$dateIdx])){
  205. list($status, $msg) = $this->convertExcelCellToDate($value[$dateIdx]);
  206. if(!$status) {
  207. $errors[] = "第{$rowIndex}行日期格式错误";
  208. } else {
  209. $array[$rowIndex][$dateIdx] = $msg;
  210. }
  211. }
  212. }
  213. $error_string = "";
  214. if(! empty($errors)) $error_string = implode('|', $errors);
  215. return [$error_string, $update];
  216. }
  217. private function getDeviceList($array, $user, $index){
  218. //查找设备
  219. $codes = array_unique(array_filter(array_column($array,$index)));
  220. return Device::where('del_time', 0)
  221. ->where('top_depart_id', $user['top_depart_id'])
  222. ->whereIn('code', $codes)
  223. ->pluck('id','code')
  224. ->toArray();
  225. }
  226. // 项目 -----------------------------------
  227. public function itemImport($array, $user, $other_param)
  228. {
  229. $upload = $array[0];
  230. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  231. if (!$status) return [false, $msg];
  232. $table_config = $msg;
  233. unset($array[0]);
  234. if (empty($array)) return [false, '导入数据不能为空'];
  235. // 1. 公共校验 (必填、唯一性等)
  236. list($array, $error) = $this->checkCommon($array, $table_config);
  237. if (!empty($error)) return [0, $error];
  238. // 2. 业务详细校验 (获取更新映射及明细数据)
  239. list($error, $update_map, $detail_data_map) = $this->itemCheck($array, $user, $table_config);
  240. if (!empty($error)) return [0, $error];
  241. $time = time();
  242. $insert_data = [];
  243. $update_data = [];
  244. $all_detail_insert = [];
  245. $update_main_ids = [];
  246. // 3. 数据分拣
  247. foreach ($array as $key => $value) {
  248. $main_tmp = [];
  249. foreach ($value as $k => $val) {
  250. if (!empty($table_config[$k]['is_main'])) {
  251. $main_tmp[$table_config[$k]['key']] = $val;
  252. }
  253. }
  254. if (isset($update_map[$key])) {
  255. // 更新逻辑
  256. $itemId = $update_map[$key];
  257. $update_data[] = array_merge($main_tmp, ['id' => $itemId]);
  258. $update_main_ids[] = $itemId;
  259. // 收集明细 (后续统一插入)
  260. if (isset($detail_data_map[$key])) {
  261. foreach ($detail_data_map[$key] as $d) {
  262. $all_detail_insert[] = array_merge($d, ['item_id' => $itemId, 'crt_time' => $time]);
  263. }
  264. }
  265. } else {
  266. // 新增逻辑
  267. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  268. $main_tmp['crt_id'] = $user['id'];
  269. $main_tmp['crt_time'] = $time;
  270. // 以 code 为键,方便后续回填 ID
  271. $insert_data[$main_tmp['code']] = $main_tmp;
  272. if (isset($detail_data_map[$key])) {
  273. foreach ($detail_data_map[$key] as $d) {
  274. $all_detail_insert[] = array_merge($d, ['_code' => $main_tmp['code'], 'crt_time' => $time]);
  275. }
  276. }
  277. }
  278. }
  279. DB::beginTransaction();
  280. try {
  281. // 4. 执行新增主表
  282. if (!empty($insert_data)) {
  283. foreach (array_chunk($insert_data, 500) as $chunk) {
  284. Item::insert($chunk);
  285. }
  286. // 获取新插入数据的 ID 映射
  287. $new_item_maps = Item::whereIn('code', array_keys($insert_data))
  288. ->where('del_time', 0)
  289. ->where('top_depart_id', $user['top_depart_id'])
  290. ->pluck('id', 'code')->toArray();
  291. }
  292. // 5. 执行更新主表 (分批更新)
  293. if (!empty($update_data)) {
  294. foreach (array_chunk($update_data, 100) as $chunk) {
  295. foreach ($chunk as $uItem) {
  296. $id = $uItem['id'];
  297. unset($uItem['id']);
  298. Item::where('id', $id)->update($uItem);
  299. }
  300. }
  301. }
  302. // 6. 处理明细表 (先删后插策略)
  303. // 删除旧明细 (逻辑删除)
  304. if (!empty($update_main_ids)) {
  305. ItemDetails::whereIn('item_id', $update_main_ids)
  306. ->where('del_time', 0)
  307. ->update(['del_time' => $time]);
  308. }
  309. // 回填新增主表的 ID 到明细数组
  310. foreach ($all_detail_insert as &$di) {
  311. if (isset($di['_code'])) {
  312. $di['item_id'] = $new_item_maps[$di['_code']] ?? 0;
  313. unset($di['_code']);
  314. }
  315. }
  316. unset($di);
  317. // 批量插入所有明细
  318. if (!empty($all_detail_insert)) {
  319. foreach (array_chunk($all_detail_insert, 500) as $chunk) {
  320. ItemDetails::insert($chunk);
  321. }
  322. }
  323. DB::commit();
  324. } catch (\Exception $e) {
  325. DB::rollBack();
  326. return [false, "入库失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  327. }
  328. return [true, '导入成功'];
  329. }
  330. private function getItemList($array, $user, $index){
  331. //查找设备
  332. $codes = array_unique(array_filter(array_column($array,$index)));
  333. return Item::where('del_time', 0)
  334. ->where('top_depart_id', $user['top_depart_id'])
  335. ->whereIn('code', $codes)
  336. ->pluck('id','code')
  337. ->toArray();
  338. }
  339. private function itemCheck(&$array, $user, $table_config)
  340. {
  341. $keys = array_column($table_config, 'key');
  342. $codeIdx = array_search('code', $keys);
  343. $stateIdx = array_search('state', $keys);
  344. $manIdx = array_search('man_list', $keys);
  345. $deviceIdx = array_search('device_list', $keys);
  346. // 日期索引
  347. $dateIdx = array_search('start_time', $keys);
  348. $date2Idx = array_search('end_time', $keys);
  349. $code_map = $this->getItemList($array, $user, $codeIdx);
  350. list($man_map, $device_map) = $this->getDataList($array, $user, $manIdx, $deviceIdx);
  351. $errors = [];
  352. $update_mapping = [];
  353. $detail_storage = [];
  354. $state_type_map = array_flip(Item::State_Type);
  355. foreach ($array as $rowIndex => $rowValue) {
  356. $valCode = $rowValue[$codeIdx] ?? '';
  357. // 1. 判定更新还是新增
  358. if (isset($code_map[$valCode])) {
  359. $update_mapping[$rowIndex] = $code_map[$valCode];
  360. }
  361. // 2. 状态校验
  362. $state_text = $rowValue[$stateIdx] ?? '';
  363. if (!isset($state_type_map[$state_text])) {
  364. $errors[] = "第{$rowIndex}行:状态[{$state_text}]无效";
  365. } else {
  366. $array[$rowIndex][$stateIdx] = $state_type_map[$state_text];
  367. }
  368. // 3. 日期转换
  369. foreach ([$dateIdx, $date2Idx] as $dIdx) {
  370. if ($dIdx !== false && !empty($rowValue[$dIdx])) {
  371. list($s, $m) = $this->convertExcelCellToDate($rowValue[$dIdx]);
  372. if (!$s) $errors[] = "第{$rowIndex}行:日期格式非法";
  373. else $array[$rowIndex][$dIdx] = $m;
  374. }
  375. }
  376. // 4. 解析人员 (明细类型1)
  377. if ($manIdx !== false && !empty($rowValue[$manIdx])) {
  378. foreach (explode(',', $rowValue[$manIdx]) as $mNum) {
  379. $mNum = trim($mNum);
  380. if (!isset($man_map[$mNum])) {
  381. $errors[] = "第{$rowIndex}行:人员编码[{$mNum}]不存在";
  382. } else {
  383. $detail_storage[$rowIndex][] = [
  384. 'type' => ItemDetails::type_one,
  385. 'data_id' => $man_map[$mNum],
  386. ];
  387. }
  388. }
  389. }
  390. // 5. 解析设备 (明细类型2)
  391. if ($deviceIdx !== false && !empty($rowValue[$deviceIdx])) {
  392. foreach (explode(',', $rowValue[$deviceIdx]) as $dCode) {
  393. $dCode = trim($dCode);
  394. if (!isset($device_map[$dCode])) {
  395. $errors[] = "第{$rowIndex}行:资产编码[{$dCode}]不存在";
  396. } else {
  397. $detail_storage[$rowIndex][] = [
  398. 'type' => ItemDetails::type_two,
  399. 'data_id' => $device_map[$dCode],
  400. ];
  401. }
  402. }
  403. }
  404. }
  405. $error_str = !empty($errors) ? implode('|', $errors) : "";
  406. return [$error_str, $update_mapping, $detail_storage];
  407. }
  408. private function getDataList($array, $user, $index1, $index2)
  409. {
  410. $manNums = [];
  411. $devCodes = [];
  412. // 去重收集
  413. foreach ($array as $row) {
  414. if (!empty($row[$index1])) {
  415. foreach (explode(',', $row[$index1]) as $v) $manNums[trim($v)] = true;
  416. }
  417. if (!empty($row[$index2])) {
  418. foreach (explode(',', $row[$index2]) as $v) $devCodes[trim($v)] = true;
  419. }
  420. }
  421. $manMap = Employee::where('del_time', 0)
  422. ->where('top_depart_id', $user['top_depart_id'])
  423. ->whereIn('number', array_keys($manNums))
  424. ->pluck('id', 'number')->toArray();
  425. $devMap = Device::where('del_time', 0)
  426. ->where('top_depart_id', $user['top_depart_id'])
  427. ->whereIn('code', array_keys($devCodes))
  428. ->pluck('id', 'code')->toArray();
  429. return [$manMap, $devMap];
  430. }
  431. // 费用 ----------------------------------
  432. public function feeImport($array, $user, $other_param)
  433. {
  434. $upload = $array[0];
  435. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  436. if (!$status) return [false, $msg];
  437. $table_config = $msg;
  438. unset($array[0]);
  439. if (empty($array)) return [false, '导入数据不能为空'];
  440. list($array, $error) = $this->checkCommon($array, $table_config);
  441. if (!empty($error)) return [0, $error];
  442. // 2. 详细校验
  443. list($error, $update_map, $parent_code_map) = $this->feeCheck($array, $user, $table_config);
  444. if (!empty($error)) return [0, $error];
  445. $time = time();
  446. $insert = [];
  447. $update = [];
  448. $all_codes = [];
  449. // --- 修正点 1: 必须确保索引提取准确 ---
  450. $keys = array_column($table_config, 'key');
  451. $codeIdx = array_search('code', $keys);
  452. // ------------------------------------
  453. foreach ($array as $key => $value) {
  454. $cCode = trim($value[$codeIdx] ?? '');
  455. if($cCode === '') continue;
  456. $all_codes[] = $cCode;
  457. $main_tmp = [];
  458. foreach ($value as $k => $val){
  459. if(!empty($table_config[$k]['is_main'])){
  460. if ($table_config[$k]['key'] !== 'parent_id') {
  461. $main_tmp[$table_config[$k]['key']] = $val;
  462. }
  463. }
  464. }
  465. if (isset($update_map[$key])) {
  466. $update[] = array_merge($main_tmp, ['id' => $update_map[$key]]);
  467. } else {
  468. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  469. $main_tmp['crt_time'] = $time;
  470. $main_tmp['parent_id'] = 0;
  471. $insert[] = $main_tmp;
  472. }
  473. }
  474. DB::beginTransaction();
  475. try {
  476. if (!empty($insert)) {
  477. foreach (array_chunk($insert, 500) as $chunk) {
  478. Fee::insert($chunk);
  479. }
  480. }
  481. if (!empty($update)) {
  482. foreach ($update as $item) {
  483. $uId = $item['id']; unset($item['id']);
  484. Fee::where('id', $uId)->update($item);
  485. }
  486. }
  487. // --- 修正点 2: 核心回填逻辑 ---
  488. $newCodeToIdMap = Fee::where('del_time', 0)
  489. ->where('top_depart_id', $user['top_depart_id'])
  490. ->whereIn('code', array_unique($all_codes))
  491. ->pluck('id', 'code')
  492. ->toArray();
  493. foreach ($parent_code_map as $rowIndex => $pCode) {
  494. // 这里必须通过 $rowIndex 从原始 $array 中精准获取当前行的编码
  495. $currentCode = isset($array[$rowIndex][$codeIdx]) ? trim($array[$rowIndex][$codeIdx]) : '';
  496. $pCode = trim($pCode);
  497. if ($currentCode === '' || $pCode === '') continue;
  498. $currentId = $newCodeToIdMap[$currentCode] ?? null;
  499. $parentId = $newCodeToIdMap[$pCode] ?? null;
  500. // 严谨判断:只有当前记录存在,且上级记录也存在,且两者不是同一个 ID 时才更新
  501. if ($currentId && $parentId && $currentId != $parentId) {
  502. Fee::where('id', $currentId)->update(['parent_id' => $parentId]);
  503. }
  504. }
  505. DB::commit();
  506. } catch (\Exception $e) {
  507. DB::rollBack();
  508. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  509. }
  510. return [true, ''];
  511. }
  512. private function feeCheck(&$array, $user, $table_config)
  513. {
  514. $keys = array_column($table_config, 'key');
  515. $codeIdx = array_search('code', $keys);
  516. $parentIdx = array_search('parent_id', $keys);
  517. // 1. 获取基础数据
  518. list($dbFeeMap, $excelCodesMap) = $this->getFeeList($array, $user, $codeIdx);
  519. $errors = [];
  520. $update = [];
  521. $parent_code_map = [];
  522. // 2. 建立 Excel 内部父子关系映射(用于环路追溯)
  523. $currentExcelMap = [];
  524. foreach ($array as $row) {
  525. $c = trim($row[$codeIdx] ?? '');
  526. $p = trim($row[$parentIdx] ?? '');
  527. if ($c !== '') $currentExcelMap[$c] = $p;
  528. }
  529. // 3. 逐行校验
  530. foreach ($array as $rowIndex => $value) {
  531. $valCode = trim($value[$codeIdx] ?? '');
  532. $valParentCode = trim($value[$parentIdx] ?? '');
  533. if ($valCode === '') continue;
  534. // 更新状态记录
  535. if (isset($dbFeeMap[$valCode])) {
  536. $update[$rowIndex] = $dbFeeMap[$valCode]['id'];
  537. }
  538. if ($valParentCode !== '') {
  539. // --- A. 存在性校验 ---
  540. // 这里会检查 006 是否在数据库,或者是否在本次 Excel 的其他行中
  541. if (!isset($dbFeeMap[$valParentCode]) && !isset($excelCodesMap[$valParentCode])) {
  542. $errors[] = "第{$rowIndex}行:上级编码[{$valParentCode}]在系统和文件中均不存在";
  543. continue;
  544. }
  545. // --- B. 自引用校验 ---
  546. if ($valCode === $valParentCode) {
  547. $errors[] = "第{$rowIndex}行:上级编码不能是自身";
  548. continue;
  549. }
  550. // --- C. 环路追溯 ---
  551. $visited = [];
  552. $res = $this->findLoopInAncestors($valParentCode, $valCode, $currentExcelMap, $dbFeeMap, $visited);
  553. if ($res !== false) {
  554. if ($res['type'] === 'LOOP_SELF') {
  555. $errors[] = "第{$rowIndex}行:编码[{$valCode}]与上级[{$valParentCode}]存在循环引用";
  556. } else {
  557. $errors[] = "第{$rowIndex}行:上级[{$valParentCode}]的溯源链条已成环";
  558. }
  559. continue;
  560. }
  561. // 记录有效的父级关系
  562. $parent_code_map[$rowIndex] = $valParentCode;
  563. }
  564. }
  565. $error_string = !empty($errors) ? implode('|', $errors) : "";
  566. return [$error_string, $update, $parent_code_map];
  567. }
  568. private function getFeeList($array, $user, $index)
  569. {
  570. // 关键:一定要把 Excel 里所有的 code 这一列全部拿出来,并去除空值
  571. $codesInExcel = [];
  572. foreach ($array as $row) {
  573. $c = trim($row[$index] ?? '');
  574. if ($c !== '') {
  575. $codesInExcel[$c] = true;
  576. }
  577. }
  578. $allFees = Fee::where('del_time', 0)
  579. ->where('top_depart_id', $user['top_depart_id'])
  580. ->select('id', 'code', 'parent_id')
  581. ->get();
  582. $dbFeeMap = [];
  583. foreach ($allFees as $fee) {
  584. $dbFeeMap[$fee->code] = [
  585. 'id' => $fee->id,
  586. 'code' => $fee->code,
  587. 'parent_id' => $fee->parent_id
  588. ];
  589. }
  590. // 返回数据库映射和 Excel 编码映射
  591. return [$dbFeeMap, $codesInExcel];
  592. }
  593. private function findLoopInAncestors($startParentCode, $targetCode, $excelMap, $dbFeeMap, &$visited)
  594. {
  595. $current = $startParentCode;
  596. while ($current !== '' && $current !== 0) {
  597. if ($current === $targetCode) {
  598. return ['type' => 'LOOP_SELF', 'code' => $current];
  599. }
  600. if (isset($visited[$current])) {
  601. return ['type' => 'EXISTING_LOOP', 'code' => $current];
  602. }
  603. $visited[$current] = true;
  604. if (isset($excelMap[$current]) && $excelMap[$current] !== '') {
  605. $current = $excelMap[$current];
  606. } elseif (isset($dbFeeMap[$current])) {
  607. $parentId = $dbFeeMap[$current]['parent_id'];
  608. $parentCode = '';
  609. foreach ($dbFeeMap as $item) {
  610. if ($item['id'] == $parentId) {
  611. $parentCode = $item['code'];
  612. break;
  613. }
  614. }
  615. $current = $parentCode;
  616. } else {
  617. break;
  618. }
  619. }
  620. return false;
  621. }
  622. //公共校验 -----------------------------------------
  623. private function checkCommon($array, $table_config) {
  624. $error = [];
  625. $uniqueCheck = []; // 格式:[$column_index => [$value => $first_line]]
  626. foreach ($array as $line => $row) {
  627. $rowData = array_filter($row);
  628. if (empty($rowData)) {
  629. unset($array[$line]);
  630. continue;
  631. }
  632. foreach ($row as $colIndex => $value) {
  633. $value = trim($value);
  634. $config = $table_config[$colIndex] ?? null;
  635. // 1. 基础存在性检查
  636. if (!$config) {
  637. $error[] = "第{$line}行第{$colIndex}列配置不存在";
  638. continue;
  639. }
  640. $fieldName = $config['value'];
  641. // 2. 必填校验
  642. if (!empty($config['required']) && ($value === '' || !isset($value))) {
  643. $error[] = "第{$line}行:[{$fieldName}] 必填";
  644. }
  645. // 3. 默认值填充
  646. if ($value === '' && isset($config['default'])) {
  647. $value = $config['default'];
  648. }
  649. // 4. 唯一性校验(重点:一次遍历解决)
  650. if (!empty($config['unique']) && $value !== '') {
  651. if (isset($uniqueCheck[$colIndex][$value])) {
  652. $prevLine = $uniqueCheck[$colIndex][$value];
  653. $error[] = "第{$line}行:[{$fieldName}] 与第{$prevLine}行重复,重复值:{$value}";
  654. } else {
  655. // 记录该值第一次出现的位置
  656. $uniqueCheck[$colIndex][$value] = $line;
  657. }
  658. }
  659. $row[$colIndex] = $value;
  660. }
  661. $array[$line] = $row;
  662. }
  663. $error_string = !empty($error) ? implode('|', $error) : "";
  664. return [$array, $error_string];
  665. }
  666. //模板校验 -----------------------------------------
  667. private function compareTableAndReturn($upload, $param){
  668. if(empty($upload)) return [false, '表头不能为空'];
  669. $config = $this->getTableConfig($param['type']);
  670. $config_array = $config['array'];
  671. if(empty($config_array)) return [false, '导入配置表头文件不存在'];
  672. foreach ($config_array as $key => $value){
  673. $key_position = $key + 1;
  674. if(! isset($upload[$key])) return [false, "第" . $key_position . "列表头缺失"];
  675. $tmp_v = trim($upload[$key]);
  676. if($tmp_v != $value['value']) return [false, "第" . $key_position . "列表头与模板不符合,请重新下载模板"];
  677. }
  678. return [true, $config_array];
  679. }
  680. //转换日期 ------------------------------------------
  681. function convertExcelCellToDate($cellValue) {
  682. // 尝试将单元格值转换为浮点数(Excel 日期序列号)
  683. $excelTimestamp = filter_var($cellValue, FILTER_VALIDATE_FLOAT);
  684. if ($excelTimestamp !== false && $excelTimestamp > 0) {
  685. // 如果成功转换并且值大于0,则认为是Excel日期序列号
  686. try {
  687. $dateTimeObject = Date::excelToDateTimeObject($cellValue);
  688. // if ($dateTimeObject->format('H:i:s') === '00:00:00') {
  689. // // 如果是,则将时间设置为 '23:59:00'
  690. // $dateTimeObject->setTime(23, 59);
  691. // }
  692. // 现在你可以格式化这个日期了
  693. $formattedDate = $dateTimeObject->format('Y-m-d');
  694. if(! strtotime($formattedDate)) return [false, ''];
  695. return [true, strtotime($formattedDate)];
  696. } catch (\Exception $e) {
  697. // 处理转换失败的情况
  698. return [false, '单元格日期格式转换时间戳失败'];
  699. }
  700. }
  701. // 如果不是有效的浮点数,则尝试按照多种日期格式解析
  702. if(! strtotime($cellValue)) return [false, '单元格文本格式转换时间戳失败'];
  703. return [true, strtotime($cellValue)];
  704. }
  705. }