<template>
  <el-dialog
    v-model="props.show"
    title=""
    width="720"
    style="border-radius: 24px"
    :before-close="handleClose"
  >
    <div class="login-dialog">
      <div class="login-top">
        <div class="info">{{ state.userType }}</div>
        <div class="switch-info" @click="switchUsers">
          切换为{{ state.userType === '个人用户' ? '企业用户' : '个人用户' }}>>
        </div>
      </div>
      <el-form ref="formRef" :model="state.loginForm" :rules="state.loginRules" label-width="0">
        <el-form-item label="" prop="Phone">
          <el-input v-model="state.loginForm.Phone" size="large" placeholder="请输入手机号">
            <template #prefix>
              <img src="../../assets/img/Phone.png" alt="" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="" prop="Code">
          <el-input v-model="state.loginForm.Code" size="large" placeholder="请输入验证码">
            <template #prefix>
              <img src="../../assets/img/pwd.png" alt="" />
            </template>
            <template #suffix>
              <el-button type="primary" link :disabled="state.sended" @click="sendCode">{{
                state.buttonText
              }}</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" style="width: 100%; margin-top: 46px" @click="onConfirm"
        >登录/注册</el-button
      >
    </div>
    <div class="agree-with">
      <el-checkbox v-model="state.agreeWith" label="" size="large" text-color="#ffffff">
        <template #default>
          <div style="color: #999999">
            同意南山就业帮
            <span style="color: #409eff" @click.prevent="open">《南山就业帮用户服务协议》</span>
            及
            <span style="color: #409eff" @click.prevent="open">《个人信息保护政策》</span>
          </div>
        </template>
      </el-checkbox>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { getCode, loginSign } from '@/services/api/login'
import { useGlobalStore } from '@/stores/modules/global'
import { useUserInfoStore } from '@/stores/modules/userInfo'

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:show'])
const globalStore = useGlobalStore()
const userInfoStore = useUserInfoStore()

const formRef = ref()
const state = reactive({
  userType: '个人用户',
  loginForm: {
    Phone: '18874693873',
    Code: '3123'
  },
  loginRules: {
    Phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      {
        pattern: /^1[3|4|5|6|7|8][0-9]\d{8}$/,
        message: '手机号码格式不正确',
        trigger: 'blur'
      }
    ],
    Code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
  },
  agreeWith: false,
  sended: false,
  buttonText: '获取验证码',
  EnCode: '3cu2jF0iHXYVJfSnl0MkLg=='
})

const switchUsers = () => {
  formRef.value?.resetFields()
  if (state.userType === '企业用户') state.userType = '个人用户'
  else state.userType = '企业用户'
}

const sendCode = () => {
  formRef.value?.validateField(['Phone'], async (valid: boolean) => {
    if (valid) {
      // 发送验证码请求
      const res: any = await getCode(state.loginForm.Phone)
      if (res.code === 200) {
        console.log(res)
        state.EnCode = res.data
        // 请求成功后将 sended 设为 true，按钮禁用，并显示倒计时
        state.sended = true
        state.buttonText = '已发送'
        let countDown = 60
        const timer = setInterval(() => {
          if (countDown > 0) {
            state.buttonText = `${countDown}s 后重试`
          } else {
            state.sended = false
            state.buttonText = '获取验证码'
            clearInterval(timer)
          }
          countDown--
        }, 1000)
      }
    }
  })
}

const onConfirm = () => {
  if (!state.agreeWith) return ElMessage.warning('请先同意授权!')
  formRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      const params = {
        Phone: state.loginForm.Phone,
        Code: state.loginForm.Code,
        EnCode: state.EnCode,
        Type: state.userType === '个人用户' ? 'GR' : 'QY' //企业：QY 个人：GR
      }
      const res: any = await loginSign(params)
      if (res.code === 200) {
        if (state.userType === '个人用户') {
          userInfoStore.setCompanyInfo({})
          userInfoStore.setPersonalInfo(res.data)
        } else {
          userInfoStore.setPersonalInfo({})
          userInfoStore.setCompanyInfo(res.data)
        }
        globalStore.setToken(res.data.Token)
        handleClose()
        ElMessage.success('登录成功')
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const open = () => {
  console.log('open')
}

const handleClose = () => {
  formRef.value?.resetFields()
  emits('update:show', false)
}
</script>

<style lang="scss" scoped>
.login-dialog {
  padding: 0 130px;
  .login-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 64px;
    .info {
      font-size: 32px;
      font-weight: 500;
      color: #000000;
    }
    .switch-info {
      color: #265ea4;
      cursor: pointer;
    }
  }
}
.agree-with {
  display: flex;
  align-items: center;
  margin-top: 24px;
  margin-bottom: 50px;
  padding-left: 130px;
}
</style>
