<template>
  <el-drawer
    v-model="showModal"
    title="分期申请"
    :size="850"
    direction="rtl"
    @close="showModal = false"
    :before-close="onHide"
  >
    <div class="h-full flex-col flex mydrawer pb-2">
      <div>
        <ProTable
          :config="config"
          ref="ProTableRef"
          :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"
                      :disabled="item.disabled"
                    />
                  </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"
            :showToolBar="false"
          >
            <template #table_top>
              <div class="flex justify-end">
                <el-button type="primary" @click="editOrConfirm" class="mr-1 my-2">{{
                  editFirst ? '确定' : '修改'
                }}</el-button>
              </div>
            </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';
  import { getByIdPlatforms } from '@/api/platform';
  import Decimal from 'decimal.js';
  import { useDict } from '@/hooks/useDict';
  const { PhoneResultStatus, RepayStatus, FlowStatus, FollowStatus, AuditStatus, CaseStatus } = useDict("PhoneResultStatus","RepayStatus", "FlowStatus", "FollowStatus","AuditStatus", "CaseStatus");
  
  const ProTableRef = ref();
  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 props = defineProps({
    mergerCase: String,
  });
  const minAmount = ref(0);
  const currentDetail = ref({});
  const onHide = (done) => {
    done();
  };

  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 = Decimal(
        Decimal(otherNum).div(Decimal(form.totalPeriod - 1))
      ).toSignificantDigits(2);
      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 Decimal(pre).add(Decimal(cur.applyAmount));
          }, 0);
          list.push({
            period: i + 1,
            playApplyDate: playApplyDate,
            repayStatus: 'pending',
            applyAmount: Decimal(form.totalRepayAmount).sub(Decimal(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 = Decimal(
      Decimal(form.totalRepayAmount).div(Decimal(form.totalPeriod))
    ).toSignificantDigits(2);
    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 Decimal(pre).add(Decimal(cur.applyAmount));
        }, 0);
        list.push({
          period: i + 1,
          playApplyDate: playApplyDate,
          repayStatus: 'pending',
          applyAmount: Decimal(form.totalRepayAmount).sub(Decimal(other)),
        });
      } else {
        list.push({
          period: i + 1,
          playApplyDate: playApplyDate,
          repayStatus: 'pending',
          applyAmount: crash,
        });
      }
    }
    splitdata.value = list;
  };
  const options = ref([
    {
      value: 2,
      label: '2',
    },
    {
      value: 3,
      label: '3',
    },
    {
      value: 4,
      label: '4',
    },
    {
      value: 5,
      label: '5',
    },
    {
      value: 6,
      label: '6',
    },
  ]);
  const getPlatforms = (id) => {
    options.value = [
      {
        value: 2,
        label: '2',
      },
      {
        value: 3,
        label: '3',
      },
      {
        value: 4,
        label: '4',
      },
      {
        value: 5,
        label: '5',
      },
      {
        value: 6,
        label: '6',
      },
    ];
    getByIdPlatforms(id).then((res) => {
      console.log('resres', res);
      if (res.success) {
        if (res.result.maxStagesNum) {
          const list = options.value.filter((v) => v.value > res.result.maxStagesNum);
          list.forEach((e) => {
            e['disabled'] = true;
          });
        }
        if (res.result.minAmount) {
          minAmount.value = res.result.minAmount;
        }
      }
      //
    });
  };

  const selectdList = ref([]);
  const onCheckboxChange = (row) => {
    selectdList.value = row.records;
    form.totalRepayAmount = 0;
    form.remainingAmount = 0;
    selectdList.value.forEach((item) => {
      const remainingAmount = Decimal(Number(item.remainingAmount) || 0).sub(
        Decimal(Number(item.sumReductionAmount) || 0)
      );

      form.totalRepayAmount = Decimal(form.totalRepayAmount).add(Decimal(remainingAmount));
      form.remainingAmount = Decimal(form.remainingAmount).add(Decimal(remainingAmount));
    });
    if (selectdList.value.length > 0) {
      getPlatforms(selectdList.value[0].loanPlatform.id);
    }
    changePeriod();
  };
  const onCheckboxAll = (flag) => {
    if (flag.checked) {
      selectdList.value = flag.records;
    } else {
      selectdList.value = [];
    }
    form.totalRepayAmount = 0;
    form.remainingAmount = 0;
    selectdList.value.forEach((item) => {
      const remainingAmount = Decimal(Number(item.remainingAmount) || 0).sub(
        Decimal(Number(item.sumReductionAmount) || 0)
      );
      form.totalRepayAmount = Decimal(form.totalRepayAmount).add(Decimal(remainingAmount));
      form.remainingAmount = Decimal(form.remainingAmount).add(Decimal(remainingAmount));
    });
    if (selectdList.value.length > 0) {
      getPlatforms(selectdList.value[0].loanPlatform.id);
    }
    changePeriod();
  };
  const config = reactive({
    checkboxConfig: {
      checkMethod: ({ row }) => {
        return props.mergerCase !== 'Y';
      },
    },
    minHeight: 200,
    columns: [
      { type: 'checkbox', width: 50 },
      {
        field: 'caseId',
        title: '案件ID',
        showOverflow: 'tooltip',
      },
      {
        field: 'product',
        title: '产品',
        showOverflow: 'tooltip',
      },
      {
        field: 'loanPlatform.name',
        title: '借款机构',
        showOverflow: 'tooltip',
      },
      {
        field: 'commissionAmount',
        title: '委案金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'sumReductionAmount',
        title: '累计减免金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'sumRepayAmount',
        title: '累计还款金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'remainingAmount',
        title: '剩余待还金额',
        showOverflow: 'tooltip',
      },
    ],
    onCheckboxChange: onCheckboxChange,
    onCheckboxAll: onCheckboxAll,
    toolbarConfig: { enabled: false },
  });
  const splitconfig = computed(() => {
    return {
      minHeight: 200,
      toolbarConfig: { enabled: false },
      columns: [
        { field: 'period', width: 50, title: '期次' },
        {
          field: 'playApplyDate',
          showOverflow: 'tooltip',
          title: '到期日',
        },
        {
          field: 'repayStatus',
          showOverflow: 'tooltip',
          title: '状态',
          width: 70,
          slots: {
            default: ({ row, rowIndex }) => {
              return (
                <>
                  {row.repayStatus
                    ? RepayStatus.value?.find((v) => v.value === row.repayStatus)?.label
                    : ''}
                </>
              );
            },
          },
        },
        {
          field: 'applyAmount',
          showOverflow: 'tooltip',
          title: '金额',
          slots: {
            default: ({ row, rowIndex }) => {
              if (editFirst.value && rowIndex === 0) {
                return (
                  <>
                    <ElInputNumber v-model={row.applyAmount} />
                  </>
                );
              } else {
                return <>{row.applyAmount}</>;
              }
            },
          },
        },
      ],
    };
  });
  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) => {
      const remainingAmount = Decimal(Number(item.remainingAmount) || 0).sub(
        Decimal(Number(item.sumReductionAmount) || 0)
      );
      form.totalRepayAmount = Decimal(form.totalRepayAmount).add(Decimal(remainingAmount));
      form.remainingAmount = Decimal(form.remainingAmount).add(Decimal(remainingAmount));
    });
    tabledata.value = caselist;
    setTimeout(() => {
      if (ProTableRef.value.element) {
        ProTableRef.value.element.setAllCheckboxRow(true);
        selectdList.value = caselist;
        // 获取最大分期数
        if (selectdList.value.length > 0) {
          getPlatforms(selectdList.value[0].loanPlatform.id);
        }
      }
    }, 500);
    changePeriod();
  };
  const emits = defineEmits(['success']);
  const submitForm = () => {
    if (editFirst.value)
      return ElMessage.warning({
        message: '修改分期数值后要确认',
        plain: true,
      });
    const arr = splitdata.value.filter((v) => v.applyAmount < minAmount.value);
    if (arr.length > 0)
      return ElMessage.warning({
        message: '分期金额要大于借款平台的分期最低金额',
        plain: true,
      });
    const params = {
      ...currentDetail.value,
      ...form,
      byStagesRecords: splitdata.value,
      loans: selectdList.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>
