<template>
    <vxe-modal
      resize
      v-model="showModal"
      title="合同详情"
      height="612"
      width="1303"
      show-footer
      esc-closable
    >
      <div class="card content-box addModel">
        <div class="w-full">
            <el-form
                ref="formRef"
                :model="form"
                label-position="top"
                :rules="rules"
                >
                <el-row :gutter="20">
                    <template v-if="form.financeFlowStatus">
                        <el-col :span="12">
                        <el-form-item label="财务审核意见：" prop="name">
                            {{form.financeRepairOpinion}}
                        </el-form-item>
                        </el-col>
                        <el-col :span="12">
                        <el-form-item label="财务审核状态：" prop="name">
                                    {{form.financeFlowStatus
                        ? FlowStatus?.find((v) => v.value === form.financeFlowStatus)?.label
                        : ''}}
                        </el-form-item>
                        </el-col>
                        
                    </template>
                    <el-col :span="12">
                    <el-form-item label="合同编号：" prop="name">
                        <el-input
                        v-model="form.contractNo"
                        :disabled="currentRow"
                        placeholder="请输入"
                        />
                    </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    <el-form-item class="w-full" label="合同签订主体：" prop="code">
                        <el-input
                        v-model="form.contractSignBody"
                        :disabled="!showEdit"
                        placeholder="请输入"
                        />
                    </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    <el-form-item class="w-full" label="业务名称：" prop="code">
                        <el-input
                        v-model="form.businessName"
                        :disabled="!showEdit"
                        placeholder="请输入"
                        />
                    </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    <el-form-item class="w-full" label="客户名称：" prop="code">
                        <el-input
                        v-model="form.customerName"
                        :disabled="!showEdit"
                        placeholder="请输入"
                        />
                    </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    <el-form-item class="w-full" label="身份证号：" prop="idCard">
                        <el-input
                        v-model="form.idCard"
                        :disabled="!showEdit"
                        placeholder="请输入"
                        />
                    </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    <el-form-item class="w-full" label="缴费形式：" prop="paymentForm">
                        <el-select v-model="form.paymentForm"  placeholder="请选择" :disabled="!showEdit">
                        <el-option
                            v-for="item in PaymentForm"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            :disabled="item.disabled"
                        />
                        </el-select>
                    </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    <el-form-item class="w-full" label="服务费总额：" prop="code">
                        <el-input
                        v-model="form.serviceFeeTotal"
                        type="number"
                        :disabled="!showEdit"
                        placeholder="请输入"
                        />
                    </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    <el-form-item class="w-full" label="服务期限：" prop="code">
                        <el-input
                        v-model="form.serviceTerm"
                        :disabled="!showEdit"
                        placeholder="请输入"
                        />
                    </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                    <el-form-item class="w-full" label="合同状态：" prop="name">
                        <el-select v-model="form.contractStatus"  placeholder="请选择" :disabled="!showEdit">
                        <el-option
                            v-for="item in ContractStatus"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            :disabled="item.disabled"
                        />
                        </el-select>
                    </el-form-item>
                    </el-col> -->
                    <el-col :span="24">
                    <el-form-item class="w-full" label="合同附件" prop="code">
                        <el-upload
                        :action="url"
                        :headers="{timeout:180000}"
                        v-if="showModal"
                        v-model:file-list="form.contractScanFileList"
                        list-type="picture-card"
                        ref="mypictureRef"
                        class="mypicture"
                        :on-preview="handlePictureCardPreview"
                        :on-success="handleFileSuccess1"
                        :on-remove="handleRemove1"
                        >
                        <div class="text-center">
                            <el-icon><Plus /></el-icon>
                            <div>合同相关附件</div>
                        </div>
                        <template #file="{ file }">
                        <img
                        class="el-upload-list__item-thumbnail"
                        :src="updataIf(file) ? getImageUrl() :file.url"
                        alt=""
                        >
                        <span class="el-upload-list__item-actions">
                        <span
                            class="el-upload-list__item-delete"
                        >
                            <el-icon @click="handleRemove1(file)">
                            <Delete />
                            </el-icon>
                        </span>
                        <span
                            class="el-upload-list__item-preview"
                        >
                            <el-icon v-if="updataIf(file)" @click="download(file.url)">
                            <Download />
                            </el-icon>
                            <el-icon v-else @click="handlePictureCardPreview(file)">
                            <ZoomIn  />
                            </el-icon>
                        </span>
                        </span>
                    </template>
                        </el-upload>
                    </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="mb-5 w-full flex justify-end">
          <el-button type="default" @click="showModal = false">取消</el-button>
          <template v-if="showEdit">
            <el-button type="primary" @click="submitForm">保存</el-button>
          </template>
          <el-button type="primary" @click="showEdit = true" v-if="currentRow">修改</el-button>
          <!-- <el-button type="danger" @click="delItem" v-if="currentRow">删除</el-button> -->
        </div>
      </div>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </vxe-modal>
  </template>
  
  <script setup name="credit">
    import { ref, computed } from 'vue';
    import { useDict } from '@/hooks/useDict';
    import { ElMessage } from 'element-plus';
    import { inject, reactive } from 'vue';
    import { getAppEnvConfig } from '@/utils/env';
    const showEdit = ref(false);
    const dialogImageUrl = ref('');
    const dialogVisible = ref(false);
    import { saveContract  } from '@/api/customer';
    const downloadfile = inject('download');
    import { useUserStore } from '@/stores/modules/user';
    const showModal = ref(false);
    const { PaymentForm, ContractStatus, FlowStatus } = useDict("PaymentForm", "ContractStatus", "FlowStatus");
    const emits = defineEmits(['success']);
    const currentRow = ref(null);
    const formRef = ref()
    const currentIndex = ref(null);
    const props = defineProps({
      mergerCase: String,
      returnConfig: Array,
      returnData: Array
    });
    const rules = ref({
        idCard: [
          { required: true, message: '请填写证件号码', trigger: 'blur' },
          {
            pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
            message: '证件号码格式有误！',
            trigger: 'blur'
          }
        ],
        paymentForm: { required: true, message: '请填写证件号码', trigger: 'blur' }
    });
    const userStore = useUserStore();
    const envs = getAppEnvConfig();
    const url = envs.VITE_GLOB_API_URL_PREFIX + '/sys/upload';
    const form = ref({
        contractNo: '',
        contractSignBody: '',
        businessName: '',
        customerName: '',
        paymentForm: '',
        serviceFeeTotal: '',
        serviceTerm: '',
        contractScanFile: '',
        contractStatus: 'created',
        "financeRepairUser": null,
        "financeFlowStatus": null,
        "financeRepairOpinion": null,
        "financeRepairTime": null,
        "legalRepairUser": null,
        "legalFlowStatus": null,
        "legalRepairOpinion": null,
        "legalRepairTime": null,
        contractScanFileList: []
    });
    const handlePictureCardPreview = (uploadFile) => {
        dialogImageUrl.value = uploadFile.url;
        dialogVisible.value = true;
    };
    const download = (item) => {
        const name = item.slice(item.lastIndexOf('/') + 1, item.length);
        downloadfile(item.replace(envs.VITE_GLOB_API_URL_PREFIX, ''), {}, name);
    };
    const handleFileSuccess1 = (response, file, fileList) => {
        if (file.uid) {
        const item = form.value.contractScanFileList.find((v) => v.uid === file.uid);
        item.url = envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + response.message;
        }
    };
    const getImageUrl = () => {
        return new URL(`@/assets/images/file.svg`, import.meta.url).href;
    }
    const handleRemove1 = (uploadFile, uploadFiles) => {
        const index = form.value.contractScanFileList.findIndex((v) => v.name === uploadFile.name);
        form.value.contractScanFileList.splice(index, 1);
    };
    const updataIf = (e) => {
        if (e.fileName) {
        if (e.fileName.split('.')[1] === 'png' || e.fileName.split('.')[1] === 'jpeg' || e.fileName.split('.')[1] === 'jpg') {
            return false
        } else {
            return true
        }
        } else {
        if (e.name.split('.')[1] === 'png' || e.name.split('.')[1] === 'jpeg' || e.name.split('.')[1] === 'jpg') {
            return false
        } else {
            return true
        }
        }
    }
    const submitForm = async () => {
    //   if(!form.value.bank && form.value.bank !== 0) {
    //     return ElMessage.warning({
    //         message: '请填写发卡银行',
    //         plain: true,
    //       });
    //   }
    //   if(!form.value.quota && form.value.quota !== 0) {
    //     return ElMessage.warning({
    //         message: '请填写授信额度',
    //         plain: true,
    //       });
    //   }
    await formRef.value.validate();
    let images = JSON.parse(JSON.stringify(form.value.contractScanFileList.map((v) => v.url)));
    images = images.map((v) => {
      return v.replace(envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/', '');
    });
    const params = JSON.parse(JSON.stringify({
        ...form.value,
        contractScanFile: images.join(','),
        contractFile: images.join(','),
        user:{
            username: userStore.userInfo?.username
        }
    }))
    delete params.contractScanFileList
    saveContract(params).then(res => {
        if(res.success) {
            ElMessage.success({
            message: '保存成功',
            plain: true,
          });
          showEdit.value = false
            showModal.value = false;
            emits('success');
        }
    })

    };
    const delItem = () => {
      emits('success', form, currentIndex.value, 'del');
      showModal.value = false;
    }
    const openModal = (row, edit) => {
      if (row) {
        form.value = JSON.parse(JSON.stringify(row))
        const arr = form.value.contractScanFile.split(',')
        form.value.contractScanFileList = arr
        ? arr.map((v) => ({
            name: v.slice(v.lastIndexOf('/') + 1, v.length),
            url: envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + v,
            }))
        : [];
        if (edit) {
            showEdit.value = true
        } else {
            showEdit.value = false
        }
      } else {
        showEdit.value = true
        form.value = {
            contractNo: '',
            contractSignBody: '',
            businessName: '',
            customerName: '',
            paymentForm: '',
            serviceFeeTotal: '',
            serviceTerm: '',
            contractScanFile: '',
            contractStatus: 'created',
            "financeRepairUser": null,
            "financeFlowStatus": null,
            "financeRepairOpinion": null,
            "financeRepairTime": null,
            "legalRepairUser": null,
            "legalFlowStatus": null,
            "legalRepairOpinion": null,
            "legalRepairTime": null,
            contractScanFileList: []
        }
      }
      currentRow.value = row
      showModal.value = true;
    };
    defineExpose({
      openModal,
    });
  
  </script>
  <style lang="scss" scoped>
  table {
    width: calc(100%);
    border-collapse: collapse;
  }
  td {
    border: 1px solid rgba(5, 5, 5, 0.06);
    background: #fff;
    color: #606268;
    // width: 240px;
    line-height: 11px;
    height: 40px;
    font-size: 14px;
    padding-left: 5px;
    &.label {
      text-align: center;
      background: #dfeaf5;
      width: 175px;
      color: #000;
    }
  }
  .addModel {
    :deep(.el-form-item__label) {
        justify-content: flex-start !important;
    }
  }
  </style>
  