<template>
  <div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-400 to-blue-700">
    <!-- 登录主卡片 -->
    <div class="w-96 p-8 bg-white rounded-2xl shadow-xl transition-all duration-300 hover:shadow-2xl">
      <div class="text-center mb-8">
        <h1 class="text-3xl font-bold text-gray-800 mb-2">欢迎回来</h1>
        <p class="text-gray-500">请输入您的账号信息</p>
      </div>
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" @keyup.enter="simpleHandleLogin">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户账号" class="!rounded-lg" :prefix-icon="User" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" class="!rounded-lg"
            :prefix-icon="Lock" show-password />
        </el-form-item>

        <!-- 短信验证码 -->
        <!-- <el-form-item prop="smsCode">
          <div class="flex w-full gap-2 items-center">
            <el-input v-model="loginForm.smsCode" placeholder="请输入短信验证码" class="!rounded-lg flex-1"
              :prefix-icon="Lock" />
            <el-button class="!rounded-lg whitespace-nowrap" :disabled="countdown>0 || sendingCode" @click="onGetCode">
              <template v-if="countdown>0">剩余 {{ countdown }}S</template>
<template v-else>获取验证码</template>
</el-button>
</div>
<div class="text-xs text-gray-500 mt-1" v-if="maskMobile">已向{{ maskMobile }}发送验证码</div>
</el-form-item> -->

        <el-button type="primary" class="w-full !rounded-lg h-12 text-base" @click="handleLogin"
          :loading="loading">立即登录</el-button>

      </el-form>
      <div class="mt-6 flex justify-end text-sm">
        <span class="cursor-pointer text-gray-600 hover:text-blue-500 transition-colors" @click.prevent="editPassword">修改密码</span>
      </div>
    </div>
    <ModifyPasswordDialog :showModifyDialog="showModifyDialog" @close="closeModifyDialog"
      :username="loginForm.username" />
    <CaptchaVerifyDialog :visible="showCaptcha" @close="showCaptcha=false" @passed="afterCaptchaPassed" />

    <el-dialog v-model="showSecondVerify" width="420px" align-center :close-on-click-modal="false"
      :close-on-press-escape="false" @closed="handleSecondVerifyClosed">
      <template #header>
        <span>{{ secondVerifyMode === 'finger' ? '指纹验证' : '短信验证' }}</span>
      </template>

      <div v-if="secondVerifyMode === 'finger'"
        class="relative flex flex-col items-center justify-center gap-6 py-12 text-center min-h-[300px]">
        <template v-if="fingerVerifyStatus === 'failed'">
          <div class="text-xl text-red-700">指纹验证失败！</div>
          <div class="text-xl text-red-700">请点击“重试”，再次按压指纹校验</div>
          <div class="mt-8">
            <el-button class="!w-48 !h-12 !text-lg !rounded-none !bg-blue-500 !text-white hover:!bg-gray-100"
              @click="onConfirmSecondVerify">
              重试
            </el-button>
          </div>
        </template>

        <template v-else>
          <div class="text-gray-600">{{ fingerVerifyStatus === 'verifying' ? '请按压指纹进行校验...' : '请点击进行指纹验证' }}</div>
          <div class="text-5xl mb-4">
            <img v-if="fingerVerifyStatus !== 'verifying'" src="@/assets/finger.png" alt="指纹验证" width="100"
              height="100" />
            <el-icon v-else class="is-loading" style="font-size: 48px;">
              <Loading />
            </el-icon>
          </div>
          <div class="text-sm" :class="fingerVerifyStatus === 'failed' ? 'text-red-500' : 'text-gray-500'"
            v-if="fingerVerifyMessage">{{ fingerVerifyMessage }}</div>
          <div v-if="fingerVerifyStatus !== 'verifying'" class="flex gap-2">
            <el-button class="!rounded-lg whitespace-nowrap" :loading="fingerVerifyStatus === 'verifying'"
              @click="onConfirmSecondVerify">
              开始验证
            </el-button>
          </div>
        </template>

        <div class="absolute left-0 bottom-4 w-full flex justify-start px-6 opacity-0 transition-opacity">
          <el-button link size="small" @click="switchToSmsVerify">使用短信验证</el-button>
        </div>
      </div>

      <div v-else class="py-4">
        <div class="flex w-full gap-2 items-center">
          <el-input v-model="loginForm.smsCode" placeholder="请输入短信验证码" />
          <el-button class="!rounded-lg whitespace-nowrap" :disabled="countdown>0 || sendingCode" @click="onGetCode">
            <template v-if="countdown>0">剩余 {{ countdown }}S</template>
            <template v-else>获取验证码</template>
          </el-button>
        </div>
        <div class="text-xs py-1 px-1 text-gray-500" v-if="maskMobile">已向{{ maskMobile }}发送验证码</div>
        <div class="flex justify-center gap-2 mt-5">
          <el-button type="primary" @click="onConfirmSecondVerify">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onUnmounted } from "vue";
