<template>
  <div class="pt-5">
    <div :class="isMobile? 'mobileBox' : 'default-width'">
      <v-btn class="my-2" color="primary" variant="text" size="large" @click="router.go(-1)">{{ `<< 返回上一页` }}</v-btn>
    </div>
    <v-card class="pa-5" :class="isMobile? 'mobileBox' : 'default-width'" :elevation="isMobile? '0' : '3'">
      <!-- 标题 -->
      <div class="resume-header">
        <div class="resume-title">{{ $t('enterprise.registeringNewEnterprise') }}</div>
      </div>
      <!-- 表单 -->
      <div class="CtFormClass" :style="{width: isMobile ? '' : '600px'}">
        <CtForm ref="CtFormRef" :items="formItems" style="width: 100%;"></CtForm>
        <!-- 上传照片 -->
        <div style="color: var(--color-999);">
          <span class="mr-1" style="color: var(--v-error-base);">*</span>
          <span>上传营业执照</span>
          <!-- <span class="mx-3 defaultLink">查看示例</span> -->
          <span>支持jpg、jpeg、png格式，照片大小不得超过10M</span>
        </div>
        <div class="file-box">
          <div class="file-item cursor-pointer" v-if="licenseUrl" @click="showPreview = !showPreview">
            <v-img width="100%" height="100%" :src="licenseUrl"></v-img>
          </div>
          <div class="file-item file-input-box" :class="{'verifyAct': fileVerify}" @click="openFileInput">
            <div class="icon text-center">
              <span class="mdi mdi-plus" style="font-size: 20px;"></span>
              <div style="font-size: 12px; ">上传照片</div>
            </div>
            <input
              type="file"
              ref="fileInput"
              accept="image/png, image/jpg, image/jpeg"
              style="display: none;"
              @change="handleUploadFile"
            />
          </div>
        </div>
        <!-- 注意事项 -->
        <div class="note mt-5">
          <h4>注意事项:</h4>
          <span>企业名称为对外展示的企业名称，建议填写公司营业执照上的名称，请区分总公司和分公司</span>
          <!-- <div>
            <span>2.若公司已注册，请上传公司委托证明下载模版</span>
            <span class="mx-3 defaultLink">下载模版</span>
          </div> -->
        </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>
      <!-- 底部 个人不能绑定企业 要去后端管理员加 -->
      <!-- <div class="text-center">
        <v-btn color="primary" variant="text" @click="router.push({ path: '/recruit/enterprise/register/joiningEnterprise' })">{{ $t('enterprise.joiningEnterprise') }}</v-btn>
      </div> -->
    </v-card>
    <PreviewImg v-if="showPreview" :current="current" :list="[licenseUrl]" @close="showPreview = !showPreview"></PreviewImg>
  </div>
</template>

<script setup>
import CtForm from '@/components/CtForm'
import Snackbar from '@/plugins/snackbar'
import { uploadFile } from '@/api/common'
import { useI18n } from '@/hooks/web/useI18n'
import { useRouter } from 'vue-router'; const router = useRouter()
import { enterpriseRegisterApply } from '@/api/personal/user'
import { onMounted, ref } from 'vue';
defineOptions({name: 'enterprise-enterpriseRegister-register'})
const { t } = useI18n()
const CtFormRef = ref()

const fileVerify = ref(false)
const loginLoading = ref(false)

// 图片预览
const showPreview = ref(false)
const current = ref(0)

// 组件挂载后添加事件监听器  
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)
})

const formItems = ref({
  options: [
    {
      type: 'text',
      key: 'name',
      value: '',
      label: '企业名称（需要与营业执照完全一致）*',
      counter: 50,
      rules: [v => !!v || '请输入企业名称']
    },
    {
      type: 'text',
      key: 'code',
      value: '',
      counter: 18,
      label: '企业统一社会信用代码 *',
      rules: [v => !!v || '请输入企业统一社会信用代码']
    },
    {
      type: 'phoneNumber',
      key: 'phone',
      value: '',
      label: '联系电话 *',
      rules: [v => !!v || '请输入联系电话']
    },
    {
      type: 'text',
      key: 'email',
      value: '',
      label: '联系邮箱 *',
      rules: [v => !!v || '请输入联系邮箱']
    },
  ]
})

// 选择文件
const fileInput = ref()
const clicked = ref(false)
const openFileInput = () => {
  if (clicked.value) return
  clicked.value = true
  fileInput.value.click()
  clicked.value = false
}
// 上传
let licenseUrl = ref('')
const handleUploadFile = async (e) => {
  const file = e.target.files[0]
  const formData = new FormData()
  formData.append('file', file)
  const { data } = await uploadFile(formData)
  if (!data) return
  licenseUrl.value = data
  fileVerify.value = false
  // console.log('uploadFile->data', data)
  Snackbar.success(t('common.uploadSucMsg'))
}
// 提交 企业注册
const handleCommit = async () => {
  // 广州辞图科技有限公司
  const { valid } = await CtFormRef.value.formRef.validate()
  const businessLicenseUrl = licenseUrl.value; if (!businessLicenseUrl) fileVerify.value = true
  if (!valid || !businessLicenseUrl) return
  const baseInfo = {}
  formItems.value.options.forEach(e => { baseInfo[e.key] = e.value })
  await enterpriseRegisterApply({ ...baseInfo, businessLicenseUrl })
  Snackbar.success(t('common.submittedSuccessfully'))
  router.push({ path: '/recruit/enterprise/register/inReview' })
}

// 不通过的企业注册申请 重新发起
const info = JSON.parse(localStorage.getItem('userApplyInfo'))
if (info && Object.keys(info).length) {
  licenseUrl.value = info?.businessLicenseUrl
  formItems.value.options.forEach(e => { e.value = info[e.key] })
}

</script>
<style lang="scss" scoped>
.CtFormClass {
  margin: 0 auto;
}
.note {
  color: var(--color-666);
  font-size: 14px;
  line-height: 32px;
}
.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); }
  }
}
.mobileBox {
  width: 100vw;
  .resume-header {
    margin-bottom: 12px;
  }
}
</style>
