<template>
  <CommonDialog
    :visible="visible"
    type="element"
    :elementDialogProps="{
      title: '新建备案人',
    }"
    :no-padding="true"
    showMask
    elementDialogSize="medium"
    @closePopup="$emit('update:visible', false)"
  >
    <div
      style="padding: 0 54px; margin-top: 24px; height: calc(100vh - 200px)"
      class="overflow-auto"
    >
      <div class="mb-9">
        <span class="title">认证信息</span>
        <span class="tip">认证信息在获得认证后将不能修改</span>
      </div>
      <ElForm :model="modelOfCert" :rules="rulesOfCert" ref="certFormRef">
        <CustomizeFormItem
          :width="95"
          label="姓名/名称"
          prop="name"
          class="flex w-full"
        >
          <syDialogInput
            v-model:value="modelOfCert.name"
            placeholder="请输入姓名/名称"
            style="width: 100%"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem
          :width="95"
          label="主体性质"
          prop="property"
          class="flex w-full"
        >
          <ElRadioGroup v-model="modelOfCert.property">
            <syRadio :label="1">自然人</syRadio>
            <syRadio :label="2">企业组织</syRadio>
          </ElRadioGroup>
        </CustomizeFormItem>
        <CustomizeFormItem
          v-if="modelOfCert.property === 1"
          :width="95"
          label="身份证号码"
          prop="idCard"
          class="flex w-full"
        >
          <syDialogInput
            v-model:value="modelOfCert.idCard"
            placeholder="请输入身份证号码"
            style="width: 100%"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem
          v-if="modelOfCert.property === 2"
          :width="95"
          label="统一社会信用代码/营业执照号码"
          prop="unifiedSocialCreditCode"
          class="flex w-full"
        >
          <syDialogInput
            v-model:value="modelOfCert.unifiedSocialCreditCode"
            placeholder="请输入统一社会信用代码/营业执照号码"
            style="width: 100%"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem
          :width="95"
          label="所在城市"
          prop="city"
          class="flex w-full"
        >
          <ElCascader
            popper-class="fuckCascader"
            class="w-full ElCascader"
            v-model="modelOfCert.city"
            :options="cityList"
          ></ElCascader>
        </CustomizeFormItem>
        <CustomizeFormItem
          v-if="modelOfCert.property === 1"
          :width="95"
          label="上传身份证"
          prop="idCardImg"
          class="flex w-full"
        >
          <CollectIdCardImg v-model="modelOfCert.idCardImg"></CollectIdCardImg>
        </CustomizeFormItem>
        <CustomizeFormItem
          v-if="modelOfCert.property === 2"
          :width="95"
          label="营业执照或副本"
          prop="businessLicenseOrCopy"
          class="flex w-full"
        >
          <CollectImage v-model="modelOfCert.businessLicenseOrCopy"
            >营业执照或副本</CollectImage
          >
        </CustomizeFormItem>
        <CustomizeFormItem
          :width="95"
          label="授权备案"
          prop="auth"
          class="flex w-full"
        >
          <syRadio v-model="modelOfCert.auth" :label="true">授权备案</syRadio>
        </CustomizeFormItem>

        <CustomizeFormItem
          :width="95"
          label="授权书图像"
          prop="powerOfAttorneyImage"
          class="flex w-full"
        >
          <CollectImage
            v-model="modelOfCert.powerOfAttorneyImage"
            @update:model-value="handle"
            >授权书图像</CollectImage
          >
        </CustomizeFormItem>
        <CustomizeFormItem
          :width="95"
          label="授权有效期"
          prop="authorizationValidityPeriod"
          class="flex w-full"
        >
          <syDatePicker
            placeholder="请输入授权有效期"
            style="width: 100%"
            v-model="modelOfCert.authorizationValidityPeriod"
          ></syDatePicker>
        </CustomizeFormItem>
      </ElForm>
      <div class="mb-9">
        <span class="title">联系信息</span>
        <span class="tip">认证信息在获得认证后将不能修改</span>
      </div>
      <ElForm
        :model="modelOfContact"
        :rules="rulesOfContact"
        ref="contactFormRef"
      >
        <CustomizeFormItem
          :width="95"
          label="联系人"
          prop="name"
          class="flex w-full"
        >
          <syDialogInput
            v-model:value="modelOfContact.name"
            placeholder="请输入联系人名称"
            style="width: 100%"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem
          :width="95"
          label="电子邮件"
          prop="email"
          class="flex w-full"
        >
          <syDialogInput
            v-model:value="modelOfContact.email"
            placeholder="请输入电子邮件"
            style="width: 100%"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem
          :width="95"
          label="手机"
          prop="cellphoneNumber"
          class="flex w-full"
        >
          <syDialogInput
            v-model:value="modelOfContact.cellphoneNumber"
            placeholder="请输入手机"
            style="width: 100%"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem
          :width="95"
          label="电话"
          prop="phoneNumber"
          class="flex w-full"
        >
          <syDialogInput
            v-model:value="modelOfContact.phoneNumber"
            placeholder="请输入电话"
            style="width: 100%"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem
          :width="95"
          label="邮编"
          prop="postCode"
          class="flex w-full"
        >
          <syDialogInput
            v-model:value="modelOfContact.postCode"
            placeholder="请输入邮编"
            style="width: 100%"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem
          :width="95"
          label="传真"
          prop="fax"
          class="flex w-full"
        >
          <syDialogInput
            v-model:value="modelOfContact.fax"
            placeholder="请输入传真"
            style="width: 100%"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem
          :width="95"
          label="联系地址"
          prop="addr"
          class="flex w-full"
        >
          <syDialogInput
            v-model:value="modelOfContact.addr"
            placeholder="请输入联系地址"
            style="width: 100%"
          ></syDialogInput>
        </CustomizeFormItem>
      </ElForm>
      <syButton
        mode="elementBtn"
        type="primary"
        size="large"
        class="w-full"
        :loading="loading"
        @click="handleConfirm"
        >确定提交</syButton
      >
    </div>
  </CommonDialog>
