<!-- 工商信息 -->
<template>
  <div style="width: 900px;margin: 0 auto">
    <CtForm ref="CtFormRef" class="mt-3" :items="formItems">
      <template #businessLicense>
        <!-- 上传照片 -->
        <div class="d-flex flex-column mb-6">
          <div style="color: var(--color-999);">
            <!-- <span 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>
    </CtForm>
    <Loading :visible="loading"></Loading>
    <PreviewImg v-if="showPreview" :current="current" :list="[licenseUrl]" @close="showPreview = !showPreview"></PreviewImg>
    <div class="text-center">
      <v-btn color="primary" class="buttons mt-3 mb-10" @click="handleSave">{{ $t('common.save') }}</v-btn>
    </div>
  </div>
</template>

<script setup>
import CtForm from '@/components/CtForm'
import { getEnterpriseBusiness, updateEnterpriseBusiness } from '@/api/enterprise'
import Snackbar from '@/plugins/snackbar'
import { reactive, ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { getBusinessLicenseOCR } from '@/api/common'
import Confirm from '@/plugins/confirm'
// import { getDict } from '@/hooks/web/useDictionaries'
const emit = defineEmits(['complete'])

defineOptions({name: 'informationSettingsComponents-businessInformation'})
const { t } = useI18n()
const showPreview = ref(false)
const current = ref(0)
let licenseUrl = ref('')
// 图片预览
const loading = ref(false)

const formItems = ref({
  options: [
    {
      slotName: 'businessLicense',
      noParam: true,
    },
    {
      type: 'text',
      key: 'name',
      value: '',
      col: 6,
      flexStyle: 'mr-3',
      label: '企业名称 *',
      rules: [v => !!v || '请输入企业名称']
    },
    {
      type: 'text',
      key: 'representative',
      value: '',
      col: 6,
      label: '法定代表人 *',
      rules: [v => !!v || '请输入法定代表人']
    },
    {
      type: 'text',
      key: 'code',
      value: '',
      col: 6,
      flexStyle: 'mr-3',
      label: '统一社会信用代码 *',
      rules: [v => !!v || '请输入统一社会信用代码']
    },
    {
      type: 'text',
      key: 'type',
      value: '',
      col: 6,
      label: '企业类型 *',
      rules: [v => !!v || '请输入企业类型']
    },
    {
      type: 'datePicker',
      key: 'establishmentTime',
      value: '2010-01-01',
      label: '成立时间 *',
      format: 'YYYY-MM-DD',
      defaultValue: new Date(2010, 1, 1),
      labelWidth: 120,
      col: 6,
      flexStyle: 'mr-3'
    },
    {
      type: 'text',
      key: 'registeredCapital',
      value: '',
      col: 6,
      // suffix: '万元',
      label: '注册资金 *',
      rules: [v => !!v || '请输入注册资金']
    },
    {
      type: 'text',
      key: 'approvalTime',
      value: '',
      col: 6,
      flexStyle: 'mr-3',
      label: '核准日期 *',
      rules: [v => !!v || '请输入核准日期']
    },
    {
      type: 'text',
      key: 'registrationAuthority',
      value: '',
      col: 6,
      label: '注册机关 *',
      rules: [v => !!v || '请输入注册机关']
    },
    {
      type: 'text',
      key: 'businessStatus',
      value: '',
      col: 6,
      flexStyle: 'mr-3',
      label: '经营状态 *',
      rules: [v => !!v || '请输入经营状态']
    },
    {
      type: 'text',
      key: 'businessTerm',
      value: null,
      col: 6,
      class: 'mb-3',
      label: '营业期限(示例：2020-03-13 至 2030-03-13) *',
      rules: [v => !!v || '请填写营业期限']
    },
    {
      type: 'text',
      key: 'area',
      value: '',
      col: 6,
      flexStyle: 'mr-3',
      label: '所属地区 *',
      rules: [v => !!v || '请输入所属地区']
    },
    {
      type: 'text',
      key: 'formerName',
      value: '',
      col: 6,
      label: '曾用名',
    },
    {
      type: 'text',
      key: 'address',
      value: '',
      label: '注册地址 *',
      rules: [v => !!v || '请输入注册地址']
    },
    {
      type: 'textarea',
      key: 'businessScope',
      value: null,
      resize: true,
      counter: 1600,
      rows: 5,
      label: '经营范围 *',
      outlined: true,
      rules: [v => !!v || '请输入经营范围']
    },
  ]
})

const business = ref({})
const CtFormRef = ref()
const query = reactive({})

// const info = JSON.parse(localStorage.getItem('userApplyInfo'))

// licenseUrl.value = info?.businessLicenseUrl ?? ''

const handleSave = async () => {
  const { valid } = await CtFormRef.value.formRef.validate()
  if (!valid) return
  formItems.value.options.forEach(e => {
    if (e.noParam) return
    query[e.key] = e.value
  })
  query.businessUrl = licenseUrl.value
  if (!query.establishmentTime) return Snackbar.warning('请选择成立时间')
  await updateEnterpriseBusiness(query)
  Snackbar.success('编辑成功')
  isUpdate = true
  getBaseInfo()
}

let isUpdate = false // 是否同时更新基本信息
// 完成度展示
const completeFun = (completeCount = 0) => {
  const totalCount = formItems.value.options?.length || 0
  emit('complete', { totalCount, completeCount, id: 'businessInformation', isUpdate })
  isUpdate = false // 重置
}

// 识别营业执照图片
const getOcr = async () => {
  loading.value = true
  try {
    const data = await getBusinessLicenseOCR(licenseUrl.value)
    
    if (data && Object.keys(data).length) {
      Confirm(t('common.confirmTitle'), '是否根据营业执照内容替换以下相关信息').then(() => {
        formItems.value.options.forEach(e => {
          if (e.noParam) return
          // if (e.key in data) {
          if (data[e.key]) {
            e.value = data[e.key]
          }
        })
        business.value = data
      })
      
    } 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 getBaseInfo = async () => {
  let completeCount = 0 // 非必填的需要completeCount++
  try {
    const data = await getEnterpriseBusiness()
    if (!data || !Object.keys(data).length) return completeFun(completeCount)
    query.id = JSON.parse(localStorage.getItem('entBaseInfo')).id
    formItems.value.options.forEach(item => {
      if (item.noParam) return completeCount++
      item.value = data[item.key]
      // 完成度展示
      if (!item.rules?.length || (item.value !== undefined && item.value !== null && item.value !== '')) completeCount++
    })
    licenseUrl.value = data.businessUrl
    // 完成度展示
    completeFun(completeCount)
  } catch (error) {
    completeFun(completeCount)
  }
}
getBaseInfo()
</script>
<style lang="scss" scoped>
.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); }
  }
}
</style>
