<template>
  <div class="login-box py-5">
    <v-card class="pa-5" :class="isMobile? 'mobileBox' : 'default-width'" :elevation="isMobile? '0' : '3'">
      <!-- 标题 -->
      <div class="mt-3" v-if="!isMobile">
        <v-btn v-if="pageType !== 'noLoginToRegister'" color="primary" variant="text" @click="router.push('/recruitHome')">{{ `<< 回到首页` }}</v-btn>
        <div v-else style="height: 30px;"></div>
      </div>
      <!-- 表单 -->
      <div class="CtFormClass" :style="{width: isMobile ? '' : '600px'}">
        <div v-if="failureReason" class="mb-8" style="color: red;">
          <span class="mr-5">《审核不通过》</span>
          <span>原因：{{ failureReason }}</span>
        </div>
        <!-- 标题 -->
        <div class="mb-10" :class="isMobile ? 'mt-0': 'mt-n8'" style="font-size: 22px; font-weight: bold; text-align: center;">{{ $t('enterprise.registeringNewEnterprise') }}</div>
        <CtForm ref="CtFormRef" :items="formItems" style="width: 100%;">
          <template #businessLicense>
            <!-- 上传照片 -->
            <div class="d-flex flex-column mb-6">
              <div style="color: var(--color-999);">
                <span v-if="!prepareValue" class="mr-1" style="color: var(--v-error-base);">*</span>
                <span>上传营业执照</span>
                <span>支持jpg、jpeg、png格式，图片大小不得超过10M</span>
              </div>
              <div class="file-box">
                <Img 
                  class="mt-3" 
                  tips="上传图片" 
                  :value="licenseUrl"
                  :showSnackbar="false" 
                  @imgClick="showPreview = !showPreview" 
                  :showCursor="true" 
                  @success="handleUploadImg" 
                  @delete="handleDeleteImg"
                ></Img>
              </div>
            </div>
          </template>
          <template #contacts>
            <!-- 联系人 -->
            <v-btn class="mb-5" style="width: 100%; text-align: center;" variant="text" color="primary" prepend-icon="mdi-plus-box" @click="handleAddContact">添加联系人</v-btn>
          </template>
        </CtForm>
        <div class="note">
          <h4>注意事项:</h4>
          <span>企业名称为对外展示的企业名称，建议填写公司营业执照上的名称，请区分总公司和分公司</span>
        </div>
      </div>
      <div class="text-center">
        <!-- 提交 -->
        <v-btn
          :loading="loginLoading"
          color="primary" class="white--text my-8" min-width="350"
          @click="handleCommit"
        >
        {{ $t('common.complete') }}
        </v-btn>
      </div>
    </v-card>
    <PreviewImg v-if="showPreview" :current="current" :list="[licenseUrl]" @close="showPreview = !showPreview"></PreviewImg>

    <Loading :visible="loading"></Loading>
    
    <CtDialog :visible="showContactList" title="添加联系人" :footer="true" widthType="3" @close="showContactList = false" @submit="contactSubmit">
      <div style="min-height: 50vh;">
        <div>
          <div v-for="(item, index) in contactCopy" :key="index" class="contactItemCard">
            <div class="d-flex justify-space-between pb-2">
              <div class="mb-3 pl-3" style="font-size: 13px; color: 00897B; border-left: 5px solid #00897B;">{{ index ? '联系人' + index : '管理员' }}</div>
              <v-btn v-if="index" color="error" density="compact" variant="text" @click="delContact(index)">删除</v-btn>
              <div v-else style="font-size: 12px; color: #999">不可删除</div>
            </div>
            <TextUI v-model="item.contactName" :item="{...contactNameObj}"></TextUI>
            <TextUI v-model="item.phone" :item="{...phoneObj}"></TextUI>
            <TextUI v-model="item.email" :item="{...emailObj}"></TextUI>
            <TextUI v-model="item.password" :item="{...passwordObj}"></TextUI>
            <TextUI v-model="item.passwordConfirm" :item="{...passwordConfirmObj}"></TextUI>
          </div>
        </div>
        <v-btn class="mb-5 mt-3" style="width: 100%; text-align: center;" color="primary" prepend-icon="mdi-plus-box" @click="addMore">继续添加</v-btn>
      </div>
    </CtDialog>
  </div>
