<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 v-if="state.userType === '企业用户'" label="" prop="Company">
          <el-input v-model="state.loginForm.Company" size="large" placeholder="请输入公司名称">
            <template #prefix>
              <img src="../../assets/img/company.png" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="" prop="Phone">
          <el-input v-model="state.loginForm.Phone" size="large" placeholder="请输入手机号">
            <template #prefix>
              <img src="../../assets/img/Phone.png" />
            </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" />
            </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"
        :loading="loading"
        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 router from '@/routers'
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 loading = ref(false)

const formRef = ref()
const state = reactive({
  userType: '个人用户',
  loginForm: {
    Phone: '18874693873',
    Code: '3123',
    Company: '货拉拉科技'
  },
  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' }],
    Company: [{ 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 = '企业用户'
}
let timer: ReturnType<typeof setInterval>

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
        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) {
      try {
        loading.value = true
        const params = {
          Phone: state.loginForm.Phone,
          FNAME: state.loginForm.Company,
          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 if (res.code === 502) {
          router.push({
            path: '/recruitmentManagement/editCompany',
            query: {
              register: 1,
              companyName: state.loginForm.Company,
              phone: state.loginForm.Phone
            }
          })
          handleClose()
          ElMessage.warning(res.msg)
        }
      } catch (error) {
        loading.value = false
      }
    } else {
      loading.value = false
      console.log('error submit!', fields)
    }
  })
}

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

const handleClose = () => {
  clearInterval(timer)
  formRef.value?.resetFields()
  loading.value = false
  state.sended = false
  state.buttonText = '获取验证码'
  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>
