<template>
  <div class="register-view">
    <van-nav-bar title="用户登录" />
    <van-form @submit="onSubmit" class="register-form">
      <van-cell-group inset>
        <van-field
          v-model="formData.phone"
          name="phone"
          label="手机号"
          placeholder="请输入手机号"
          :rules="[
            { required: true, message: '请填写手机号' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
          ]"
          @blur="onPhoneBlur"
        />

        <van-field
          v-model="formData.name"
          name="name"
          label="姓名"
          placeholder="请输入姓名"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />

        <van-field
          v-model="displayPositionType"
          name="positionType"
          label="岗位性质"
          readonly
          clickable
          placeholder="请选择岗位性质"
          :rules="[{ required: true, message: '请选择岗位性质' }]"
          @click="showPositionTypePicker = true"
        />
        <!-- eslint-disable-next-line vue/no-v-model-argument -->
        <van-popup v-model:show="showPositionTypePicker" position="bottom">
          <van-picker
            :columns="positionTypeOptions"
            @confirm="onPositionTypeConfirm"
            @cancel="showPositionTypePicker = false"
            show-toolbar
            title="选择岗位性质"
          />
        </van-popup>
      </van-cell-group>

      <div class="submit-btn">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
        <p class="tip-text">首次登录的用户将自动完成注册</p>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { showToast, showNotify } from 'vant';

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

const formData = reactive({
  phone: '',
  name: '',
  positionType: '',
});

const showPositionTypePicker = ref(false);
const displayPositionType = ref('');

const positionTypeOptions = [
  { text: '管理岗', value: 'MANAGEMENT' },
  { text: '技术岗', value: 'TECHNICAL' },
  { text: '业务岗', value: 'BUSINESS' },
  { text: '职能支持岗', value: 'SUPPORT' }
];

// 手机号失去焦点时检查用户信息
async function onPhoneBlur() {
  if (formData.phone && /^1[3-9]\d{9}$/.test(formData.phone)) {
    try {
      const userInfo = await userStore.getUserInfoByPhone(formData.phone);
      if (userInfo) {
        // 如果用户存在，自动填充信息
        formData.name = userInfo.name;
        formData.positionType = userInfo.positionType;
        displayPositionType.value = positionTypeOptions.find(
          opt => opt.value === userInfo.positionType
        )?.text || '';
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
    }
  }
}

// 岗位性质选择确认
function onPositionTypeConfirm({ selectedOptions }) {
  formData.positionType = selectedOptions[0].value;
  displayPositionType.value = selectedOptions[0].text;
  showPositionTypePicker.value = false;
}

// 提交表单
async function onSubmit() {
  try {
    console.log('开始注册，表单数据：', formData);
    const response = await userStore.loginOrRegister(formData);
    console.log('注册成功，响应数据：', response);

    // 使用 showNotify 显示成功提示，不会干扰用户操作
    showNotify({
      type: 'success',
      message: '注册成功',
      duration: 2000,
      position: 'top'
    });

    // 等待提示显示后再跳转
    setTimeout(() => {
      console.log('准备跳转到问卷页面');
      router.push({
        name: 'survey',
        replace: true
      }).catch(err => {
        console.error('路由跳转失败:', err);
        showToast('页面跳转失败，请刷新重试');
      });
    }, 500);
  } catch (error) {
    console.error('注册失败:', error);
    showToast(error.message || '注册失败，请重试');
  }
}
</script>

<style scoped>
.register-view {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.register-form {
  padding: 20px;
}

.submit-btn {
  margin: 16px;
}

.tip-text {
  font-size: 14px;
  color: #999;
  text-align: center;
  margin-top: 12px;
}
</style>