</template>

<script setup lang="ts">
import { formatTime, syButton } from "cqk-sy-ui";
import { ElForm, ElRadioGroup, ElCascader, ElMessage } from "element-plus";
import { computed, ref, watch } from "vue";
import cityList from "@/config/city";
import CustomizeFormItem from "@/components/Form/CustomizeFormItem.vue";
import CollectIdCardImg from "@/components/Form/Collect/CollectIdCardImg.vue";
import { globalState } from "@/store/state";
import CollectImage from "./components/CollectImage.vue";
import { editAuth, postAuth } from "@/service/copyrightService";
import CommonDialog from "@/components/CommonDialog/index.vue";
import syDialogInput from "@/components/CommonInput/index.vue";
import syRadio from "@/components/Radio/index.vue";
import syDatePicker from "../../components/DatePicker/index.vue";

function handle() {
  console.log(...arguments);
}
const props = defineProps<{
  visible: boolean;
}>();
const emit = defineEmits(["update:visible", "addSuccess"]);

const certFormRef = ref<InstanceType<typeof ElForm>>();
const contactFormRef = ref<InstanceType<typeof ElForm>>();

const g = computed(() => globalState);

const loading = ref(false);
const mode = ref("add");
const id = ref(NaN);
const modelOfCert = ref({
  name: "",
  property: 1,
  idCard: "",
  city: [] as string[],
  idCardImg: null as any,
  auth: true,
  authorizationValidityPeriod: "",
  unifiedSocialCreditCode: "",
  businessLicenseOrCopy: null as any,
  powerOfAttorneyImage: null as any,
});
const rulesOfCert = {
  name: [{ required: true, message: "请输入姓名/名称" }],
  property: [{ required: true, message: "选择主体性质" }],
  idCard: [{ required: true, message: "请输入身份证号码" }],
  city: [{ required: true, message: "请选择所在城市" }],
  idCardImg: [{ required: true, message: "请上传身份证" }],
  auth: [],
  powerOfAttorneyImage: [{ required: true, message: "请上传授权书图像" }],
  authorizationValidityPeriod: [
    { required: true, message: "请选择授权有效期" },
  ],
  unifiedSocialCreditCode: [
    {
      required: true,
      message: "请输入统一社会信用代码/营业执照号码",
    },
  ],
  businessLicenseOrCopy: [],
};

