<template>
  <el-form
      ref="formRef"
      v-loading="loading"
      :model="form"
      :rules="rules"
      label-position="top"
      class="w-full sm:py-2"
      size="large"
      status-icon
  >
    <el-tabs v-model="form.type" class="flash bg-white ml-0">
      <el-tab-pane :name="0" label="个人认证"/>
      <el-tab-pane :name="1" label="企业认证"/>
    </el-tabs>
    <!-- 已完成认证 -->
    <template v-if="form.status === 1">
      <template v-if="form.merchantCode == ''">
        <el-result
            icon="success"
            title="个人认证已通过"
            :sub-title="`认证完成时间 ${form.completedTime}`"
        >
          <template #extra>
            <el-button type="text" @click="onUpdate">修改认证信息</el-button>
          </template>
        </el-result>
      </template>
      <template v-else>
        <el-result
            icon="success"
            title="企业认证已通过"
            :sub-title="`认证完成时间 ${form.completedTime}`"
        >
          <template #extra>
            <el-button type="text" @click="onUpdate">修改认证信息</el-button>
          </template>
        </el-result>
      </template>
    </template>
    <!-- 申请被驳回 -->
    <template v-if="form.status === 2">
      <el-result
          icon="error"
          title="您的申请已被驳回"
          :sub-title="`${form.reason}`"
      >
        <template #extra>
          <el-button type="text" @click="onUpdate">修改认证信息</el-button>
        </template>
      </el-result>
    </template>
    <!-- 未完成认证 -->
    <template v-if="form.status === 0 && form.checkStatus">
      <el-result
          icon="warning"
          title="审核中"
          :sub-title="`您的申请已提交，请耐心等待工作人员的审核，非常感谢`"
      >
      </el-result>
    </template>
    <template v-if="form.status === 0 && !form.checkStatus">
      <template v-if="form.type == 1">
        <el-form-item label="企业名称" prop="merchantName">
          <el-input v-model="form.merchantName" placeholder="请输入企业名称"/>
        </el-form-item>
        <el-form-item label="社会信用代码" prop="merchantCode">
          <el-input v-model="form.merchantCode" placeholder="请输入社会信用代码"/>
        </el-form-item>
        <el-form-item label="营业执照" required>
          <el-upload
              v-model:file-list="yyzzFile"
              action="https://common-api.websoft.top/api/oss/upload"
              :headers="{
                Authorization: token,
                TenantId: tenantId,
              }"
              :limit="1"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="yyzzRemove"
              :on-success="yyzzOnSuccess"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <div class="flex justify-center">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </div>
          </el-dialog>
        </el-form-item>
        <el-form-item label="门头照片">
          <el-upload
              v-model:file-list="image"
              action="https://common-api.websoft.top/api/oss/upload"
              :headers="{
                Authorization: token,
                TenantId: tenantId,
              }"
              :limit="1"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="imageRemove"
              :on-success="imageOnSuccess"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <div class="flex justify-center">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </div>
          </el-dialog>
        </el-form-item>
        <el-form-item label="其他证件">
          <el-upload
              v-model:file-list="files"
              action="https://common-api.websoft.top/api/oss/upload"
              :headers="{
                Authorization: token,
                TenantId: tenantId,
              }"
              :limit="9"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="filesRemove"
              :on-success="filesOnSuccess"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <div class="flex justify-center">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </div>
          </el-dialog>
        </el-form-item>
      </template>
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="form.realName" placeholder="请输入真实姓名"/>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="form.phone" maxlength="11" placeholder="请输入真实有效的手机号码"/>
      </el-form-item>
      <el-form-item label="身份证号码" prop="idCard">
        <el-input v-model="form.idCard" placeholder="请输入证件号码"/>
      </el-form-item>
      <el-form-item label="身份证" required>
        <el-upload
            v-model:file-list="sfzFile"
            action="https://common-api.websoft.top/api/oss/upload"
            :headers="{
                Authorization: token,
                TenantId: tenantId,
              }"
            :limit="2"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="sfzRemove"
            :on-success="sfzSuccess"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="所属行业" prop="category">
        <el-cascader
            v-model="industry"
            :options="industryData"
            placeholder="请选择所属行业"
            class="w-full"
            @change="handleChange"
        />
      </el-form-item>
      <el-form-item label="业务描述" prop="comments">
        <el-input v-model="form.comments" placeholder="请输入公司业务介绍" :rows="5" type="textarea" />
      </el-form-item>
      <el-form-item label="注册协议">
        <el-checkbox v-model="isAgree">
          请务必提供真实信息，我司有权自行或委托第三方审查您提供的身份信息是否属真实，有效。若提供虚假信息，由此的全部后果由您承担。
        </el-checkbox>
      </el-form-item>
      <el-space class="flex">
        <el-button type="primary" size="large" :disabled="!isAgree" @click="submitForm(formRef)">
          {{ isUpdate ? '提交修改' : '提交申请' }}
        </el-button>
      </el-space>
    </template>
  </el-form>
  <el-dialog v-model="dialogVisible">
    <div class="flex justify-center">
      <el-image w-full :src="dialogImageUrl" alt="查看证件" />
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue'
import {Plus} from '@element-plus/icons-vue'
import type {FormInstance, FormRules, UploadProps, UploadUserFile} from 'element-plus'
import type {ShopMerchantApply} from "~/api/shop/shopMerchantApply/model";
import industryData from '@/assets/json/industry-data.json';
import {useClientRequest} from "~/composables/useClientRequest";
import type {ApiResult} from "~/api";
import {useServerRequest} from "~/composables/useServerRequest";
import type {ShopMerchant} from "~/api/shop/shopMerchant/model";
import useFormData from "~/utils/use-form-data";

