<template>
  <el-drawer
    v-model="showModal"
    :size="950"
    class="overflow-hidden1"
    @close="showModal = false"
    direction="rtl"
    :before-close="onHide"
  >
    <template #header="{ titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">减免审批
        <el-tag :type="currentDetail.flowStatus === 'pass' ? 'success' : currentDetail.flowStatus === 'fail' ? 'danger' : 'warning'">{{currentDetail.flowStatus
                    ? FlowStatus?.find((v) => v.value === currentDetail.flowStatus)?.label
                    : ''}}</el-tag>
      </h4>
    </template>
    <div class="h-full flex-col flex mydrawer">
      <div class="flex">
        <div class=" w-1/4 pl-1 flex-shrink-0 after-border">
          <p class=" font-bold mb-3">审批进程</p>
          <div :class="{nopending: currentDetail.flowStatus !== 'pending'}">
            <el-timeline style="max-width: 600px">
              <el-timeline-item
                :timestamp="currentDetail?.createTime"
                color="#234ca3"
              >
                <p class=" font-bold text-sm">发起人</p>
                <span class="text-xs bg-gray-200 rounded-sm text-slate-900 px-2">{{currentDetail?.cpe?.username}}</span>
              </el-timeline-item>
              <el-timeline-item
                :timestamp="currentDetail?.createTime"
                :color="currentDetail.flowStatus !== 'pending' ? '#234ca3' : null"
              >
                <p class=" font-bold text-sm">平台审批环节</p>
                <span class="text-xs bg-gray-200 rounded-sm text-slate-900 px-2">{{currentDetail?.createBy}}</span>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
        <el-form
          class="pl-3"
          ref="formRef"
          inline
          :model="form"
          :rules="rules"
          label-width="110px"
          label-position="left"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item class="w-full" label="姓名：" prop="name" label-width="120px">
                {{ currentDetail?.borrower?.name }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="w-full" label="证件号：" prop="name" label-width="120px">
                {{ currentDetail?.borrower?.idCard }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="w-full" label="产品：" prop="name" label-width="120px">
                {{Array.from(new Set(currentDetail?.reduceRecords.map((v) => v?.loan?.loanPlatform.name))).join(',')}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="w-full" label="调解中心：" prop="name" label-width="120px">
                {{Array.from(new Set(currentDetail?.reduceRecords.map((v) => v.loan?.tenant?.name))).join(',')}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="w-full" label="申请CPE：" prop="name" label-width="120px">
                {{ currentDetail?.cpe?.username }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="w-full" label="申请时间：" prop="name" label-width="120px">
                {{ currentDetail?.createTime }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="w-full" label="减免截止时间：" prop="code">
                <el-date-picker v-model="form.applyDate" type="datetime" disabled />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item class="w-full" label="减免到期时间：" prop="code">
                <el-date-picker v-model="form.datetime" type="datetime" />
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item class="w-full" label="减免金额(总计)：" prop="name" label-width="120px">
                {{ form.totalReduceAmount }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="w-full" label="减免案件数：" prop="role">{{
                form.totalNumber
              }}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="w-full" label="减免原因：" prop="code">
                <el-input v-model="form.reason" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="w-full" label="委案金额：" prop="relation">
                {{ form.commissionAmount }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="w-full" label="备注：" prop="code">
                <el-input v-model="form.remark" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="w-full" label="应还金额：" prop="relation">
                {{ form.remainingAmount }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="w-full" label="附件" prop="code">
                <el-upload
                  :action="url"
                  :headers="{timeout:180000}"
                  list-type="picture-card"
                  v-if="showModal"
                  v-model:file-list="form.images"
                  ref="mypictureRef"
                  disabled
                  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.response.message)">
                          <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>
        <ProTable
          :config="config"
          ref="ProTableRef"
          :data="tabledata"
          :showPagination="false"
          :dataCallback="dataCallback"
          :showToolBar="false"
        >
          <template #table_top>
            <p class="font-bold">关联案件：</p>
          </template>
        </ProTable>
      </div>
    </div>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="showModal = false">取消</el-button>
        <el-button type="primary" @click="submitForm('fail')" v-if="currentDetail.flowStatus === 'pending'">不通过</el-button>
        <el-button type="primary" @click="submitForm('pass')" v-if="currentDetail.flowStatus === 'pending'">通过</el-button>
      </div>
    </template>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </el-drawer>
</template>
<script setup lang="jsx" name="reduceDrawer">
  import dayjs from 'dayjs';
  import { computed } from 'vue';
  import { reactive, ref } from 'vue';
  import { saveReduce } from '@/api/property';
  import { ElMessage, ElTag } from 'element-plus';
  import { Download, ZoomIn } from '@element-plus/icons-vue';
  import { onMounted } from 'vue';
  import { watch } from 'vue';
  import Decimal from 'decimal.js';
  import { getAppEnvConfig } from '@/utils/env';
  import { useDict } from '@/hooks/useDict';
  import { inject } from 'vue';
  const envs = getAppEnvConfig();
  const { PhoneResultStatus, ReduceType, FlowStatus, FollowStatus, AuditStatus, CaseStatus } = useDict("PhoneResultStatus","ReduceType", "FlowStatus", "FollowStatus","AuditStatus", "CaseStatus");
  const emits = defineEmits(['success']);
  const url = envs.VITE_GLOB_API_URL_PREFIX + '/sys/upload';
  const showModal = ref(false);
  const tabledata = ref([]);
  const ProTableRef = ref();
  const mypictureRef = ref();
  const dialogImageUrl = ref('');
  const dialogVisible = ref(false);
  const downloadfile = inject('download');
  const form = reactive({
    totalReduceAmount: 0,
    totalNumber: '',
    reason: '',
    remark: '',
    images: [],
    reduceType: 'settle',
    commissionAmount: 0,
    remainingAmount: 0,
    applyDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  });
  const props = defineProps({
    mergerCase: String,
  });
  const selectdList = ref([]);
  const onCheckboxChange = (row) => {
    selectdList.value = row.records;
    form.totalNumber = row.records.length;
    form.totalReduceAmount = 0;
    form.remainingAmount = 0;
    selectdList.value.forEach((item) => {
      form.totalReduceAmount = Decimal(form.totalReduceAmount).add(
        Decimal(Number(item.reduceAmount) || 0)
      );
      form.remainingAmount = Decimal(form.remainingAmount).add(
        Decimal(Number(item.payAmount) || 0)
      );
    });
  };
  const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url;
    dialogVisible.value = true;
  };
  // 判断文件类型,图片预览，文件下载
  const updataIf = (e) => {
    console.log('eeee', 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 handleRemove1 = (uploadFile) => {
    const index = form.images.findIndex((v) => v.name === uploadFile.name);
    form.images.splice(index, 1);
  };
  const download = (item) => {
    const name = item.slice(item.lastIndexOf('/') + 1, item.length);
    downloadfile('/sys/static/' + item, {}, name);
  };
  const handleFileSuccess1 = (response, file, fileList) => {
    if (file.uid) {
      const item = form.images.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 onCheckboxAll = (flag) => {
    if (flag.checked) {
      selectdList.value = flag.records;
      form.totalNumber = flag.records.length;
    } else {
      selectdList.value = [];
      form.totalNumber = 0;
    }
    form.totalReduceAmount = 0;
    form.remainingAmount = 0;
    selectdList.value.forEach((item) => {
      form.totalReduceAmount = Decimal(form.totalReduceAmount).add(
        Decimal(Number(item.reduceAmount) || 0)
      );
      form.remainingAmount = Decimal(form.remainingAmount).add(
        Decimal(Number(item.payAmount) || 0)
      );
    });
  };
  const currentDetail = ref({});
  const onHide = (done) => {
    done();
  };
  const config = reactive({
    checkboxConfig: {
      checkMethod: ({ row }) => {
        return false;
      },
    },
    minHeight: 200,
    columns: [
      { type: 'checkbox', title: '', width: '40px',fixed: 'left' },
      {
        field: 'loan.caseId',
        width: 230,
        showOverflow: 'tooltip',
        title: '案件ID',
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <div
                  className="inline-block"
                >
                  {row.loan.caseId}
                </div>
                <Tag row={row.loan} />
              </>
            );
          },
        }
      },
      {
        field: 'mergerCase',
        title: '是否共案处理',
        showOverflow: 'tooltip',
        width: 120,
        slots: {
          default: ({ row }) => {
            return <ElTag>{row.loan.mergerCase == 'Y' ? '是' : '否'}</ElTag>;
          },
        },
      },
      {
        field: 'loan.product',
        width: 100,
        showOverflow: 'tooltip',
        title: '产品',
      },
      {
        field: 'loan.loanPlatform.name',
        showOverflow: 'tooltip',
        title: '借款平台',
        width: 90,
      },
      {
        field: 'loan.commissionAmount',
        showOverflow: 'tooltip',
        width: 90,
        title: '委案金额',
      },
      {
        field: 'loan.sumReductionAmount',
        showOverflow: 'tooltip',
        width: 100,
        title: '累计减免金额',
      },
      {
        field: 'loan.sumRepayAmount',
        showOverflow: 'tooltip',
        width: 100,
        title: '累计还款金额',
      },
      {
        field: 'reduceAmount',
        showOverflow: 'tooltip',
        width: 100,
        title: '减免金额',
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <ElInput v-model={row.reduceAmount} disabled onChange={() => changeNum(row, rowIndex)} />
              </>
            );
          },
        },
      },
      {
        field: 'loan.remainingAmount',
        showOverflow: 'tooltip',
        width: 166,
        title: '剩余待还金额（减免前）',
      },
      {
        field: 'payAmount',
        showOverflow: 'tooltip',
        width: 140,
        title: '应还金额（减免后）',
      },
    ],
    onCheckboxChange: onCheckboxChange,
    onCheckboxAll: onCheckboxAll,
    toolbarConfig: { enabled: false },
  });
  const changeNum = (row) => {
    row.payAmount = Decimal(row.loan.remainingAmount).sub(Decimal(row.reduceAmount));
    form.totalReduceAmount = 0;
    form.remainingAmount = 0;
    selectdList.value.forEach((item) => {
      form.totalReduceAmount = Decimal(form.totalReduceAmount).add(
        Decimal(Number(item.reduceAmount) || 0)
      );
      form.remainingAmount = Decimal(form.remainingAmount).add(
        Decimal(Number(item.payAmount) || 0)
      );
    });
  };
  const openModal = (detail) => {
    const caselist = detail.reduceRecords
    showModal.value = true;
    currentDetail.value = detail;
    form.totalReduceAmount = detail.totalReduceAmount;
    form.remark = detail.remark;
    form.reason = detail.reason;
    form.remainingAmount = Decimal(detail.remainingAmount).sub(Decimal(detail.totalReduceAmount));
    form.applyDate = detail.applyDate
    const list = [];
    form['commissionAmount']  = 0
    form.images = detail.images
      ? detail.images.map((v) => ({
          name: v.slice(v.lastIndexOf('/') + 1, v.length),
          url: envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + v,
        }))
      : [];
    caselist.forEach((item) => {
      item['payAmount'] = Decimal(item.loan.remainingAmount).sub(Decimal(item.reduceAmount));
      form['commissionAmount'] = Decimal(form['commissionAmount']).add(Decimal(item.loan.commissionAmount))
    });
    tabledata.value = caselist;
    form.totalNumber = detail.totalNumber;
    setTimeout(() => {
      if (ProTableRef.value.element) {
        ProTableRef.value.element.setAllCheckboxRow(true);
        selectdList.value = caselist;
      }
    }, 500);
  };
  const submitForm = (type) => {
    const list = JSON.parse(JSON.stringify(selectdList.value));

    list.forEach((item) => {
      delete item.payAmount;
    });
    let images = JSON.parse(JSON.stringify(form.images.map((v) => v.url)));
    images = images.map((v) => {
      return v.replace(envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/', '');
    });
    console.log('remainingAmount', form)
    const params = {
      ...currentDetail.value,
      askForStatus: 'Pending',
      flowStatus: type,
      ...form,
      images: images.length > 0 ? images : null,
      reduceRecords: list,
    };
    saveReduce(params).then((res) => {
      if (res.success) {
        ElMessage.success({
          message: '保存成功',
          plain: true,
        });
        showModal.value = false;
        emits('success');
      }
    });
  };
  defineExpose({
    openModal,
  });
</script>
<style lang="scss" scoped>
  .mydrawer {
    :deep(.card) {
      padding: 0;
      border: none;
    }
  }
  .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: 12px;
    }
  }
  .after-border {
    position: relative;
    &::after {
      position: absolute;
      top: -20px;
      right: 0;
      bottom: 0;
      width: 1px;
      background: #e5e7eb;
      content: '';
      display: block;
    }
  }
  .overflow-hidden1 {
    .el-form-item {
      margin-bottom: 5px !important;
    }
  }
  
</style>
<style lang="scss">
  .el-drawer .el-drawer__header .el-tag--warning .el-tag__content {
    color: var(--el-color-warning) !important;
  }
  .el-drawer .el-drawer__header .el-tag--success .el-tag__content {
    color: var(--el-color-success) !important;
  }
  .el-drawer .el-drawer__header .el-tag--danger .el-tag__content {
    color: var(--el-color-danger) !important;
  }
  .overflow-hidden1 {
    .el-drawer__body{
      overflow: hidden;
    }
  }
</style>
