<template>
  <el-form
    ref="formRef"
    v-loading="loading"
    :model="form"
    :rules="rules"
    label-position="top"
    class="w-full sm:py-2 ml-4 mt-1"
    size="large"
    status-icon
  >
    <el-tabs v-model="form.type">
      <el-tab-pane :name="0" label="个人认证">
        <!-- 未完成认证 -->
        <template v-if="form.status === 0 && form.checkStatus">
          <el-result
            icon="warning"
            title="审核中"
            :sub-title="`您的申请已提交，请耐心等待工作人员的审核，非常感谢`"
          >
          </el-result>
        </template>
        <!-- 已完成认证 -->
        <template v-if="form.status === 1">
          <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-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-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" disabled maxlength="11" placeholder="请输入真实有效的手机号码"/>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="form.realName" placeholder="请输入真实姓名"/>
          </el-form-item>
          <el-form-item label="身份证号码" prop="idCard" required>
            <el-input v-model="form.idCard" placeholder="请输入证件号码"/>
          </el-form-item>
          <el-form-item label="身份证">
            <el-upload
              v-model:file-list="sfzFile"
              action="https://server.gxwebsoft.com/api/oss/upload"
              :headers="{
                Authorization: token,
                TenantId: 5,
              }"
              :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-tab-pane>
      <el-tab-pane :name="1" label="企业认证">
        <!-- 未完成认证 -->
        <template v-if="form.status === 0 && form.checkStatus">
          <el-result
            icon="warning"
            title="审核中"
            :sub-title="`您的申请已提交，请耐心等待工作人员的审核，非常感谢`"
          >
          </el-result>
        </template>
        <!-- 已完成认证 -->
        <template v-if="form.status === 1">
          <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-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-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://server.gxwebsoft.com/api/oss/upload"
              :headers="{
                Authorization: token,
                TenantId: 5,
              }"
              :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://server.gxwebsoft.com/api/oss/upload"
              :headers="{
                Authorization: token,
                TenantId: 5,
              }"
              :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://server.gxwebsoft.com/api/oss/upload"
              :headers="{
                Authorization: token,
                TenantId: 5,
              }"
              :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>
          <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" disabled maxlength="11" placeholder="请输入真实有效的手机号码"/>
          </el-form-item>
          <el-form-item label="身份证号码" prop="idCard" required>
            <el-input v-model="form.idCard" placeholder="请输入证件号码"/>
          </el-form-item>
          <el-form-item label="身份证">
            <el-upload
              v-model:file-list="sfzFile"
              action="https://server.gxwebsoft.com/api/oss/upload"
              :headers="{
                Authorization: token,
                TenantId: 5,
              }"
              :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-tab-pane>
    </el-tabs>
    <el-dialog v-model="dialogVisible">
      <div class="flex justify-center">
        <el-image w-full :src="dialogImageUrl" alt="查看证件"/>
      </div>
    </el-dialog>
  </el-form>
</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 useFormData from "~/utils/use-form-data";
import {
  addShopMerchantApply, getShopMerchantApplyByPhone,
  getShopMerchantApplyByUserId,
  updateShopMerchantApply
} from "~/api/shop/shopMerchantApply";
import {useUser} from "~/composables/configState";


const emit = defineEmits<{
  (e: 'done', status: boolean): void
}>()

const token = useToken();
const user = useUser();
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: user.value.phone,
  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 submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate(async (valid) => {
    if (!valid) return;

    console.log('submit!', valid);

    if (form.type === 0) {
      form.shopType = '个人开发者';
      form.merchantName = form.realName;
    }

    if (form.type === 1) {
      form.shopType = '企业开发者';
      if (!form.yyzz) {
        ElMessage.error('请上传营业执照');
        return;
      }
      if (filesStr.value.length > 0) {
        form.files = JSON.stringify(filesStr.value);
      }
    }

    if (sfzStr.value.length < 2) {
      ElMessage.error('请上传身份证正反面');
      return;
    }

    form.sfz1 = sfzStr.value[0];
    form.sfz2 = sfzStr.value[1];

    const saveOrUpdate = isUpdate.value ? updateShopMerchantApply : addShopMerchantApply;

    try {
      const res = await saveOrUpdate({
        ...form,
        files: filesStr.value.length ? JSON.stringify(filesStr.value) : undefined,
        yyzz: form.yyzz || undefined,
        sfz1: form.sfz1 || undefined,
        sfz2: form.sfz2 || undefined,
      });
      console.log(res);
      ElMessage.success('提交成功');
      await reload()
    } catch (err) {
      console.log(err)
    }
  });
};


const reload = async () => {
  getShopMerchantApplyByPhone()
    .then(data => {
      assignFields(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 (user.value.phone) {
        form.phone = user.value.phone;
      }
      if (form.sfz1) {
        sfzFile.value.push({
          uid: 1,
          url: form.sfz1,
          name: '身份证正面',
        })
        sfzStr.value.push(form.sfz1)
      }
      if (form.sfz2) {
        sfzFile.value.push({
          uid: 2,
          url: form.sfz2,
          name: '身份证反面',
        })
        sfzStr.value.push(form.sfz2)
      }
      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((item: any) => {
          files.value.push({
            uid: i++,
            url: item,
            name: '',
          })
          filesStr.value.push(item)
        })
      }
      if(form.status == 1){
        emit('done',true)
      }
      isUpdate.value = true
    })
    .catch(() => {
      resetFields();
      emit('done',false)
    })
    .finally(() => {
      loading.value = false
    })
}
reload();
</script>