const token = useToken();
const tenantId = localStorage.getItem('TID_ADMIN')
const formRef = ref<FormInstance>()
const yyzzFile = ref<UploadUserFile[]>([])
const sfzFile = ref<UploadUserFile[]>([])
const sfzStr = ref<string[]>([]);
const files = ref<UploadUserFile[]>([])
const filesStr = ref<string[]>([])
const image = ref<UploadUserFile[]>([])
const industry = ref<any[]>([])
const loading = ref<boolean>(true)
const isUpdate = ref<boolean>(false)
const isAgree = ref<boolean>(false)

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const {form, assignFields, resetFields} = useFormData<ShopMerchantApply>({
  applyId: undefined,
  type: 0,
  merchantName: undefined,
  merchantCode: undefined,
  image: undefined,
  phone: undefined,
  realName: undefined,
  idCard: undefined,
  sfz1: undefined,
  sfz2: undefined,
  yyzz: undefined,
  name2: undefined,
  shopType: undefined,
  parentId: undefined,
  categoryId: undefined,
  category: undefined,
  commission: undefined,
  keywords: undefined,
  files: undefined,
  ownStore: undefined,
  recommend: undefined,
  completedTime: undefined,
  goodsReview: undefined,
  userId: undefined,
  comments: undefined,
  reason: undefined,
  checkStatus: undefined,
  status: 0,
  sortNumber: undefined
})

const rules = reactive<FormRules<ShopMerchantApply>>({
  realName: [
    {required: true, message: '请输入真实姓名', trigger: 'blur'},
    {min: 2, max: 5, message: '长度应为2-5个字符', trigger: 'blur'},
  ],
  phone: [
    {required: true, message: '请输入手机号码', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'},
  ],
  idCard: [
    {required: true, message: '请输入证件号码', trigger: 'blur'},
    {min: 18, max: 18, message: '证件号码长度应为18位', trigger: 'blur'},
  ],
  merchantName: [
    {required: true, message: '请输入企业名称', trigger: 'blur'}
  ],
  merchantCode: [
    {required: true, message: '请输入社会信用代码', trigger: 'blur'}
  ],
  category: [
    {required: true, message: '请选择所属行业', trigger: 'change'}
  ]
})

const yyzzRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  form.yyzz = '';
}

