<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2 class="login-title">调压通管理后台</h2>
      </template>
      <el-form
        :model="loginForm"
        :rules="rules"
        ref="loginFormRef"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="phone">
          <el-input
            v-model="loginForm.phone"
            placeholder="请输入手机号"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
            :prefix-icon="Lock"
          />
        </el-form-item>
        <el-alert
          type="info"
          :closable="false"
          title="登录页只需手机号和密码。若匹配到多个院内账号，系统会在下一步让你选择。"
          style="margin-bottom: 16px"
        />
        <el-form-item>
          <el-button
            type="primary"
            class="login-btn"
            :loading="loading"
            @click="handleLogin"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog
      v-model="accountSelectVisible"
      title="选择登录账号"
      width="420px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-radio-group v-model="selectedAccountId" class="account-list">
        <el-radio
          v-for="account in candidateAccounts"
          :key="account.id"
          :value="account.id"
          class="account-item"
        >
          <div class="account-name">{{ account.name }}</div>
          <div class="account-meta">
            {{ formatAccountMeta(account) }}
          </div>
        </el-radio>
      </el-radio-group>

      <template #footer>
        <el-button @click="resetAccountSelection">取消</el-button>
        <el-button
          type="primary"
          :loading="confirmLoading"
          @click="handleConfirmLogin"
        >
          确认进入
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '../store/user';
import { User, Lock } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { getRoleLabel } from '../constants/role-labels';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const loginFormRef = ref(null);
const loading = ref(false);
const confirmLoading = ref(false);
const accountSelectVisible = ref(false);
const selectedAccountId = ref(null);
const pendingLoginTicket = ref('');
const candidateAccounts = ref([]);

const loginForm = reactive({
  phone: '',
  password: '',
});

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少为 8 位', trigger: 'blur' },
  ],
};

const formatAccountMeta = (account) => {
  const parts = [getRoleLabel(account.role)];
  if (account.hospitalName) {
    parts.push(account.hospitalName);
  }
  return parts.join(' / ');
};

const redirectToTarget = () => {
  ElMessage.success('登录成功');
  const redirect = route.query.redirect || '/';
  router.push(redirect);
};

const resetAccountSelection = () => {
  accountSelectVisible.value = false;
  selectedAccountId.value = null;
  pendingLoginTicket.value = '';
  candidateAccounts.value = [];
};

const handleLogin = async () => {
  if (!loginFormRef.value) return;
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const result = await userStore.login(loginForm);
        if (result?.needSelect) {
          pendingLoginTicket.value = result.loginTicket;
          candidateAccounts.value = result.accounts || [];
          selectedAccountId.value = result.accounts?.[0]?.id ?? null;
          accountSelectVisible.value = true;
          return;
        }

        if (result?.success) {
          redirectToTarget();
        } else {
          ElMessage.error('登录失败，未获取到登录信息');
        }
      } catch (error) {
        console.error('登录请求失败', error);
      } finally {
        loading.value = false;
      }
    }
  });
};

const handleConfirmLogin = async () => {
  if (!pendingLoginTicket.value || !selectedAccountId.value) {
    ElMessage.warning('请先选择一个账号');
    return;
  }

  confirmLoading.value = true;
  try {
    const result = await userStore.confirmLogin(
      pendingLoginTicket.value,
      selectedAccountId.value,
    );
    if (result?.success) {
      resetAccountSelection();
      redirectToTarget();
      return;
    }

    ElMessage.error('登录失败，未获取到登录信息');
  } catch (error) {
    console.error('确认登录失败', error);
  } finally {
    confirmLoading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
}
.login-card {
  width: 400px;
}
.login-title {
  margin: 0;
  text-align: center;
  color: #303133;
}
.login-btn {
  width: 100%;
}

.account-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

.account-item {
  margin-right: 0;
  padding: 12px 14px;
  border: 1px solid #dcdfe6;
  border-radius: 10px;
  width: 100%;
}

.account-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.account-meta {
  font-size: 12px;
  color: #909399;
}
</style>
