<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">
                  {{ minAmount }}
                </el-form-item>
              </el-col>
              <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.applyTime"
                    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-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>
        <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"
                  v-if="currentDetail.canStages === 'Y'"
                  >{{ 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-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 { ElInputNumber, ElMessage, ElTag } from 'element-plus';
  import { savebyStages } from '@/api/property';
  import { getByIdPlatforms } from '@/api/platform';
  import { getAppEnvConfig } from '@/utils/env';
  import { Download, ZoomIn, Delete } from '@element-plus/icons-vue';
  import Decimal from 'decimal.js';
  import { useDict } from '@/hooks/useDict';
  import { useAuthStore } from '@/stores/modules/auth';
  import { inject } from 'vue';
  import { useUserStore } from '@/stores/modules/user';
  const userStore = useUserStore();
  const { PhoneResultStatus, RepayStatus, FlowStatus, FollowStatus, AuditStatus, CaseStatus } =
    useDict(
      'PhoneResultStatus',
      'RepayStatus',
      'FlowStatus',
      'FollowStatus',
      'AuditStatus',
      'CaseStatus'
    );
  const envs = getAppEnvConfig();
  const { authButtonListGet } = useAuthStore(); // 获取用户权限列表

  const url = envs.VITE_GLOB_API_URL_PREFIX + '/sys/upload';
  const ProTableRef = ref();
  const mypictureRef = ref();
  const showModal = ref(false);
  const editFirst = ref(false);
  const tabledata = ref([]);
  const splitdata = ref([]);
  const dialogImageUrl = ref('');
  const dialogVisible = ref(false);
  const downloadfile = inject('download');
  const form = reactive({
    remainingAmount: 0,
    images: [],
    totalRepayAmount: 0,
    totalPeriod: 2,
    applyTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    firstApplyDate: dayjs().format('YYYY-MM-DD'),
  });
  const props = defineProps({
    mergerCase: String,
  });
  const minAmount = ref(0);
  const currentDetail = ref({});
  const onHide = (done) => {
    done();
  };
  const download = (item) => {
    const name = item.slice(item.lastIndexOf('/') + 1, item.length);
    downloadfile('/sys/static/' + item, {}, name);
  };
  const getImageUrl = () => {
    return new URL(`@/assets/images/file.svg`, import.meta.url).href;
  };
  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 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 = 1; i < form.totalPeriod; i++) {
        const playApplyDate = dayjs(form.firstApplyDate)
          .add(i, '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;
    }
    editFirst.value = !editFirst.value;
  };
  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 handleRemove1 = (uploadFile, uploadFiles) => {
    console.log('uploadFile', uploadFile);
    const index = form.images.findIndex((v) => v.name === uploadFile.name);
    form.images.splice(index, 1);
  };
  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, '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([]);
  const getPlatforms = (id) => {
    const maxStagesNum = Number(currentDetail.value.maxStagesNum) || 6;
    for (let i = 2; i <= maxStagesNum; i++) {
      options.value.push({
        value: i,
        label: i + '',
      });
    }
    minAmount.value = Number(currentDetail.value.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 row.repayStatus !== 'over';
      },
    },
    minHeight: 200,
    columns: [
      { type: 'checkbox', width: 60, fixed: 'left' },
      {
        field: 'caseId',
        title: '案件ID',
        width: 230,
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <div className="inline-block">{row.caseId}</div>
                <Tag row={row} />
              </>
            );
          },
        },
        showOverflow: 'tooltip',
      },
      {
        field: 'mergerCase',
        title: '是否共案处理',
        visible: authButtonListGet.includes('show_merger_case'),
        showOverflow: 'tooltip',
        width: 100,
        slots: {
          default: ({ row }) => {
            return <ElTag>{row.mergerCase == 'Y' ? '是' : '否'}</ElTag>;
          },
        },
      },
      {
        field: 'canStages',
        title: '分期是否可修改',
        showOverflow: 'tooltip',
        visible: authButtonListGet.includes('show_can_stages'),
        width: 100,
        slots: {
          default: ({ row }) => {
            return <ElTag>{row.canStages == 'Y' ? '是' : '否'}</ElTag>;
          },
        },
      },
      {
        field: 'loanPlatform.name',
        title: '借款平台',
        width: 120,
        showOverflow: 'tooltip',
      },
      {
        field: 'commissionAmount',
        title: '委案金额',
        width: 120,
        showOverflow: 'tooltip',
      },
      {
        field: 'sumReductionAmount',
        title: '累计减免金额',
        width: 120,
        showOverflow: 'tooltip',
      },
      {
        field: 'sumRepayAmount',
        title: '累计还款金额',
        width: 120,
        showOverflow: 'tooltip',
      },
      {
        field: 'remainingAmount',
        title: '剩余待还金额',
        width: 120,
        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 handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url;
    dialogVisible.value = true;
  };
  const openModal = (detail, caselist) => {
    showModal.value = true;
    editFirst.value = false;
    currentDetail.value = detail;
    form.totalRepayAmount = 0;
    form.images = [];
    mypictureRef.value?.clearFiles();
    form.remainingAmount = 0;
    const a = caselist.filter((v) => v.repayStatus !== 'over');
    caselist.forEach((item) => {
      if (item.repayStatus !== 'over') {
        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.setCheckboxRow(a, true);
        selectdList.value = a;
        // 获取最大分期数
        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,
      });
    if (Number(form.totalRepayAmount || 0) < minAmount.value)
      return ElMessage.warning({
        message: '分期金额要大于本批次的分期最低金额',
        plain: true,
      });
    if (!selectdList.value || selectdList.value.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 = {
      ...currentDetail.value,
      ...form,
      applyUser: {
        username: userStore.userInfo?.username,
        id: userStore.userInfo?.id,
      },
      images: images.length > 0 ? images : null,
      byStagesRecords: splitdata.value,
      loans: selectdList.value,
      flowStatus: 'pending',
      id: null,
    };
    delete params.tenantTime
    console.log(params);
    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%;
    }
  }
  .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>
