<template>
  <view class="f-straight wrapper">
    <uni-forms ref="formRef" :modelValue="formData" :rules="formRules" validateTrigger="bind" label-width="105px" label-align="right" label-position="left">
      <uni-forms-item name="prepare" label="筹备中" required>
        <uni-data-checkbox 
          v-model="formData.prepare" 
          selectedColor="#00B760" 
          selectedTextColor="#00B760" 
          :localdata="[{ text: '是', value: true }, { text: '否', value: false }]"
          @change="handleChangePrepare"
        />
      </uni-forms-item>
      <uni-forms-item name="businessLicenseUrl" label="营业执照" :required="required['businessLicenseUrl']">
        <view style="display: flex;flex-wrap: wrap;">
          <view class="upload-img" v-if="formData?.businessLicenseUrl">
            <uni-icons size="35" type="clear" color="#fe574a" style="position: absolute; right: -15px; top: -15px; z-index: 9" @click="handleDeleteImg"></uni-icons>
            <image :src="formData?.businessLicenseUrl" mode="contain" style="width: 200rpx;height: 200rpx;" @click="handlePreviewImage"></image>
          </view>
          <view v-else class="upload-file" @click="uploadPhotos">
            <uni-icons type="plusempty" size="50" color="#f1f1f1"></uni-icons>
          </view>
          <view class="ss-m-t-10 color-999">上传营业执照支持jpg、jpeg、png格式，图片大小不得超过20M</view>
        </view>
      </uni-forms-item>
      <uni-forms-item name="name" label="企业名称" required>
        <uni-easyinput v-model="formData.name" placeholder="请输入"></uni-easyinput>
        <view class="ss-m-t-10 color-999">注：需与营业执照一致，上传营业执照可自动识别</view>
      </uni-forms-item>
      <uni-forms-item name="anotherName" label="对外展示名称" required>
        <uni-easyinput v-model="formData.anotherName" placeholder="请输入"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="code" label="社会信用代码" :required="required['code']">
        <uni-easyinput v-model="formData.code" placeholder="请输入"></uni-easyinput>
        <view class="ss-m-t-10 color-999">注：需与营业执照一致，上传营业执照可自动识别</view>
      </uni-forms-item>
      <uni-forms-item name="description" label="备注/说明">
        <uni-easyinput v-model="formData.description" placeholder="请输入" type="textarea"></uni-easyinput>
      </uni-forms-item>
    </uni-forms>

    <button class="send-button" @tap="handleNext">下一步</button>
  </view>
</template>

<script setup>
// 扫码登录注册
import { ref, unref } from 'vue'
import { uploadFile } from '@/api/file'
import { getBusinessLicenseOCR } from '@/api/common'

const formRef = ref()
const formData = ref({
  prepare: true,
  businessLicenseUrl: '',
  name: '',
  anotherName: '',
  code: '',
  description: ''
})

const required = ref({
  code: false,
  businessLicenseUrl: false
})

const formRules = ref({
	name:{
		rules: [{required: true, errorMessage: '请输入企业名称' }]
	},
  anotherName:{
		rules: [{required: true, errorMessage: '请输入企业对外展示名称' }]
	},
	prepare: {
		rules: [{required: true, errorMessage: '请选择贵企业是否在筹备中' }]
	}
})

// 图片预览
const handlePreviewImage = () => {
  uni.previewImage({
    current: 0,
    urls: [formData.value.businessLicenseUrl]
  })
}

// 图片删除
const handleDeleteImg = () => {
  formData.value.businessLicenseUrl = ''
  business.value = {}
  formData.value.ocr = null
  formData.value.code = ''
  formData.value.name = ''
}

// 识别营业执照图片
const business = ref({})
const getOcr = async () => {
  uni.showLoading({ title: '识别中...' })
  try {
    const { data } = await getBusinessLicenseOCR(formData.value.businessLicenseUrl)
    if (data && Object.keys(data).length) {
      formData.value.code = data.code
      formData.value.name = data.name
      business.value = data
    } else {
      formData.value.businessLicenseUrl = ''
      uni.showToast({
        title: '识别失败，请重新上传清晰合法图片',
        icon: 'none',
        duration: 2000
      })
    }
  } catch (error) {
    formData.value.businessLicenseUrl = ''
    console.error(error, 'error')
    uni.hideLoading()
    uni.showToast({
      title: '识别失败，请重新上传清晰合法图片',
      icon: 'none',
      duration: 2000
    })
  } finally {
    uni.hideLoading()
  }
}

// 选择营业执照
const uploadPhotos = () => {
  wx.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: function(res){
      const size = res.tempFiles[0]?.size || 0
      if (size >= 31457280) {
        uni.showToast({
          icon: 'none',
          title: '上传图片大小不得超过 20MB !',
          duration: 2000
        })
        return
      }
      const path = res.tempFilePaths[0]
      uploadFile(path, 'img').then(res => {
        formData.value.businessLicenseUrl = res.data
        getOcr()
      }).catch(error => {
        uni.showToast({
          icon: 'error',
          title: '图片上传失败!',
          duration: 2000
        })
      })
    }
  })
}

// 是否筹备中
const handleChangePrepare = (e, clear = true) => {
  const prepare = e.detail.value
  for(let i in required.value) {
    required.value[i] = !prepare
  }
  formRules.value.code = { rules: !prepare ? [{required: true, errorMessage: '请填写统一社会信用代码' }] : [] }
  formRules.value.businessLicenseUrl = { rules: !prepare ? [{required: true, errorMessage: '请上传营业执照' }] : [] }
  if (clear) formRef.value.clearValidate()
}

// 申请拒绝-重新提交数据回显
const applyInfo = ref(uni.getStorageSync('entRegisterData') ? JSON.parse(uni.getStorageSync('entRegisterData')) : {})
console.log(applyInfo.value, '申请拒绝-重新提交数据回显')
if (applyInfo.value && Object.keys(applyInfo.value).length > 0 && applyInfo.value.status === '2') {
  for (let i in formData.value) {
    formData.value[i] = applyInfo.value[i]
  }
  business.value = applyInfo.value?.orc || {}
  handleChangePrepare({ detail: { value: applyInfo.value.prepare }}, false)
}

// 登录
const handleNext = async () => {
  const validate = await unref(formRef).validate()
  if (!validate) return

  // if (business.value && Object.keys(business.value).length) formData.value.ocr = business.value
  
  // const isEdit = applyInfo.value && Object.keys(applyInfo.value).length > 0 && applyInfo.value.status === '2'
  // if (isEdit) formData.value.id = applyInfo.value.id
  console.log(formData.value, 'index-next-formData')

  // uni.setStorageSync('registerInfo', JSON.stringify(formData.value))
  // uni.navigateTo({
  //   url: isEdit ? '/pages/register/contact?isEdit=true' : '/pages/register/contact'
  // })
}
</script>

<style scoped lang="scss">
.wrapper{
	padding: 15px;
  padding-top: 30px;
}
.upload-img{
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border: 1px solid #f1f1f1;
  margin: 10rpx;
}
.upload-file{
  width: 200rpx;
  height: 200rpx;
  border: 1px solid #f1f1f1;
  margin: 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 10rpx;
}
</style>
