<template>
  <el-drawer
    v-model="showModal"
    title="减免申请"
    :size="800"
    @close="showModal = false"
    direction="rtl"
    :before-close="onHide"
  >
    <div class="h-full overflow-auto 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="82px">
              <el-select v-model="form.reduceType" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </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" />
            </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="relation">
              <div>
                <p>{{ form.remainingAmount }}</p>
                <p class="text-red-600 leading-3">*应还金额</p>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <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">确定</el-button>
      </div>
    </template>
  </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 } from 'element-plus';
  import { onMounted } from 'vue';
  import { watch } from 'vue';
  import Decimal from 'decimal.js';
  const emits = defineEmits(['success']);
  const showModal = ref(false);
  const tabledata = ref([]);
  const ProTableRef = ref();
  const form = reactive({
    totalReduceAmount: 0,
    totalNumber: '',
    reduceType: 'settle',
    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 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 options = [
    {
      value: 'settle',
      label: '结清减免',
    },
    {
      value: 'by_stages',
      label: '分期减免',
    },
  ];
  const config = reactive({
    checkboxConfig: {
      checkMethod: ({ row }) => {
        return props.mergerCase !== 'Y';
      },
    },
    minHeight: 200,
    columns: [
      { type: 'checkbox', title: '', width: '40px' },
      {
        field: 'loan.caseId',
        width: 100,
        showOverflow: 'tooltip',
        title: '案件ID',
      },
      {
        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} 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, caselist) => {
    showModal.value = true;
    currentDetail.value = detail;
    console.log('currentDetail', currentDetail.value, caselist);
    form.totalReduceAmount = 0;
    form.remainingAmount = 0;
    const list = [];
    caselist.forEach((item) => {
      const payAmount = Number(item.remainingAmount) || 0;
      list.push({ reduceAmount: Number(item.reduceAmount) || 0, payAmount: payAmount, loan: item });
      form.totalReduceAmount = Decimal(form.totalReduceAmount).add(
        Decimal(Number(item.reduceAmount) || 0)
      );
      form.remainingAmount = Decimal(form.remainingAmount).add(Decimal(payAmount));
    });
    tabledata.value = list;
    form.totalNumber = caselist.length;
    setTimeout(() => {
      if (ProTableRef.value.element) {
        ProTableRef.value.element.setAllCheckboxRow(true);
        selectdList.value = list;
      }
    }, 500);
  };
  const submitForm = () => {
    const list = JSON.parse(JSON.stringify(selectdList.value));

    list.forEach((item) => {
      delete item.payAmount;
    });
    const params = {
      borrower: currentDetail.value.borrower,
      askForStatus: 'Pending',
      flowStatus: 'pending',
      ...form,
      reduceRecords: list,
    };
    console.log('sadas', params);
    delete params.id;
    delete params.cpe;
    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;
    }
  }
</style>
