<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;

class ItemDuiBiController extends Controller
{
    public function compareWithTxt(Request $request)
    {
        try {
            // 1. 读取并解析TXT文件
            $filePath = storage_path('app/medical_items.txt');

            if (!File::exists($filePath)) {
                return view('compare-result', [
                    'error' => 'TXT文件不存在，请检查 storage/app/medical_items.txt'
                ]);
            }

            $fileContent = File::get($filePath);
            $txtItems = json_decode($fileContent, true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                return view('compare-result', [
                    'error' => 'TXT文件不是有效的JSON格式：' . json_last_error_msg()
                ]);
            }

            // 提取TXT中的项目并按名称分组（保留完整信息）
            $txtItemsGrouped = collect($txtItems)
                ->filter(function($item) {
                    return !empty($item['itemName']);
                })
                ->groupBy('itemName')
                ->map(function($group) {
                    // 每个名称只保留第一条记录的信息
                    return $group->first();
                });

            // 提取TXT中的itemName
            $txtNames = $txtItemsGrouped->keys()->sort()->values()->all();

            // 2. 从数据库查询项目（表名：s_check_item）
            $dbItems = DB::table('s_check_item')
                ->distinct()
                ->where(['is_del' => 0,'item_class_id'=>4])
                ->whereNotNull('item_name')
                ->get(['id', 'item_name'])
                ->keyBy('item_name'); // 按名称作为键

            $dbNames = $dbItems->keys()->sort()->values()->all();

            // 3. 数据比对
            $txtCollection = collect($txtNames);
            $dbCollection = collect($dbNames);

            $onlyInTxt = $txtCollection->diff($dbCollection)->all();
            $onlyInDb = $dbCollection->diff($txtCollection)->all();
            $inBothNames = $txtCollection->intersect($dbCollection)->all();

            // 4. 处理两者都存在的项目，关联设备信息
            $inBothWithDevices = [];
            foreach ($inBothNames as $name) {
                // 获取TXT中的scheduleName
                $txtItem = $txtItemsGrouped->get($name);
                $scheduleNames = !empty($txtItem['scheduleName'])
                    ? explode(',', $txtItem['scheduleName'])
                    : [];

                // 去除空格并过滤空值
                $scheduleNames = array_filter(array_map('trim', $scheduleNames));

                // 获取数据库项目ID
                $checkItem = $dbItems->get($name);
                $checkItemId = $checkItem ? $checkItem->id : null;

                // 查询匹配的设备ID
                $deviceIds = [];
                if (!empty($scheduleNames)) {
                    $devices = DB::table('s_devices')
                        ->whereIn('device_name', $scheduleNames)
                        ->get(['id', 'device_name']);

                    $deviceIds = $devices->pluck('id')->all();
                }

                $inBothWithDevices[] = [
                    'name' => $name,
                    'check_item_id' => $checkItemId,
                    'schedule_names' => $scheduleNames,
                    'device_ids' => $deviceIds,
                    'device_count' => count($deviceIds)
                ];
            }

            // 5. 传递数据到视图
            return view('compare-result', [
                'summary' => [
                    'txt_total' => count($txtNames),
                    'db_total' => count($dbNames),
                    'only_in_txt_count' => count($onlyInTxt),
                    'only_in_db_count' => count($onlyInDb),
                    'in_both_count' => count($inBothNames)
                ],
                'onlyInTxt' => $onlyInTxt,
                'onlyInDb' => $onlyInDb,
                'inBoth' => $inBothWithDevices,
                'error' => null
            ]);

        } catch (\Exception $e) {
            return view('compare-result', [
                'error' => '比对失败：' . $e->getMessage()
            ]);
        }
    }
}