const modelOfContact = ref({
  name: "",
  email: "",
  cellphoneNumber: "",
  phoneNumber: "",
  postCode: "",
  fax: "",
  addr: "",
});
const rulesOfContact = {
  name: [
    {
      required: true,
      message: "请输入联系人名称",
    },
  ],
  email: [
    {
      required: true,
      message: "请输入电子邮箱",
    },
  ],
  cellphoneNumber: [
    {
      required: true,
      message: "请输入手机号",
    },
  ],
  phoneNumber: [],
  postCode: [],
  fax: [],
  addr: [{ required: true, message: "请输入联系地址" }],
};

defineExpose({
  modelOfCert,
  modelOfContact,
  mode,
  id,
});

const handleConfirm = () => {
  loading.value = true;
  certFormRef.value?.validate((isValidOfCert) => {
    contactFormRef.value?.validate(async (isValidOfContact, invalidFields) => {
      if (isValidOfCert && isValidOfContact) {
        const { file: f1, ...front } =
          (modelOfCert.value.idCardImg && modelOfCert.value.idCardImg.front) ||
          {};
        const { file: f2, ...back } =
          (modelOfCert.value.idCardImg && modelOfCert.value.idCardImg.back) ||
          {};
        const { file: f3, ...businessLicenseOrCopy } =
          modelOfCert.value.businessLicenseOrCopy || {};
        const { file: f4, ...powerOfAttorneyImage } =
          modelOfCert.value.powerOfAttorneyImage || {};

        const params = {
          authentication_name: modelOfCert.value.name,
          authentication_subject_nature: modelOfCert.value
            .property as unknown as number,
          authentication_subject_nature_code:
            modelOfCert.value.property === 1
              ? modelOfCert.value.idCard
              : modelOfCert.value.unifiedSocialCreditCode,
          authentication_certificate_of_authorization_image:
            powerOfAttorneyImage,
          authentication_certificate_of_authorization_date: formatTime(
            new Date(modelOfCert.value.authorizationValidityPeriod).getTime(),
            "YYYY-MM-DD"
          ),

          contact_person: modelOfContact.value.name,
          contact_email: modelOfContact.value.email,
          contact_mobile: modelOfContact.value.cellphoneNumber,
          contact_telephone: modelOfContact.value.phoneNumber,
          contact_post_code: modelOfContact.value.postCode,
          contact_fax: modelOfContact.value.fax,
          contact_address: modelOfContact.value.addr,
          authentication_province: modelOfCert.value.city[0],
          authentication_city: modelOfCert.value.city[1],
          authentication_district: modelOfCert.value.city[2],
        } as any;

        if (params.authentication_subject_nature === 2) {
          params.authentication_business_license = businessLicenseOrCopy;
        } else if (params.authentication_subject_nature === 1) {
          params.authentication_held_front_id_card = front;
          params.authentication_held_back_id_card = back;
        }
        let ret: any;
        if (mode.value === "add") {
          ret = await postAuth(params);
        } else {
          ret = await editAuth({ ...params, id: id.value });
        }
        if (ret && ret.code === 200) {
          emit("update:visible", false);
          if (mode.value === "add") {
            ElMessage.success("新建成功");
          } else {
            ElMessage.success("编辑成功");
          }
          emit("addSuccess");
        } else {
        }
        loading.value = false;
      }
    });
  });
};

watch(
  () => props.visible,
  () => {
    if (props.visible === false) {
      certFormRef.value?.resetFields();
      contactFormRef.value?.resetFields();
      mode.value = "add";
    }
  }
);
</script>
<style>
.fuckCascader {
  z-index: 3000 !important;
}
</style>

<style lang="scss" scoped>
.title {
  font-size: 18px;
  font-weight: 500;
  color: #000000;
  line-height: 25px;
}
.tip {
  font-size: 14px;
  font-weight: 400;
  color: #ababab;
  line-height: 20px;
  margin-left: 7px;
}
:deep(.ElCascader) {
  .el-input__inner {
    border-radius: 8px;
    height: 36px;
    line-height: 36px;
  }
}
</style>
