<template>
  <vxe-modal
    resize
    v-model="showModal"
    :title="currentType"
    @hide="onHide"
    height="482"
    width="1003"
    show-footer
    esc-closable
  >
    <div class="w-full px-3 h-full overflow-auto flex-col flex mytable">
      <template v-if="currentType === '结清减免还款' || currentType === '直接还款'">
        <table style="margin-bottom: 10px" v-if="currentType === '结清减免还款'">
          <tr>
            <td class="label">减免申请ID</td>
            <td>{{ currentInfo.id }}</td>
            <td class="label">减免截止时间</td>
            <td>{{ currentInfo.applyDate }}</td>
            <td class="label">减免金额(总计)</td>
            <td>{{ currentInfo.totalReduceAmount }}</td>
          </tr>
          <tr>
            <td class="label">减免案件数</td>
            <td>{{ currentInfo.totalNumber }}</td>
            <td class="label">减免生效时间</td>
            <td>{{ currentInfo.inEffectDate }}</td>
            <td class="label">应还金额</td>
            <td colspan="5">{{ Decimal(currentInfo.remainingAmount).sub(currentInfo.totalReduceAmount) }}</td>
          </tr>
          <!-- Add more rows as needed -->
        </table>
        <table style="margin-bottom: 10px" v-else>
          <tr>
            <td class="label">案件ID</td>
            <td>{{ currentInfo.caseId }}</td>
            <td class="label">借款平台</td>
            <td>{{ currentInfo.loanPlatform.name }}</td>
            <td class="label">资管公司</td>
            <td>{{ currentInfo.manageOrg.orgName }}</td>
          </tr>
          <tr>
            <td class="label">委案金额</td>
            <td>{{ currentInfo.commissionAmount }}</td>
            <td class="label">累计减免金额</td>
            <td>{{ currentInfo.sumReductionAmount }}</td>
            <td class="label">剩余待还金额</td>
            <td>{{ currentInfo.remainingAmount }}</td>
          </tr>
          <tr>
            <td class="label">累计还款金额</td>
            <td colspan="5">{{ currentInfo.sumRepayAmount }}</td>
          </tr>
          <!-- Add more rows as needed -->
        </table>
        <div>
          <el-form ref="formRef" inline :model="form" :rules="rules" label-width="110px">
            <el-row>
              <el-col :span="8">
                <el-form-item class="w-full" label="实际还款金额：" prop="realRepayAmount">
                  <div>
                    <el-input
                      v-model="form.realRepayAmount"
                      placeholder="请输入"
                      style="width: 100%"
                    />
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item class="w-full" label="实际还款时间：" prop="name">
                  <el-date-picker
                    v-model="form.realRepayTime"
                    class="w-full"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetime"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="currentType === '结清减免还款'">
                <el-form-item class="w-full" label="付款凭证：" prop="name">
                  <el-upload
                    v-model:file-list="form.files"
                    :action="url"
                    :headers="{timeout:180000}"
                    list-type="picture-card"
                    class="mypicture"
                    :on-success="handleFileSuccess"
                    :auto-upload="true"
                    :on-remove="handleRemove"
                  >
                    <div class="text-center">
                      <el-icon><Plus /></el-icon>
                      <div>付款相关附件</div>
                    </div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
      <template v-if="currentType === '分期还款'">
        <table style="margin-bottom: 10px">
          <tr>
            <td class="label">分期申请ID</td>
            <td>{{ currentDetail.id }}</td>
            <td class="label">还款总额</td>
            <td>{{ currentDetail.totalRepayAmount }}</td>
            <td class="label">分期申请时间</td>
            <td>{{ currentDetail.applyDate }}</td>
          </tr>
          <tr>
            <td class="label">还款期数</td>
            <td>{{ currentDetail.totalPeriod }}</td>
            <td class="label">首期还款日</td>
            <td>{{ currentDetail.firstApplyDate }}</td>
            <td class="label">分期生效时间</td>
            <td>{{ currentDetail.effectiveTime }}</td>
          </tr>
          <tr>
            <td class="label">期次</td>
            <td>{{ currentInfo.period }}</td>
            <td class="label">期次还款到期日</td>
            <td colspan="3">{{ currentInfo.playApplyDate }}</td>
          </tr>
          <tr>
            <td class="label">期次应还金额</td>
            <td>{{ currentInfo.applyAmount }}</td>
            <td class="label">期次还款状态</td>
            <td colspan="3">{{
              currentInfo.repayStatus
                ? currentInfo.repayStatus === 'over'
                  ? '已还款'
                  : '待还款'
                : ''
            }}</td>
          </tr>
        </table>
        <div class="flex">
          <div class="w-2/5 pr-11">
            <el-form ref="formRef" inline :model="form" :rules="rules" label-width="110px">
              <el-row>
                <el-col :span="24">
                  <el-form-item class="w-full" label="实际还款时间：" prop="realRepayTime">
                    <el-date-picker
                      v-model="form.realRepayTime"
                      class="w-full"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetime"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item class="w-full" label="实际还款金额：" prop="realRepayAmount">
                    <div class="w-full">
                      <el-input
                        v-model="form.realRepayAmount"
                        placeholder="请输入"
                        class="w-full"
                      />
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="w-3/5">
            <ProTable
              :config="config"
              :data="tabledata"
              :showPagination="false"
              :showToolBar="false"
            />
          </div>
        </div>
      </template>
      <div class=" font-bold pl-3">还款记录</div>
      <ProTable
        :config="props.returnConfig"
        :data="props.returnData"
        :showPagination="false"
        :showToolBar="false"
      />
    </div>
    <template #footer>
      <el-button type="default" @click="showModal = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </vxe-modal>