import { User, Lock, Loading } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { login, simpleLogin } from "@/api/account";
import { getDoctorByNo, getHisEmployeeInfo } from "@/api/hlw";
import { sendVerificationCode } from "@/api/sms";
import { memberStore } from "@/store/member";
import { tagsStore } from "@/store/tags";
import { templateStore } from "@/store/template";
import { teamStore as useTeamStore } from "@/store/team";
import { configStore } from "@/store/config";
import { useRouter } from "vue-router";
import ModifyPasswordDialog from "@/components/modify-password-dialog/modify-password-dialog.vue";
import CaptchaVerifyDialog from "@/components/captcha-verify-dialog/index.vue";
import { useImStore } from "@/store/im";
import { caStore } from "@/components/ca-sign/store";
import { storeToRefs } from "pinia";
import { authStore } from "@/store/auth";
import { getFingerMatchApi, getReadCardApi } from "@/api/card-jsonp";
const router = useRouter();
// 登录相关
const loginFormRef = ref();
const loading = ref(false);
const loginForm = reactive({
  username: "hnAdmin",
  password: "hnhlw123456789",
});
const loginRules = {
  username: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  smsCode: [{ required: true, message: "请输入短信验证码", trigger: "blur" }],
};
// 短信验证码相关
const sendingCode = ref(false);
const countdown = ref(0);
let timer = null;
const showCaptcha = ref(false);
const showSecondVerify = ref(false);
const secondVerifyMode = ref("sms");
const pendingUser = ref(null);
const fingerVerifyStatus = ref("idle");
const fingerVerifyMessage = ref("");
const doctorMobile = ref("");
const storedFingerprints = ref({ finger1: null, finger2: null });

function startCountdown(sec = 60) {
  countdown.value = sec;
  timer && clearInterval(timer);
  timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
      timer = null;
    }
  }, 1000);
}

function mobileMask(m) {
  if (!m) return "";
  // 如果看起来像手机号，则使用手机号掩码
  if (/^\d{11}$/.test(m)) {
    return m.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  }
  // 非手机号时，对中间部分进行简单掩码（保留两端）以保护隐私
  if (m.length <= 2) return '*'.repeat(m.length);
  if (m.length <= 4) return m[0] + '*'.repeat(m.length - 2) + m[m.length - 1];
  return m.slice(0, 2) + '****' + m.slice(-2);
}

async function onGetCode() {
  if (!loginForm.username) {
    return ElMessage.warning('请输入账号');
  }
  // 去除手机号格式校验：账号可以是任意数字或字符（后端决定如何发送验证码）
  // 直接弹出图形验证码
  showCaptcha.value = true;
}

async function afterCaptchaPassed() {
  showCaptcha.value = false;
  const mobile = String(loginForm.username).trim();
  try {
    sendingCode.value = true;
    const { success, message, data } = await sendVerificationCode({ mobile, corpId: import.meta.env.VITE_CORP_ID });
    sendingCode.value = false;
    if (!success) {
      return ElMessage.error(message || '验证码发送失败');
    }
    const respDoctorMobile = data.data.phone;

    // 优先使用后端返回的 doctorMobile 字段（如果存在），否则使用本地掩码
    doctorMobile.value = respDoctorMobile || mobileMask(mobile);
    ElMessage.success('验证码已发送');
    startCountdown(60);
  } catch (e) {
    sendingCode.value = false;
    ElMessage.error(e.message || '验证码发送失败');
  }
}

