<template>
  <el-drawer
    v-model="showModal"
    title="减免申请"
    :size="800"
    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.totalPayAmount }}</p>
                <p class="text-red-600 leading-3">*应还金额</p>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div>
        <ProTable :config="config" :data="tabledata" :showPagination="false" :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';
  const emits = defineEmits(['success']);
  const showModal = ref(false);
  const tabledata = ref([]);
  const form = reactive({
    totalReduceAmount: 0,
    totalNumber: '',
    reduceType: 'settle',
    totalPayAmount: 0,
    applyDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  });
  const selectdList = ref([]);
  const onCheckboxChange = (row) => {
    selectdList.value = row.records;
    form.totalNumber = row.records.length;
  };
  const currentDetail = ref({});
  const onHide = (done) => {
    currentDetail.value = {};
    done();
  };
  const options = [
    {
      value: 'settle',
      label: '结清减免',
    },
    {
      value: 'by_stages',
      label: '分期减免',
    },
  ];
  const config = reactive({
    minHeight: 200,
    columns: [
      // { type: 'checkbox', title: '', width: '40px' },
      {
        field: 'loan.caseId',
        title: '案件ID',
      },
      {
        field: 'loan.product',
        title: '产品',
      },
      {
        field: 'loan.payOrg',
        title: '借款机构',
      },
      {
        field: 'loan.commissionAmount',
        title: '委案金额',
      },
      {
        field: 'loan.sumReductionAmount',
        title: '累计减免金额',
      },
      {
        field: 'loan.sumRepayAmount',
        title: '累计还款金额',
      },
      {
        field: 'reduceAmount',
        title: '减免金额',
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <ElInput v-model={row.reduceAmount} onChange={() => changeNum(row, rowIndex)} />
              </>
            );
          },
        },
      },
      {
        field: 'loan.remainingAmount',
        title: '剩余待还金额（减免前）',
      },
      {
        field: 'payAmount',
        title: '应还金额（减免后）',
      },
    ],
    onCheckboxChange: onCheckboxChange,
    toolbarConfig: { enabled: false },
  });
  const changeNum = (row) => {
    row.payAmount = row.loan.remainingAmount - row.reduceAmount;
    form.totalReduceAmount = 0;
    form.totalPayAmount = 0;
    tabledata.value.forEach((item) => {
      form.totalReduceAmount += Number(item.reduceAmount) || 0;
      form.totalPayAmount += Number(item.payAmount) || 0;
    });
  };
  const openModal = (detail, caselist) => {
    showModal.value = true;
    currentDetail.value = detail;
    console.log('currentDetail', currentDetail.value, caselist);
    form.totalReduceAmount = 0;
    form.totalPayAmount = 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 += Number(item.reduceAmount) || 0;
      form.totalPayAmount += payAmount;
    });
    tabledata.value = list;
    form.totalNumber = caselist.length;
  };
  const submitForm = () => {
    const list = JSON.parse(JSON.stringify(tabledata.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>
