import React, { useEffect, useState } from "react";
import "./UI6.css";
import "../../assets/css/basic.css";
import { useNavigate } from "react-router-dom";
import BackButton from "../../components/BackButton";
import ConfirmButton from "../../components/ConfirmButton";
import DecorLine from "../../components/DecorLine";
import { getPackagItemDetail } from "../../api/hisApi";

const UI6: React.FC = () => {
  const navigate = useNavigate();

  const handleBack = () => {
    navigate(-1);
  };

  const handleConfirm = () => {
    navigate("/UI7");
  };

  const [ListData, setListData] = useState<any[]>([]);
  const [PackageInfo, setPackageInfo] = useState<any>({});
  useEffect(() => {
    getListData();
  }, []);


  const getListData = async () => {
    const id_no = localStorage.getItem("lastIdCardNo");
    if (!id_no) {
      alert("请先输入身份证号");
      return;
    }
    const res = await getPackagItemDetail(id_no as string);
    if (res.Status === 200) {
      localStorage.setItem(
        "package_code",
        res.Data.packagItemInfo.package_code || ""
      );
      localStorage.setItem(
        "selectedExamId",
        res.Data.packagItemInfo.physical_exam_id.toString() || "0"
      );

      // 处理数据：按科室合并检查项目
      const departmentMap = new Map<
        number,
        {
          department_id: number;
          department_name: string;
          project_ids: string[];
          project_names: string[];
        }
      >();

      res.Data.listPackDetail.forEach((item: any) => {
        const deptId = item.department_id;
        const deptName = item.department_name;

        // 兼容旧格式（一个字符串里用顿号分隔）和新格式（每条记录一个项目）
        const projectIds: string[] = item.project_id
          ? String(item.project_id)
            .split("、")
            .map((id: string) => id.trim())
            .filter((id: string) => id)
          : [];

        const projectNames: string[] = item.project_name
          ? String(item.project_name)
            .split("、")
            .map((name: string) => name.trim())
            .filter((name: string) => name)
          : [];

        if (!departmentMap.has(deptId)) {
          departmentMap.set(deptId, {
            department_id: deptId,
            department_name: deptName,
            project_ids: [],
            project_names: [],
          });
        }

        const dept = departmentMap.get(deptId)!;

        projectIds.forEach((id) => {
          if (!dept.project_ids.includes(id)) {
            dept.project_ids.push(id);
          }
        });

        projectNames.forEach((name) => {
          if (!dept.project_names.includes(name)) {
            dept.project_names.push(name);
          }
        });
      });

      const mergedData = Array.from(departmentMap.values());

      setListData(mergedData);
      setPackageInfo(res.Data.packagItemInfo);
    } else {
      alert(`获取列表数据失败: ${res.Message}`);
    }
  };


  return (
    <div className="basic-root">
      <div className="basic-white-block">
        <div className="basic-content">
          <span className="basic-title">体检套餐确认</span>
          <DecorLine />

          <span className="basic-paragraph">
            {localStorage.getItem("name")}{localStorage.getItem("gender") === "男" ? "先生" : "女士"} <strong>{PackageInfo.package_name}</strong>
            <br />
            <br />
            尊敬的客户，以下是您预约的 {PackageInfo.appointment_datetime} 体检套餐详情，请核对确认
          </span>

          <div className="ui6-table-container">
            <table className="ui6-table">
              <thead>
                <tr>
                  <th className="ui6-table-header ui6-table-dept">科室</th>
                  <th className="ui6-table-header ui6-table-project">检查项目</th>
                </tr>
              </thead>
              <tbody>
                {ListData.map((item, index) => (
                  <tr key={index} className="ui6-table-row">
                    <td className="ui6-table-dept-cell">{item.department_name}</td>
                    <td className="ui6-table-project-cell">
                      {item.project_names.map((project: string, pIndex: number) => (
                        <div key={pIndex} className="ui6-project-item">
                          <span style={{ paddingLeft: 20 }}>{project}</span>
                        </div>
                      ))}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className="basic-confirm-section">
            <BackButton text="返回" onClick={handleBack} />
            <ConfirmButton text="确定" onClick={handleConfirm} />
          </div>
        </div>
      </div>
    </div>
  );
};

export default UI6;
