<template>
  <el-drawer
    v-model="showModal"
    title="分期申请"
    :size="850"
    direction="rtl"
    :before-close="onHide"
  >
    <div class="h-full flex-col flex mydrawer pb-2">
      <div>
        <ProTable :config="config" :data="tabledata" :showPagination="false" :showToolBar="false">
          <template #table_top>
            <p class="font-bold">关联案件：</p>
          </template>
        </ProTable>
      </div>
      <div class="flex">
        <div class="mt-3 pr-8 w-2/5">
          <el-form
            ref="formRef"
            inline
            :model="form"
            :rules="rules"
            label-width="110px"
            label-position="left"
          >
            <el-row>
              <el-col :span="24">
                <el-form-item class="w-full" label="剩余待还总额：" prop="name">
                  {{ form.remainingAmount }}
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="w-full" label="还款总额：" prop="code">
                  <el-input
                    v-model="form.totalRepayAmount"
                    placeholder="请输入"
                    @change="changePeriod"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="w-full" label="分期申请时间：" prop="code">
                  <el-date-picker
                    v-model="form.applyDate"
                    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="name">
                  <el-select v-model="form.totalPeriod" placeholder="请选择" @change="changePeriod">
                    <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="24">
                <el-form-item class="w-full" label="首期还款日：" prop="code">
                  <el-date-picker
                    @change="changePeriod"
                    class="w-full"
                    v-model="form.firstApplyDate"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    type="date"
                  />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="24">
                <el-form-item class="w-full" label="非首期还款日：" prop="code">
                  <el-date-picker
                    v-model="form.datetime"
                    class="w-full"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    type="date"
                  />
                </el-form-item>
              </el-col> -->
              <el-col :span="24">
                <el-form-item class="w-full" label="分期生效时间：" prop="code">
                  <el-date-picker
                    v-model="form.effectiveTime"
                    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-row>
          </el-form>
        </div>
        <div class="w-3/5">
          <ProTable :config="splitconfig" :data="splitdata" :showPagination="false">
            <template #right_tools>
              <el-button type="primary" @click="editOrConfirm" class="mr-1">{{
                editFirst ? '确定' : '修改'
              }}</el-button>
            </template>
          </ProTable>
          <div class="flex">
            <div class="ml-auto text-gray-400">总计： {{ form.totalRepayAmount }}</div>
          </div>
        </div>
      </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 { ElInputNumber, ElMessage } from 'element-plus';
  import { savebyStages } from '@/api/property';
  const showModal = ref(false);
  const editFirst = ref(false);
  const tabledata = ref([]);
  const splitdata = ref([]);

  const form = reactive({
    remainingAmount: 0,
    totalRepayAmount: 0,
    totalPeriod: 2,
    applyDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    firstApplyDate: dayjs().format('YYYY-MM-DD'),
    effectiveTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  });
  const currentDetail = ref({});
  const onHide = (done) => {
    currentDetail.value = {};
    done();
  };
  const add = (a, b) => {
    return (parseFloat(a) + parseFloat(b)).toFixed(2);
  };

  const minus = (a, b) => {
    return (parseFloat(a) - parseFloat(b)).toFixed(2);
  };

  const multiply = (a, b) => {
    return (parseFloat(a) * parseFloat(b)).toFixed(2);
  };

  const divide = (a, b) => {
    return (parseFloat(a) / parseFloat(b)).toFixed(2);
  };
  const editOrConfirm = () => {
    if (editFirst.value) {
      if (!splitdata.value[0].applyAmount || isNaN(Number(splitdata.value[0].applyAmount)))
        return ElMessage.warning({
          message: '请重新确认数值',
          plain: true,
        });
      const otherNum = form.totalRepayAmount - Number(splitdata.value[0].applyAmount);
      const list = [splitdata.value[0]];
      const crash = divide(Math.round(divide(otherNum, form.totalPeriod - 1) * 100), 100);
      for (let i = 0; i < form.totalPeriod - 1; i++) {
        console.log('i', i);
        const playApplyDate = dayjs(form.firstApplyDate)
          .add(i + 1, 'month')
          .format('YYYY-MM-DD');
        if (i === form.totalPeriod - 2) {
          const other = list.reduce((pre, cur) => {
            return add(pre, cur.applyAmount);
          }, 0);
          list.push({
            period: i + 1,
            playApplyDate: playApplyDate,
            repayStatus: 'pending',
            applyAmount: minus(form.totalRepayAmount, other),
          });
        } else {
          list.push({
            period: i + 1,
            playApplyDate: playApplyDate,
            repayStatus: 'pending',
            applyAmount: crash,
          });
        }
      }
      splitdata.value = list;
    }
    editFirst.value = !editFirst.value;
  };

  const changePeriod = () => {
    const list = [];
    const crash = divide(Math.round(divide(form.totalRepayAmount, form.totalPeriod) * 100), 100);
    for (let i = 0; i < form.totalPeriod; i++) {
      console.log('i', i);
      const playApplyDate = dayjs(form.firstApplyDate)
        .add(i + 1, 'month')
        .format('YYYY-MM-DD');
      if (i === form.totalPeriod - 1) {
        const other = list.reduce((pre, cur) => {
          return add(pre, cur.applyAmount);
        }, 0);
        list.push({
          period: i + 1,
          playApplyDate: playApplyDate,
          repayStatus: 'pending',
          applyAmount: minus(form.totalRepayAmount, other),
        });
      } else {
        list.push({
          period: i + 1,
          playApplyDate: playApplyDate,
          repayStatus: 'pending',
          applyAmount: crash,
        });
      }
    }
    splitdata.value = list;
  };
  const options = [
    {
      value: 2,
      label: '2',
    },
    {
      value: 3,
      label: '3',
    },
    {
      value: 4,
      label: '4',
    },
    {
      value: 5,
      label: '5',
    },
    {
      value: 6,
      label: '6',
    },
  ];
  const repayStatusOpt = [
    {
      value: 'pending',
      label: '待还款',
    },
    {
      value: 'over',
      label: '已还款',
    },
  ];
  const selectdList = ref([]);
  const onCheckboxChange = (row) => {
    selectdList.value = row.records;
  };
  const config = reactive({
    minHeight: 200,
    columns: [
      // { type: 'checkbox', width: 50 },
      {
        field: 'caseId',
        title: '案件ID',
      },
      {
        field: 'product',
        title: '产品',
      },
      {
        field: 'loanPlatform.name',
        title: '借款机构',
      },
      {
        field: 'commissionAmount',
        title: '委案金额',
      },
      {
        field: 'sumReductionAmount',
        title: '累计减免金额',
      },
      {
        field: 'sumRepayAmount',
        title: '累计还款金额',
      },
      {
        field: 'remainingAmount',
        title: '剩余待还金额',
      },
    ],
    onCheckboxChange: onCheckboxChange,
    toolbarConfig: { enabled: false },
  });
  const splitconfig = computed(() => {
    return {
      minHeight: 200,
      columns: [
        { field: 'period', width: 50, title: '期次' },
        {
          field: 'playApplyDate',
          title: '到期日',
        },
        {
          field: 'repayStatus',
          title: '状态',
          width: 70,
          slots: {
            default: ({ row, rowIndex }) => {
              return (
                <>
                  {row.repayStatus
                    ? repayStatusOpt.find((v) => v.value === row.repayStatus).label
                    : ''}
                </>
              );
            },
          },
        },
        {
          field: 'applyAmount',
          title: '金额',
          slots: {
            default: ({ row, rowIndex }) => {
              if (editFirst.value && rowIndex === 0) {
                return (
                  <>
                    <ElInputNumber v-model={row.applyAmount} />
                  </>
                );
              } else {
                return <>{row.applyAmount}</>;
              }
            },
          },
        },
      ],
      onCheckboxChange: onCheckboxChange,
    };
  });
  const openModal = (detail, caselist) => {
    showModal.value = true;
    editFirst.value = false;
    currentDetail.value = detail;
    console.log('currentDetail', currentDetail.value, caselist);
    form.totalRepayAmount = 0;
    form.remainingAmount = 0;
    caselist.forEach((item) => {
      form.totalRepayAmount += Number(item.remainingAmount) || 0;
      form.remainingAmount += Number(item.remainingAmount) || 0;
    });
    tabledata.value = caselist;
    changePeriod();
  };
  const emits = defineEmits(['success']);
  const submitForm = () => {
    if (editFirst.value)
      return ElMessage.warning({
        message: '修改分期数值后要确认',
        plain: true,
      });
    const params = {
      ...currentDetail.value,
      ...form,
      byStagesRecords: splitdata.value,
      loans: tabledata.value,
      flowStatus: 'pending',
      id: null,
    };
    savebyStages(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;
    }
    :deep(.el-date-editor) {
      width: 100%;
    }
  }
</style>