onUnmounted(() => { if (timer) clearInterval(timer) })
const simpleHandleLogin = async () => {
  await loginFormRef.value.validate();
  loading.value = true;
  const { username, password } = loginForm;
  const res = await simpleLogin({ username, password, corpId: import.meta.env.VITE_CORP_ID });
  const { success, message, data } = res;
  if (!success) {
    loading.value = false;
    ElMessage.error(message);
    return;
  }
  const { user } = data;
  try {
    const doctorNo = user.doctorNo || user.relatedHlwPeople || user.workNo || "";
    let doctorInfo = null;
    storedFingerprints.value = { finger1: null, finger2: null };

    if (doctorNo) {
      const resp = await getDoctorByNo({ doctorNo });
      const doctorRes = resp?.data;
      doctorInfo = resp?.success ? (doctorRes.data || null) : null;
    }
    const isDoctorOrPharmacist = !!doctorInfo;
    pendingUser.value = user;
    secondVerifyMode.value = isDoctorOrPharmacist ? "finger" : "sms";
    showSecondVerify.value = true;

    // 根据模式决定后续动作
    if (secondVerifyMode.value === "finger") {
      // 确认是指纹模式后，才获取 HIS 指纹信息
      try {
        const { success: hisEmployeeInfoSuccess, data: hisEmployeeInfo } = await getHisEmployeeInfo({
          code: doctorInfo.doctorNo,
        });
        if (!hisEmployeeInfoSuccess) {
          ElMessageBox.alert("未录入指纹信息，请联系管理员处理。", "提示", {
            confirmButtonText: "知道了",
            buttonSize: "default",
            customStyle: {
              width: "300px",
              padding: "10px",
            },
          });
          return false;
        }
        storedFingerprints.value = {
          finger1: hisEmployeeInfo?.data?.finger || null,
          finger2: hisEmployeeInfo?.data?.finger2 || null,
        };
        // 获取成功后自动触发验证
        setTimeout(() => {
          onConfirmSecondVerify();
        }, 100);
      } catch (error) {
        ElMessage.error(error.message || "获取指纹信息失败");
        loading.value = false;
        return;
      }
    } else {

      // 短信模式自动发送验证码
      setTimeout(() => {
        onGetCode();
      }, 100);
    }

    loading.value = false;
    return;
  } catch (error) {
    console.error("登录过程中出错:", error);
    ElMessage.error(error.message || "登录过程中出现错误，请重试");
    loading.value = false;
    return;
  }
};

function switchToSmsVerify() {
  fingerVerifyStatus.value = "idle";
  fingerVerifyMessage.value = "";
  secondVerifyMode.value = "sms";
  // Auto-send SMS code when switching to SMS mode
  setTimeout(() => {
    onGetCode();
  }, 100);
}

async function handleSecondVerifyClosed() {
  showSecondVerify.value = false;
  loading.value = false;
  fingerVerifyStatus.value = "idle";
  fingerVerifyMessage.value = "";
}

async function onConfirmSecondVerify() {
  if (!pendingUser.value) return;

  if (secondVerifyMode.value === "finger") {
    fingerVerifyStatus.value = "verifying";
    fingerVerifyMessage.value = "";
    const ok = await handleFingerprintVerification(pendingUser.value);
    if (!ok) {

      fingerVerifyStatus.value = "failed";
      fingerVerifyMessage.value = "指纹验证失败，请重试";
      return;
    }
    fingerVerifyStatus.value = "success";
    fingerVerifyMessage.value = "指纹验证通过";
    showSecondVerify.value = false;
    await handleLogin();
    return;
  }

  if (!loginForm.smsCode) {
    return ElMessage.warning("请输入短信验证码");
  }
  showSecondVerify.value = false;
  await handleLogin();
}