</template>

<script setup>
defineOptions({name: 'enterprise-enterpriseRegister-register'})
import CtForm from '@/components/CtForm'
import Snackbar from '@/plugins/snackbar'
import { useI18n } from '@/hooks/web/useI18n'
import { useRouter } from 'vue-router'; const router = useRouter()
import { enterpriseRegisterApply } from '@/api/personal/user'
import { onMounted, ref, computed } from 'vue';
import { checkEmail } from '@/utils/validate'
import { getBusinessLicenseOCR } from '@/api/common'
import Confirm from '@/plugins/confirm'
import TextUI from '@/components/FormUI/TextInput'

const { t } = useI18n()
const CtFormRef = ref()
const loginLoading = ref(false)

// 图片预览
const loading = ref(false)
const showPreview = ref(false)
const current = ref(0)
const business = ref({})
let licenseUrl = ref('')
const email = localStorage.getItem('loginAccount') || ''

// 组件挂载后添加事件监听器
const isMobile = ref(false)
onMounted(() => {
  const userAgent = navigator.userAgent
  isMobile.value = /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i.test(userAgent)
})

import { useRoute } from 'vue-router'; const route = useRoute()
const pageType = route?.query?.type || '' // type: noLoginToRegister:->登录页注册企业

const showContactList = ref(false)
const contactInfo = { contactName: '', phone: '', email: '', password: '', passwordConfirm:'' }
let contactList = [{ ...contactInfo }]
const contactCopy = ref([])
const contactSubmit = () => {
  let falseValueIndex = null
  let falseKey = null
  contactCopy.value.forEach((e, index) => {
    if (falseValueIndex !== null) return
    if (e && Object.keys(e).length) {
      Object.keys(e).forEach(key => {
        if (falseValueIndex !== null) return
        if (!e[key]) {
          falseValueIndex = index
          falseKey = key
        }
      })
    }
    if (e.password && e.passwordConfirm && e.password !== e.passwordConfirm) 
    falseValueIndex = index
    falseKey = 'compareFalse'
  })
  const textList =  {
    contactName: '姓名',
    phone: '联系电话',
    email: '企业邮箱',
    password: '登录密码',
    passwordConfirm: '登录密码',
  }
  if (falseValueIndex || falseValueIndex === 0) {
    //
    let text = ''
    if (falseKey === 'compareFalse') {
      text = falseValueIndex ? `【联系人${falseValueIndex}】两次输入的密码不一致` : `【管理员】两次输入的密码不一致`
    } else {
      text = falseValueIndex ? `请完善联系人${falseValueIndex}的【${textList[falseKey]}】` : `请完善管理员的【${textList[falseKey]}】`
    }
    Confirm(t('common.confirmTitle'), text, { hideCancelBtn: true })
    return
  } 
  contactList = [...contactCopy.value]
  showContactList.value = false
  saveRegisterInfo()
}
const handleAddContact = () => {
  contactCopy.value = [...contactList]
  showContactList.value = true
}
const addMore = () => {
  contactCopy.value.push({...contactInfo})
}
const delContact = (index) => {
  Confirm('系统提示', `是否确认删除${index ? `联系人${index}` : '管理员'}？`).then(async () => {
    contactCopy.value.splice(index, 1)
  })
}

// 注册信息保存
const enterpriseRegisterInfo = ref(localStorage.getItem('enterpriseRegisterInfo') ? JSON.parse(localStorage.getItem('enterpriseRegisterInfo')) : {})
const saveRegisterInfo = () => {
  const obj = {
    licenseUrl: licenseUrl.value,
    ocr: business.value
  }
  formItems.value.options.forEach(e => {
    if (e.key) obj[e.key] = e.value
  })
  obj.contactList = contactList
  localStorage.setItem('enterpriseRegisterInfo', JSON.stringify(obj))
}

const codeLabelTet = '企业统一社会信用代码（可从上传的营业执照自动识别）'
// 是否筹建中
const isPrepareChange = () => {
  const code = formItems.value.options.find(e => e.key === 'code')
  if (code) {
    code.label = prepareValue.value ? codeLabelTet : codeLabelTet + ' *'
    code.rules = prepareValue.value ? [] : [v => !!v || '请输入企业统一社会信用代码']
  }
  saveRegisterInfo()
}