</template>

<script setup lang="jsx" name="allocationModal">
  import { computed } from 'vue';
  import dayjs from 'dayjs';
  import Decimal from 'decimal.js';
  import { reactive, ref } from 'vue';
  import { getAppEnvConfig } from '@/utils/env';
  import { ElMessage,ElTag } from 'element-plus';
  import { useDict } from '@/hooks/useDict';
  const { PhoneResultStatus, RepayType, FlowStatus, FollowStatus, AuditStatus, CaseStatus } = useDict("PhoneResultStatus","RepayType", "FlowStatus", "FollowStatus","AuditStatus", "CaseStatus");
  import { saveRepayRecord } from '@/api/property';
  const envs = getAppEnvConfig();
  const data = ref([]);
  const mytransfer = ref();
  const tabledata = ref([]);
  const url = envs.VITE_GLOB_API_URL_PREFIX + '/sys/upload';
  const showModal = ref(false);
  const currentType = ref('');
  const formRef = ref();
  const currentInfo = ref({});
  const currentDetail = ref({});
  const emits = defineEmits(['success']);
  const form = reactive({
    realRepayAmount: '',
    files: [],
    realRepayTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  });
  const props = defineProps({
    mergerCase: String,
    returnConfig: Array,
    returnData: Array
  });
  const radio = ref(0);
  const validaterealRepayAmount = (rule, value, callback) => {
    if (currentType.value === '结清减免还款' &&
      Number(value) !== Number(Decimal(currentInfo.value.remainingAmount).sub(currentInfo.value.totalReduceAmount))
    ) {
      callback(new Error('*金额必须等于应还金额'));
    } else if (
      currentType.value === '直接还款' &&
      Number(value) > Number(currentInfo.value.remainingAmount)
    ) {
      callback(new Error('*金额必须小于应还金额'));
    } else if (
      currentType.value === '分期还款' &&
      Number(value) !== Number(currentInfo.value.applyAmount)
    ) {
      callback(new Error('*金额必须等于应还金额'));
    } else {
      callback();
    }
  };
  const rules = ref({
    realRepayAmount: [{ validator: validaterealRepayAmount, trigger: 'blur' }],
  });
  const onHide = () => {
    // currentInfo.value = {};
  };
  const openModal = (info, detail, type) => {
    showModal.value = true;
    form.realRepayAmount = '';
    form.files = [];
    form.realRepayTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    currentInfo.value = info;
    console.log('currentInfo', currentInfo.value);
    currentDetail.value = detail;
    currentType.value = type;
    tabledata.value = detail.loans;
  };

  const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles);
  };

  const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url;
    dialogVisible.value = true;
  };
  const submitForm = () => {
    console.log('currentInfo.value', currentInfo.value, currentDetail.value, tabledata.value);
    formRef.value.validate((valid) => {
      if (valid) {
        const param = {
          repayType: RepayType.value.find((v) => v.label === currentType.value).value,
          ...form,
          repayAmount: form.realRepayAmount,
          borrower: currentInfo.value.borrower,
          flowStatus: 'pending',
          repayStatus: 'over',
          status: 'enable',
          loanPlatform: currentInfo.value?.loanPlatform?.name,
        };
        if (currentType.value === '结清减免还款') {
          param['loanPlatform'] = currentDetail.value.loanPlatform.name;
          param['reduce'] = {
            id: currentInfo.value.id,
          };
        }
        if (currentType.value === '直接还款') {
          param['loan'] = currentInfo.value;
        }
        if (currentType.value === '分期还款') {
          param['borrower'] = currentDetail.value.borrower;
          param['loanPlatform'] = currentDetail.value.loans[0].loanPlatform.name;
          param['stages'] = {
            id: currentDetail.value.id,
            borrower: currentDetail.value.borrower,
            totalPeriod: currentDetail.value.totalPeriod,
            remainingAmount: currentInfo.value.remainingAmount,
            totalRepayAmount: currentDetail.value.totalRepayAmount,
            applyDate: currentDetail.value.applyDate,
            firstApplyDate: currentDetail.value.firstApplyDate,
            effectiveTime: currentDetail.value.effectiveTime,
            loans: currentDetail.value.loans,
            flowStatus: 'pending',
          };
          const item = currentDetail.value.byStagesRecords.find(
            (v) => currentInfo.value.period === v.period
          );
          item['repayStatus'] = 'over';
          param['stages']['byStagesRecords'] = currentDetail.value.byStagesRecords;
          param['byStagesRecord'] = item;
        }
        saveRepayRecord(param).then((res) => {
          console.log('res', res);
          if (res.success) {
            ElMessage.success({
              message: '保存成功',
              plain: true,
            });
            showModal.value = false;
            emits('success');
          }
        });
      }
    });
  };
  const handleFileSuccess = (response, file, fileList) => {
    console.log('888877', response, file, fileList);
  };
  const config = computed(() => {
    return {
      toolbarConfig: { enabled: false },
      columns: [
        {
          field: 'caseId',
          width: 230,
          slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <div
                  className="inline-block"
                >
                  {row.caseId}
                </div>
                <Tag row={row} />
              </>
            );
          },
        },
          title: '案件ID',
          showOverflow: 'tooltip',
        },
        {
          field: 'loanPlatform.name',
          title: '借款平台',
          showOverflow: 'tooltip',
        },
        {
          field: 'remainingAmount',
          title: '剩余待还金额',
          showOverflow: 'tooltip',
        },
      ],
    };
  });
  defineExpose({
    openModal,
  });
</script>
<style lang="scss" scoped>
  .box-title {
    font-weight: 600;
    font-size: 16px;
    color: #000000;
    line-height: 43px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.06);
    margin-bottom: 10px;
  }
  .mytable {
    .el-form-item {
      margin-right: 0;
    }
    table {
      width: 100%;
      border-collapse: collapse;
    }
    td {
      border: 1px solid rgba(5, 5, 5, 0.06);
      background: #fff;
      color: #606268;
      width: 240px;
      height: 40px;
      font-size: 14px;
      padding-left: 5px;
      line-height: 11px;
      &.label {
        width: 160px;
        text-align: center;
        font-weight: bold;
        background: #f6f8ff;
        color: #909399;
      }
    }
  }
  .mypicture {
    :deep(.el-upload--picture-card) {
      width: 70px;
      height: 70px;
    }
    :deep(.el-upload-list__item) {
      width: 70px;
      height: 70px;
    }
    :deep(.el-upload--picture-card) {
      font-size: 11px;
    }
  }
</style>