const handleLogin = async () => {
  await loginFormRef.value.validate();
  loading.value = true;
  const { username, password } = loginForm;
  const isFingerLogin = secondVerifyMode.value === "finger";

  // 调登陆接口，区分指纹登录与短信验证码登录
  const loginParams = {
    platform: "PC",
    username,
    password,
    corpId: import.meta.env.VITE_CORP_ID,
  };

  const res = await login(loginParams);
  const { success, message, data } = res;
  if (!success) {
    loading.value = false;
    ElMessage.error(message);
    return;
  }
  const { user, defaultPassword, accessToken, refreshToken } = data;
  const auth = authStore();
  await auth.setAccessToken(accessToken);
  await auth.setRefreshToken(refreshToken);
  if (success) {
    sessionStorage.setItem("corpId", import.meta.env.VITE_CORP_ID);
    sessionStorage.setItem("isLogin", true);
    sessionStorage.setItem("loginId", user.loginId);
    const res = await loginSuccess(user);
    if (!res) {
      return;
    }
    // loading.value = false;
    ElMessage.success("登录成功");
    return;
  }
  // loading.value = false;
  if (message === "密码未设置") {
    ElMessageBox.confirm("您的密码为初始密码，请修改密码", "提示", {
      confirmButtonText: "修改密码",
      type: "warning",
    }).then(() => {
      showModifyDialog.value = true;
    });
  } else {
    ElMessage.error(message);
  }
};

// 修改密码相关
function editPassword() {
  showModifyDialog.value = true;
}
// 登陆成功后的操作
async function loginSuccess(user) {
  const { userid, roleIds } = user;
  sessionStorage.setItem("userId", userid);
  const { getCorpInfo } = memberStore();
  const { memberInfo } = storeToRefs(memberStore());
  memberInfo.value = user;
  const { setUserMenus } = tagsStore();
  try {
    const [corp, menuTree] = await Promise.all([getCorpInfo(), setUserMenus(roleIds)]);
    const firstMenu = menuTree[0] && menuTree[0].children && menuTree[0].children[0] ? menuTree[0].children[0] : null;
    const path = firstMenu ? firstMenu.path : "";
    sessionStorage.setItem("doctorNo", user.doctorNo || "");
    sessionStorage.setItem("isLogin", true);
    if (import.meta.env.VITE_NEED_CA && (user.doctorNo || user.workNo)) {
      sessionStorage.setItem("uniqueId", user.doctorNo || user.workNo);
      caStore().getUserCaInfo();
    }
    if (user.doctorNo) {
      const { imLogin } = useImStore();
      await imLogin();
      // setCurrentTeam();
    }
    path && router.replace({ name: path });
    return true;
  } catch (error) {
    console.error("登录后初始化失败:", error);
    ElMessage.error(error.message);
    // 清理登录状态
    sessionStorage.removeItem("isLogin");
    sessionStorage.removeItem("userId");
    loading.value = false;
    return false;
  }
}

async function checkLocalFingerprintService(timeoutMs = 800) {
  const controller = new AbortController();
  const t = setTimeout(() => controller.abort(), timeoutMs);
  try {
    const res = await fetch("http://127.0.0.1:8732", {
      method: "GET",
      mode: "no-cors",
      signal: controller.signal,
    });
    clearTimeout(t);
    return !!res;
  } catch (e) {
    clearTimeout(t);
    return false;
  }
}