const formItems = ref({
  options: [
    {
      type: 'ifRadio',
      key: 'prepare',
      value: false,
      label: '是否筹建中 *',
      width: 100,
      items: [
        { label: '是', value: true },
        { label: '否', value: false }
      ],
      change: isPrepareChange
    },
    {
      slotName: 'businessLicense'
    },
    {
      type: 'text',
      key: 'name',
      value: '',
      label: '企业名称（需要与营业执照完全一致，可从上传的营业执照自动识别）*',
      counter: 50,
      rules: [v => !!v || '请输入企业名称'],
      blur: saveRegisterInfo
    },
    {
      type: 'text',
      key: 'anotherName',
      value: '',
      label: '企业别称',
      counter: 50,
      blur: saveRegisterInfo
    },
    {
      type: 'text',
      key: 'code',
      value: '',
      counter: 18,
      label: codeLabelTet + ' *',
      rules: [v => !!v || '请输入企业统一社会信用代码'],
      blur: saveRegisterInfo
    },
    {
      slotName: 'contacts'
    },
    {
      type: 'textarea',
      key: 'description',
      value: '',
      clearable: true,
      resize: true,
      counter: 500,
      rows: 2,
      label: '备注/说明',
      blur: saveRegisterInfo
    },
  ]
})

// 是否筹建中
const prepareValue = computed(() => {
  return formItems.value.options.find(e => e.key === 'prepare').value
})

// 识别营业执照图片
const getOcr = async () => {
  loading.value = true
  try {
    const data = await getBusinessLicenseOCR(licenseUrl.value)
    if (data && Object.keys(data).length) {
      formItems.value.options.find(e => e.key === 'code').value = data.code
      formItems.value.options.find(e => e.key === 'name').value = data.name
      business.value = data
      saveRegisterInfo()
    } else {
      licenseUrl.value = ''
      Confirm(t('common.confirmTitle'), '营业执照图片识别失败,请重新上传清晰合法图片', { hideCancelBtn: true })
    }
  } catch (error) {
    licenseUrl.value = ''
    Confirm(t('common.confirmTitle'), error, { hideCancelBtn: true })
  } finally {
    loading.value = false
  }
}

// 上传
const handleUploadImg = (url) => {
  licenseUrl.value = url
  if (licenseUrl.value) getOcr()
}

const handleDeleteImg = () => {
  licenseUrl.value = ''
  business.value = {}
  formItems.value.options.find(e => e.key === 'code').value = ''
  formItems.value.options.find(e => e.key === 'name').value = ''
  saveRegisterInfo()
}

// 提交 企业注册
const handleCommit = async () => {
  const { valid } = await CtFormRef.value.formRef.validate()
  if (!valid) return

  const businessLicenseUrl = licenseUrl.value;
  if (!prepareValue.value && !businessLicenseUrl) return Snackbar.warning('请上传营业执照图片')
  if (!contactList || !contactList.length || !contactList[0].contactName) return Snackbar.warning('请添加联系人信息')
  const params = {
    businessLicenseUrl,
    prepare: prepareValue.value,
  }
  formItems.value.options.forEach(e => { 
    if (e.key) params[e.key] = e.value
  })
  if (business.value && Object.keys(business.value).length) params.ocr = business.value
  // 联系人
  params.contacts = contactList
  params.contactName = contactList[0].contactName
  params.phone = contactList[0].phone
  params.email = contactList[0].email

  await enterpriseRegisterApply(params)
  localStorage.removeItem('loginAccount')
  localStorage.removeItem('enterpriseRegisterInfo')
  Snackbar.success(t('common.submittedSuccessfully'))
  router.push({ path: '/recruit/entRegister/inReview' })
}

