<template>
  <el-drawer
    v-model="showModal"
    title="减免申请"
    class="overflow-hidden1"
    :size="800"
    @close="showModal = false"
    direction="rtl"
    :before-close="onHide"
  >
    <div class="h-full overflow-hidden flex-col flex mydrawer">
      <el-form
        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="code">
              <el-date-picker v-model="form.inEffectDate" type="datetime" format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"/>
            </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" />
            </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" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="w-full" label="应还金额：" prop="relation">
              <div>
                <p>{{ form.remainingAmount }}</p>
                <p class="text-red-600 leading-3">*应还金额</p>
              </div>
            </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-model:file-list="form.images"
                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.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 style="height: calc(100% - 250px);overflow: auto;">
        <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">确定</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 { useUserStore } from '@/stores/modules/user';
  import { useAuthStore } from '@/stores/modules/auth';
  import { inject } from 'vue';
  const envs = getAppEnvConfig();
  const userStore = useUserStore();
  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 { authButtonListGet } = useAuthStore(); // 获取用户权限列表
  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: '',
    images: [],
    reduceType: 'settle',
    reason: '',
    remark: '',
    remainingAmount: 0,
    commissionAmount: 0,
    inEffectDate: null,
  });
  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;
    form['commissionAmount'] = 0;
    selectdList.value.forEach((item) => {
      form.totalReduceAmount = (Decimal(form.totalReduceAmount).add(
        Decimal(Number(item.reduceAmount) || 0)).toNumber()
      );
      form.remainingAmount = (Decimal(form.remainingAmount).add(
        Decimal(Number(item.payAmount) || 0)).toNumber()
      );
      form['commissionAmount'] = (Decimal(form['commissionAmount']).add(
        Decimal(item?.loan?.commissionAmount)).toNumber()
      );
    });
  };
  const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url;
    dialogVisible.value = true;
  };
  // 判断文件类型,图片预览，文件下载
  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 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;
    form.commissionAmount = 0;
    selectdList.value.forEach((item) => {
      form.totalReduceAmount = (Decimal(form.totalReduceAmount).add(
        Decimal(Number(item.reduceAmount) || 0)).toNumber()
      );
      form.remainingAmount = (Decimal(form.remainingAmount).add(
        Decimal(Number(item.payAmount) || 0)).toNumber()
      );
      form['commissionAmount'] = (Decimal(form['commissionAmount']).add(
        Decimal(item?.loan?.commissionAmount)).toNumber()
      );
    });
  };
  const currentDetail = ref({});
  const onHide = (done) => {
    done();
  };
  const config = reactive({
    checkboxConfig: {
      checkMethod: ({ row }) => {
        return row.loan.repayStatus !== 'over';
      },
    },
    height: 250,
    'min-height': 250,
    columns: [
      { type: 'checkbox', title: '', width: '40px', fixed: 'left' },
      {
        field: 'loan.caseId',
        showOverflow: 'tooltip',
        width: 230,
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <div className="inline-block">{row.loan.caseId}</div>
                <Tag row={row.loan} />
              </>
            );
          },
        },
        title: '案件ID',
      },
      {
        field: 'mergerCase',
        title: '是否共案处理',
        visible: authButtonListGet.includes('show_merger_case'),
        showOverflow: 'tooltip',
        width: 120,
        slots: {
          default: ({ row }) => {
            return <ElTag>{row.loan.mergerCase == 'Y' ? '是' : '否'}</ElTag>;
          },
        },
      },
      {
        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} 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))).toNumber();
    if(row.payAmount < 0) {
      row.reduceAmount = row.loan.remainingAmount
      row.payAmount = 0
      ElMessage.warning({
        message: '该案件减免金额不能大于委案金额',
        plain: true,
      });
    }
    form.totalReduceAmount = 0;
    form.remainingAmount = 0;
    selectdList.value.forEach((item) => {
      form.totalReduceAmount = (Decimal(form.totalReduceAmount).add(
        Decimal(Number(item.reduceAmount) || 0)).toNumber()
      );
      form.remainingAmount = (Decimal(form.remainingAmount).add(
        Decimal(Number(item.payAmount) || 0)).toNumber()
      );
    });
  };
  const openModal = (detail, caselist) => {
    showModal.value = true;
    currentDetail.value = detail;
    form.totalReduceAmount = 0;
    form.commissionAmount = 0;
    form.remark = '';
    form.reason = '';
    form.remainingAmount = 0;
    const list = [];
    form.images = [];
    mypictureRef.value?.clearFiles();
    const a = [];
    caselist.forEach((item) => {
      const payAmount = Number(item.remainingAmount) || 0;
      const listitem = {
        reduceAmount: Number(item.reduceAmount) || 0,
        payAmount: payAmount,
        loan: item,
      };
      list.push(listitem);
      if (item.repayStatus !== 'over') {
        form.totalReduceAmount = (Decimal(form.totalReduceAmount).add(
          Decimal(Number(item.reduceAmount) || 0)).toNumber()
        );
        a.push(listitem);
        form['commissionAmount'] = (Decimal(form['commissionAmount']).add(
          Decimal(item.commissionAmount)).toNumber()
        );
        form.remainingAmount = (Decimal(form.remainingAmount).add(Decimal(payAmount))).toNumber();
      }
    });
    tabledata.value = list;
    form.totalNumber = a.length;
    setTimeout(() => {
      if (ProTableRef.value.element) {
        ProTableRef.value.element.setCheckboxRow(a, true);
        selectdList.value = a;
      }
    }, 500);
  };
  const submitForm = () => {
    console.log('form.totalReduceAmount', form.totalReduceAmount, form.commissionAmount)
    if (form.totalReduceAmount > form.commissionAmount)
      return ElMessage.warning({
        message: '减免金额不能大于委案金额',
        plain: true,
      });
    const list = JSON.parse(JSON.stringify(selectdList.value));
    if (!list || list.length === 0) {
      return ElMessage.warning({
        message: '至少勾选一个案件',
        plain: true,
      });
    }
    list.forEach((item) => {
      delete item.payAmount;
    });
    const arr1 = list.filter((v) => v.loan.repayStatus === 'over');
    if (arr1.length > 0)
      return ElMessage.warning({
        message: '不可以勾选结案的案件',
        plain: true,
      });
    let images = form.images.map((v) => v.url);
    images = images.map((v) => {
      return v.replace(envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/', '');
    });
    const params = {
      borrower: currentDetail.value.borrower,
      askForStatus: 'Pending',
      flowStatus: 'pending',
      ...form,
      applyTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      applyUser: {
        username: userStore.userInfo?.username,
        id: userStore.userInfo?.id,
      },
      images: images.length > 0 ? images : null,
      reduceRecords: list,
    };
    console.log('sadas', params);
    delete params.id;
    delete params.cpe;
    delete params.tenantTime
    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;
    }
  }
</style>
