<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 label="个人认证"/>
      <el-tab-pane 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="所属行业" prop="category">
          <el-cascader
              v-model="industry"
              :options="industryData"
              placeholder="请选择所属行业"
              class="w-full"
              @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="LOGO">
          <el-upload
              v-model:file-list="fileList"
              :limit="1"
              class="upload-demo"
              action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
          >
            <el-button size="default">上传文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="业务描述" prop="comments">
          <el-input v-model="form.comments" :rows="5" type="textarea" />
        </el-form-item>
        <el-form-item label="营业执照">
          <el-upload
              v-model:file-list="fileList"
              :limit="1"
              class="upload-demo"
              action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
          >
            <el-button size="default">上传文件</el-button>
          </el-upload>
        </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="注册协议">
        <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>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue'
import {UploadFilled} from '@element-plus/icons-vue'
import type {ComponentSize, 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 formRef = ref<FormInstance>()
const fileList = ref<UploadUserFile[]>([])
const industry = ref<any[]>([])
const loading = ref<boolean>(true)
const isUpdate = ref<boolean>(false)
const showEdit = ref<boolean>(false)
const isAgree = ref<boolean>(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,
  tenantId: undefined,
  createTime: 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'},
  ],
  sfz1: [
    {required: true, message: '请上传身份证正面', trigger: 'change'}
  ],
  sfz2: [
    {required: true, message: '请上传身份证反面', trigger: 'change'}
  ],
  merchantName: [
    {required: true, message: '请输入企业名称', trigger: 'blur'}
  ],
  merchantCode: [
    {required: true, message: '请输入社会信用代码', trigger: 'blur'}
  ],
  yyzz: [
    {required: true, message: '请上传营业执照', trigger: 'change'}
  ],
  category: [
    {required: true, message: '请选择所属行业', trigger: 'change'}
  ]
})

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (file) => {
  console.log(file)
}

const handleClick = (index: number) => {
  // form.type = index
}
const props = {
  expandTrigger: 'hover' as const,
}

// 所属行业
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 onEdit = () => {
  showEdit.value = !showEdit.value;
}

const runtimeConfig = useRuntimeConfig();
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      if (form.type == '0') {
        form.shopType = '个人开发者';
      }
      if(form.type == '1'){
        form.shopType = '企业开发者';
      }
      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', {baseURL: runtimeConfig.public.apiServer})
  if (response.value?.data) {
    console.log(response.value.data)
    isUpdate.value = true;
    assignFields(response.value.data)
    industry.value = []
    industry.value.push(form.parentId)
    industry.value.push(form.categoryId)
  }
  loading.value = false
}
reload();
</script>