async function handleFingerprintVerification(user) {
  let fingerprintLoader = null;
  try {
    const localOk = await checkLocalFingerprintService();
    if (!localOk) {
      ElMessage.error("本地指纹服务(8732端口)未运行或不可访问，请先启动指纹程序");
      return false;
    }

    const { finger1, finger2 } = storedFingerprints.value || {};
    if (!finger1 && !finger2) {
      ElMessageBox.alert("未检测到指纹信息，请重新登录或联系管理员处理。", "提示", {
        confirmButtonText: "知道了",
        buttonSize: "default",
        customStyle: {
          width: "300px",
          padding: "10px"
        }
      });
      return false;
    }
    //const storedFinger3 = "SjBTUzIxAAADc3UECAUHCc7QAAAvcpEBAAAAg54bZXOmANUPhQC4AN98zQCPAOsP7AD5c10PdgA/AYoOgnNcANEP1wC8AGp8vgBMAd0JVwBjcsoL1gDfACkPQHMPAdgPKwAoANR86QC2AG4OJwAQcvUPJwCJABEPmnNXAN4PbACcAc14WgBhAVIJDQANcuQPcAB8AJIPWHN9ANMPJgB1AFF8twBoAOcPOACic/ULUABnAJcPp3NcAdQBcQC0Aelxd4NiB4f57IVhfycLaYZCB3p87/RDhOcPgYOTh42MpPbu9AZ9qIKt9jp2DggXFK77sooj4T7+ZoMmCMyKR3xSAsuLNX/RcWaH9nxmh36EFmBGCecb7oZW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aelxd4NiB4f57IVhfycLaYZCB3p87/RDhOcPgYOTh42MpPbu9AZ9qIKt9jp2DggXFK77sooj4T7+ZoMmCMyKR3xSAsuLNX/RcWaH9nxmh36EFmBGCecb7oZWhaRxGA66+fYH5H3qlYCDHYVJa88HpoBq+OMLqYXoff36rH1ZgrL7N4JsDCp/MgmugQP/7fseCS+OXYKD/iTyJAmW+B/uiB4y6Ich+PfbBeU2AnEMG9QIAIzqXoqMMAUAmS9gAWYGc6U0ZMNeC8WxNhfDwVbC/n3DAHREV8HAZAQAeTpqDQUAaDtciM0AzUhswcLB/3HCAFROVsHA/1YXxdFHHoj+wHTB/5nBUrPBQwYARUWSbcJ2AeNLd5IIxTJRJcP/wP9XBcXsVQnCXBQA+mJFwsAVecDAwv7CoE8Jc01nVlPBRAENAyBpSTVwR/4HAwJzanfBEwCyqmLDGcFrXFXBKsABBQZwZxQA13e1wsMNZv9q/8D+tgsDHnpcflL/VdAA2w9jwf3BwsAFdFmzVEkYAQl+rENOsmtkwMBwPwQLAwF+U8DAwf6nQQ9zWINXc8H/BU/AawAMjG3/UwfCwoyKUXPAwFbAACf+VsE+FQD3YXfBHXlkav/C/gRPB3IbrHqBBQDgs1NLEwDmtHSQrn7Ds8HAwWAVAdK3dBmRWnjAasGjDgOUu2vBanPCoMEFchnCd2fCBsQYzwTBwXUSARoTemyMw3/CZsHAmBACbt93wHTCh6LAfX4B0eNmwXCxwHh0ABrodFmFygEdhnzC/8PAbwR4bnABJ/lc/wPFLP4j/AUBH/10Bf7AdxAUC3dsCtQVFQloiI4HEN3SacGzgggREyB3BcGPswkRES6Akb4GEmo9hsLBnQbUGUbz/sSFBhEYlYD8t5QLERdbgwfCwrX8/vjEwwTUCmcEkQ==";

    const isMatch = await performFingerprintMatch(finger1, finger2);
    if (!isMatch) {
      ElMessage.error("指纹验证失败");
      return false;
    } else {
      ElMessage.success("指纹验证通过！");
      return true;
    }
  } catch (error) {
    fingerprintLoader?.close();
    console.error("指纹验证过程中出错:", error);
    ElMessage.error(error.message || "指纹验证失败");
    return false;
  }
}

async function performFingerprintMatch(fingerA, fingerB) {
  try {
    const primaryFinger = fingerA || fingerB;
    const secondaryFinger = fingerA && fingerB ? fingerB : null;
    const result = await getFingerMatchApi({
      fingerA: primaryFinger,
      fingerB: secondaryFinger
    });
    console.log("指纹对比结果:", result);
    // NOTE: Assuming the service returns a specific success code/property.
    // Adjust this based on the actual API response for a successful match.
    if (result === 1) {
      return true;
    }
    else {
      if (String(result).includes("-2")) {
        ElMessage.error("指纹读取设备未连接或未初始化，请检查指纹读取设备");
        return false;
      }
      return false;
    }
  } catch (error) {
    console.error("指纹比对服务调用失败", error);
    return false;
  }
}

// 修改密码相关
const showModifyDialog = ref(false);

function closeModifyDialog() {
  showModifyDialog.value = false;
}
</script>

<style lang="scss">
/* 自定义表单元素样式 */
</style>