const yyzzOnSuccess = (e: any) => {
  form.yyzz = e.data.downloadUrl
}

const sfzRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  form.sfz1 = '';
  form.sfz2 = '';
}

const sfzSuccess = (e:any) => {
  sfzStr.value.push(e.data.downloadUrl)
}

const imageOnSuccess = (e: any) => {
  form.image = e.data.downloadUrl
}

const imageRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  form.image = '';
}

const filesRemove: UploadProps['onRemove'] = (uploadFile) => {
  const index = filesStr.value.findIndex(f => f == uploadFile.url);
  filesStr.value.splice(index, 1)
}

const filesOnSuccess = (e: any) => {
  filesStr.value.push(e.data.downloadUrl)
}

// 所属行业
const handleChange = (value: any) => {
  let parent = ''
  let category = ''
  industryData.map(d => {
    if (d.value == value[0]) {
      form.parentId = d.value
      parent = d.label
      if (d.children) {
        d.children.map(c => {
          if (c.value == value[1]) {
            category = c.label
            form.categoryId = c.value
          }
        })
      }
    }
  })
  form.category = `${parent}/${category}`
}

const onUpdate = () => {
  form.status = 0;
  form.checkStatus = false
}


const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const runtimeConfig = useRuntimeConfig();
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!',valid)
      if (form.type == 0) {
        form.shopType = '个人开发者';
        form.merchantName = form.realName;
      }
      if(form.type == 1){
        form.shopType = '企业开发者';
        if(form.yyzz == ''){
          return ElMessage.error('请上营业执照');
        }
        if(filesStr.value.length > 0){
          form.files = JSON.stringify(filesStr.value)
        }
      }
      if(sfzStr.value.length == 1){
        return ElMessage.error('请上传身份证正反面');
      }
      form.sfz1 = sfzStr.value[0];
      form.sfz2 = sfzStr.value[1];
      useClientRequest<ApiResult<any>>(`/shop/shop-merchant-apply`, {
        baseURL: runtimeConfig.public.apiServer,
        method: isUpdate.value ? 'PUT' : 'POST',
        body: form
      }).then(res => {
        if (res.code == 0) {
          ElMessage.success(res.message)
          reload();
        } else {
          return ElMessage.error(res.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  resetFields();
}

const reload = async () => {
  const {data: response} = await useServerRequest<ApiResult<ShopMerchant>>('/shop/shop-merchant-apply/getByUserId')
  if (response.value?.data) {
    isUpdate.value = true;
    assignFields(response.value.data)
    industry.value = []
    industry.value.push(form.parentId)
    industry.value.push(form.categoryId)
    files.value = []
    filesStr.value = []
    yyzzFile.value = []
    sfzFile.value = []
    sfzStr.value = []
    image.value = []
    if(form.sfz1){
      sfzFile.value.push({
        uid: 1,
        url: form.sfz1,
        name: '身份证正面',
      })
    }
    if(form.sfz2){
      sfzFile.value.push({
        uid: 2,
        url: form.sfz2,
        name: '身份证反面',
      })
    }
    if(form.yyzz){
      yyzzFile.value.push({
        uid: 3,
        url: form.yyzz,
        name: '营业执照',
      })
    }
    if(form.image){
      image.value.push({
        uid: 4,
        url: form.image,
        name: '',
      })
    }
    if (form.files) {
      const arr = JSON.parse(form.files)
      let i = 1;
      arr.map(d => {
        files.value.push({
          uid: i++,
          url: d,
          name: '',
        })
        filesStr.value.push(d)
      })
    }
  }
  loading.value = false
}
reload();
</script>
<style scoped>
/* 自定义 el-dialog 的样式 */
.el-dialog {
  background: rgba(255, 255, 255, 0.5); /* 设置背景颜色为半透明白色 */
  backdrop-filter: blur(10px); /* 可选：为背景添加模糊效果 */
}
</style>
