import React, { useEffect, useState } from "react";
import "./u2.css";
import { useNavigate } from "react-router-dom";
import DecorLine from "../../components/DecorLine";
import nan from "../../assets/nan.png";
import nv from "../../assets/nv.png";
import semicircle from "../../assets/semicircle.png";
import BackButton from "../../components/BackButton";
import ConfirmButton from "../../components/ConfirmButton";
import {
  getPatientInfo,
  getVipStatus,
  getOptionalItemList,
  updatePatientInfo,
  PatientInfo,
} from "../../api/hisApi";
import { parseRegionCodesFromId } from "../../utils/idCard";

const U2: React.FC = () => {
  const navigate = useNavigate();
  const idCardNo = localStorage.getItem("lastIdCardNo");
  const [patientInfo, setPatientInfo] = useState<PatientInfo | null>(null);
  const [loading, setLoading] = useState<boolean>(() => !!idCardNo);
  const [isVip, setIsVip] = useState<number | null>(null);
  const vipCalledRef = React.useRef(false);
  // 婚姻状况：10-未婚 20-已婚，初始使用后端返回的值
  const [selectedMarital, setSelectedMarital] = useState<number | null>(null);

  useEffect(() => {
    if (idCardNo) {
      setLoading(true);
      getPatientInfo(idCardNo)
        .then((res) => {
          if (res.Status === 200 && res.Data) {
            setPatientInfo(res.Data);
            localStorage.setItem("name", res.Data.name);
            localStorage.setItem("gender", res.Data.gender_name);
            // 初始化婚姻状况选择器
            // 如果需要更新且marital不是10或20，则设为null（未选中）
            const needUpdate = res.Data.is_update_patient_info === 1;
            const marital = res.Data.marital;
            if (needUpdate && marital !== 10 && marital !== 20) {
              setSelectedMarital(null);
            } else {
              setSelectedMarital(marital);
            }
          } else {
            alert(`未查询到您的档案信息，请联系前台工作人员`);
            navigate("/");
          }
        })
        .catch((err) => {
          console.error(err);
          alert(`获取用户信息异常: ${err.message}`);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [idCardNo]);

  // 获取 VIP 状态，避免重复请求
  useEffect(() => {
    if (!idCardNo) return;
    if (vipCalledRef.current) return;
    vipCalledRef.current = true;
    getVipStatus(idCardNo)
      .then((res) => {
        if (res.Status === 200) {
          setIsVip(res.Data?.is_vip ?? 0);
        } else {
          console.warn("获取 VIP 状态失败:", res.Message);
          setIsVip(0);
        }
      })
      .catch((err) => {
        console.error("getVipStatus error", err);
        setIsVip(0);
      });
  }, [idCardNo]);

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

  const handleConfirm = () => {
    // 判断是否为有效签到
    if (!patientInfo?.is_valid_exam || patientInfo.is_valid_exam !== 1) {
      // alert("当前签到无效，请联系前台工作人员处理");
      return;
    }
    if (!idCardNo) {
      alert("未获取到身份证号，请重新刷卡");
      navigate("/");
      return;
    }

    // 先判断是否需要更新客户信息
    const needUpdate = patientInfo?.is_update_patient_info === 1;

    // 如果需要更新且用户未选择婚姻状况（selectedMarital为null或不是10/20），则提示
    if (
      needUpdate &&
      (selectedMarital === null ||
        (selectedMarital !== 10 && selectedMarital !== 20))
    ) {
      // alert("请确认婚姻状况");
      return;
    }

    const maritalChanged =
      selectedMarital !== null && selectedMarital !== patientInfo?.marital;

    const proceedToNext = () => {
      // 判断是否为 VIP 客户（0 否，1 是）
      if (isVip === 1) {
        navigate("/u3");
        return;
      } else {
        // 调用接口判断是否有可选套餐
        getOptionalItemList(idCardNo)
          .then((res) => {
            if (res.Status === 200) {
              localStorage.setItem(
                "selectedExamId",
                res.Data.packageInfo.physical_exam_id.toString() || ""
              );

              const isPackageUndecided =
                res.Data?.packageInfo?.is_optional_package === 1 &&
                res.Data?.packageInfo.registration_time?.length > 0;
              if (isPackageUndecided) {
                navigate("/u4", { state: { optionalData: res.Data } });
              } else {
                // 如果没有可选套餐，检查是否有错误消息需要提示
                if (!res.Data?.packageInfo && res.Message) {
                  alert(res.Message);
                } else {
                  navigate("/UI6");
                }
              }
            } else {
              if (res.Message) {
                alert(res.Message);
              } else {
                navigate("/UI6");
              }
            }
          })
          .catch((err) => {
            console.error("getOptionalItemList error", err);
            navigate("/UI6");
          });
      }
    };

    // 如果后端要求更新且用户修改了婚姻状况，则调用更新接口
    if (needUpdate && maritalChanged && selectedMarital !== null) {
      // 读取存储的完整身份证数据
      let idCardData: any = {};
      try {
        const storedData = localStorage.getItem("idCardData");
        if (storedData) {
          idCardData = JSON.parse(storedData);
        }
      } catch (err) {
        console.warn("Failed to parse idCardData from localStorage", err);
      }

      const address = idCardData.address || "";
      // 根据身份证号推断省/市/县编码（优先使用 idCardNo）
      // const regionFromId = parseRegionCodesFromId(idCardNo || undefined);
      // const provinceCode = regionFromId.province || "";
      // const cityCode = regionFromId.city || "";
      // const countyCode = regionFromId.county || "";

      const tryUploadWithPhoto = async () => {
        const photoPath = idCardData.photo_path;
        if (!photoPath) {
          window.electronAPI.log("error", "身份证照片路径不存在，无法上传照片");
          throw new Error("身份证照片路径不存在");
        }
        if (!window.electronAPI || !window.electronAPI.readLocalFile) {
          window.electronAPI.log(
            "error",
            "系统不支持读取本地文件，无法上传身份证照片"
          );
          throw new Error("系统不支持读取本地文件");
        }

        const res = await window.electronAPI.readLocalFile(photoPath);
        if (!res || !res.success || !res.data) {
          window.electronAPI.log(
            "error",
            `读取身份证照片失败: ${res?.error || "未知错误"}`
          );
          throw new Error(res?.error || "读取身份证照片失败");
        }

        const base64 = res.data as string;
        // 仅支持 BMP：优先使用主进程返回的 mime，否则默认为 image/bmp
        const mime = res.mime || "image/bmp";

        // base64 -> Blob
        const byteCharacters = atob(base64);
        const byteNumbers = new Array(byteCharacters.length);
        for (let i = 0; i < byteCharacters.length; i++) {
          byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray], { type: mime });
        //打印参数

        // window.electronAPI.log(
        //   "info",
        //   `Updating patient info: id_no=${idCardNo}, marital_status=${selectedMarital}, province=${provinceCode}, city=${cityCode}, county=${countyCode}, address=${address}, id_no_pic size=${blob.size}`
        // );
        // 调用带图片的更新接口（传入推断的省市县编码）
        return updatePatientInfo(
          idCardNo,
          selectedMarital,
          address,
          blob,
          idCardData.life_end
        );
      };

      tryUploadWithPhoto()
        .then((res) => {
          if (res.Status === 200) {
            console.log("客户信息更新成功");
            proceedToNext();
          } else {
            alert(res.Message || "更新客户信息失败");
          }
        })
        .catch((err) => {
          console.error("updatePatientInfo error", err);
          window.electronAPI.log(
            "error",
            `更新客户信息异常: ${err.message || err}`
          );
          alert("更新客户信息异常，请联系前台工作人员");
        });
    } else {
      // 不需要更新或用户未修改，直接进入下一步
      proceedToNext();
    }
  };

  // 返回头像地址：使用 gender_name 字段（"女" 显示女性头像），忽略 photo_path
  const getAvatarSrc = () => {
    const genderName = (patientInfo?.gender_name || "").trim();
    if (genderName === "女") return nv;
    return nan;
  };

  // 根据 gender_name 返回显示的性别标签（用于界面展示）
  const getGenderLabel = () => {
    const genderName = (patientInfo?.gender_name || "").trim();
    if (!genderName) return "";
    return genderName;
  };

  // 脱敏证件号：保留前6后4，其余替换为*
  const maskIdCard = (id?: string | null) => {
    if (!id) return "---";
    const s = String(id).trim();
    if (s.length <= 10) return s.replace(/.(?!.{4})/g, "*");
    const head = s.slice(0, 6);
    const tail = s.slice(-4);
    const middleLen = s.length - 10;
    return head + "*".repeat(middleLen) + tail;
  };

  // 在数据加载时显示占位，加载完成后再渲染完整内容
  if (loading) {
    return <></>;
  }

  return (
    <div className="u2-root">
      <span className="u2-title">尊敬的客户，请确认您的个人信息：</span>
      <DecorLine />
      <div className="u2-info-card">
        <div className="u2-info-top">
          <div className="u2-avatar-container">
            <img className="u2-avatar" src={getAvatarSrc()} alt="avatar" />
          </div>
          <div className="u2-details-list">
            <div className="u2-detail-row">
              <div className="u2-detail-bar" />
              <div className="u2-detail-text">
                姓名：{loading ? "" : patientInfo?.name || "---"}
              </div>
            </div>

            <div className="u2-detail-row">
              <div className="u2-detail-bar" />
              <div className="u2-detail-text">
                性别：{loading ? "" : getGenderLabel()}
              </div>
            </div>

            <div className="u2-detail-row">
              <div className="u2-detail-bar" />
              <div className="u2-detail-text">
                年龄：{loading ? "" : patientInfo?.age || "---"}
              </div>
            </div>

            <div className="u2-detail-row">
              <div className="u2-detail-bar" />
              <div className="u2-detail-text">
                证件号：
                {loading ? "" : maskIdCard(idCardNo || patientInfo?.IdCard)}
              </div>
            </div>

            <div className="u2-detail-row">
              <div className="u2-detail-bar" />
              <div className="u2-detail-text">
                手机号：{loading ? "" : patientInfo?.phone || "---"}
              </div>
            </div>

            <div className="u2-detail-row">
              <div className="u2-detail-bar" />
              <div className="u2-detail-text">
                婚姻状况：
                {loading ? (
                  ""
                ) : patientInfo?.is_update_patient_info === 1 ? (
                  // 需要更新：显示两个可选按钮
                  <div className="u2-marital-selector">
                    <span
                      className={`u2-marital-option ${
                        selectedMarital === 10 ? "selected" : ""
                      }`}
                      onClick={() => setSelectedMarital(10)}
                    >
                      未婚
                    </span>
                    <span
                      className={`u2-marital-option ${
                        selectedMarital === 20 ? "selected" : ""
                      }`}
                      onClick={() => setSelectedMarital(20)}
                    >
                      已婚
                    </span>
                  </div>
                ) : (
                  // 不需要更新：只显示当前已选中的按钮（只读）
                  <div className="u2-marital-selector">
                    {selectedMarital === 10 && (
                      <span className="u2-marital-option selected">未婚</span>
                    )}
                    {selectedMarital === 20 && (
                      <span className="u2-marital-option selected">已婚</span>
                    )}
                    {selectedMarital !== 10 && selectedMarital !== 20 && (
                      <span>{patientInfo?.marital_name || "---"}</span>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
        {patientInfo?.is_valid_exam !== 1 ? (
          <div className="u2-error-msg">
            未查询到您当日的体检预约信息，建议核对预约日期!
          </div>
        ) : patientInfo?.is_update_patient_info === 1 &&
          selectedMarital === null ? (
          <div className="u2-error-msg">请确认婚姻状况后再点击确认</div>
        ) : (
          ""
        )}
      </div>
      <span className="u2-instruction">
        <span className="u2-asterisk">*</span> 如信息有误，请联系前台
      </span>
      <img className="u2-semicircle" alt="start button" src={semicircle} />
      <div className="u2-confirm-section">
        <BackButton text="返回" onClick={handleBack} />
        <ConfirmButton text="确认" onClick={handleConfirm} />
      </div>
    </div>
  );
};

export default U2;