// 不通过的企业注册申请 重新发起
const failureReason = ref('')
const info = JSON.parse(localStorage.getItem('userApplyInfo'))
console.log(1, '23456', info)
// 审核不通过的数据回显
if (info && Object.keys(info).length && info.status === '2') {
  failureReason.value = info?.reason || ''
  licenseUrl.value = info?.businessLicenseUrl
  contactList = info?.contacts.map(e => {
    e.passwordConfirm = e.password
    return e
  }) || [{ ...contactInfo }]
  // prepareValue.value = info?.prepare || false
  formItems.value.options.forEach(e => {
    // if (e.key === 'passwordConfirm') e.value = info.password
    // else e.value = info[e.key]
    e.value = info[e.key]
  })
  isPrepareChange()
} else {
  // 表单信息保存
  if (enterpriseRegisterInfo.value && Object.keys(enterpriseRegisterInfo.value).length) {
    licenseUrl.value = enterpriseRegisterInfo.value.licenseUrl
    business.value = enterpriseRegisterInfo.value?.ocr
    contactList = enterpriseRegisterInfo.value?.contactList || []
    formItems.value.options.forEach(e => {
      if (e.key === 'passwordConfirm') e.value = enterpriseRegisterInfo.value.password
      else e.value = enterpriseRegisterInfo.value[e.key]
    })
    isPrepareChange()
  }
}

const contactNameObj = {
  type: 'text',
  key: 'contactName',
  value: '',
  label: '联系人姓名 *',
  rules: [v => !!v || '请输入联系人姓名'],
}
const phoneObj = {
  type: 'phoneNumber',
  key: 'phone',
  value: '',
  label: '联系电话 *',
  rules: [v => !!v || '请输入联系电话'],
}

const emailObj = {
  type: 'text',
  key: 'email',
  value: email ? email : '',
  label: '企业邮箱 *（此邮箱将用于日后“登录邮箱”）',
  // label: '企业邮箱 * (此邮箱将作为企业登录的账号)',
  rules: [
    value => {
      if (value) return true
      return '请输入企业邮箱'
    },
    value => {
      if (checkEmail(value)) return true
      return '请输入正确的企业邮箱'
    }
  ],
}

const passwordObj = {
  type: 'password',
  key: 'password',
  value: '',
  password: true,
  appendInnerIcon: 'mdi-eye-off-outline',
  label: '账户登录密码 *',
  placeholder: '请输入账户登录密码',
  // appendInnerClick: handlePassword,
  rules: [
    value => {
      if (value) return true
      return '请输入账户登录密码'
    },
    value => {
      if (/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,16}$/.test(value)) return true
      return '请输入8-16位数由数字、大小写字母组成的密码'
    }
  ],
}

const passwordConfirmObj = {
  type: 'password',
  key: 'passwordConfirm',
  value: '',
  password: true,
  appendInnerIcon: 'mdi-eye-off-outline',
  label: '请再次输入账户登录密码 *',
  placeholder: '请再次输入账户登录密码',
  // appendInnerClick: handleSecondConfirm,
  rules: [
    value => {
      if (value) return true
      return '请再次输入密码'
    },
  ],
}
</script>

<style lang="scss" scoped>
.CtFormClass {
  margin: 0 auto;
}
.note {
  color: var(--color-666);
  font-size: 14px;
  line-height: 32px;
}
.login-box {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: url('https://www.mendunerhr.com/images/userfiles/92d7e4a755e2428b94aab3636d5047f3/images/recruitment/adImages/2018/11/1920x940.jpg');
  background-size: cover;
}
.file-box {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  width: 100%; /* 设置容器宽度 */
  .file-item {
    height: 80px;
    width: 100px;
    border-radius: 5px;
    margin-right: 8px;
    margin-top: 12px;
    // border: 1px solid rgb(188, 188, 188);
    border: 1px solid rgba(188, 188, 188, 0.5);
  }
  .file-input-box {
    position: relative;
    border: 1px solid rgb(188, 188, 188);
    cursor: pointer;
    .icon {
      position: absolute;
      top: 45%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: var(--color-999);
    }
  }
  // 验证是否为空
  .verifyAct {
    color: var(--v-error-base);
    border: 1px solid var(--v-error-base);
    .icon { color: var(--v-error-base); }
  }
}
.PrepareBox {
  margin-top: 74px;
  margin-left: 32px;
}
.mobileBox {
  width: calc(100vw - 16px);
  margin: 0 auto;
  .resume-header {
    margin-bottom: 12px;
  }
}
.contactItemCard {
  background-color: var(--default-bgc);
  border-radius: 8px;
  padding: 16px 24px;
  margin-bottom: 20px;
}
</style>
