<template>
  <div class="table-box">
    <div class="card flex mb-2" style="padding-top: 0">
      <div style="width: 29%">
        <div class="mb-1 text-center step">
          <div class="xuhao">1</div>
          上传文件
          <div class="jt"
            ><el-icon size="60" color="#e3e3e3d9"><ArrowRight /></el-icon
          ></div>
        </div>
        <div class="w-full flex items-center justify-center pt-5">
          <div>
            <el-upload
              class="avatar-uploader"
              :headers="{ timeout: 600000 }"
              ref="uploadRef"
              :action="upload.url"
              :disabled="upload.isUploading"
              accept=".xls, .xlsx"
              :limit="1"
              :on-success="handleFileSuccess"
              :on-remove="handleRemove"
              :auto-upload="true"
              :on-progress="uploadVideoProcess"
            >
              <el-button type="primary" plain :icon="Upload" :loading="upload.isUploading"
                >上传文件</el-button
              >
            </el-upload>
            <!-- 进度条 -->
            <!-- <el-progress v-if="progressFlag" :percentage="loadProgress" /> -->
            <div class="mt-2 text-xs text-gray-400"> 仅支持1个文件上传，格式为xls和xlsx </div>
            <div class="mt-1 text-blue-500 underline cursor-pointer" @click="downloadtemplate"
              >下载模板</div
            >
          </div>
        </div>
      </div>
      <div style="width: 29%">
        <div class="mb-1 text-center step">
          <div class="xuhao">2</div>
          检查数据
          <div class="jt"
            ><el-icon size="60" color="#e3e3e3d9"><ArrowRight /></el-icon
          ></div>
        </div>
        <div class="w-full flex items-center justify-center pt-5">
          <div>
            <div class="flex items-center">
              <el-button
                type="danger"
                @click="checkData"
                :disabled="!form.path"
                :loading="checkObj.checkloading"
                >检查</el-button
              >
            </div>
            <div class="text-sm mt-2">
              <span class="mr-2 text-gray-400">通过{{ checkObj?.result?.success || 0 }}条</span>
              <span class="text-gray-400">失败{{ checkObj?.result?.error || 0 }}条</span>
            </div>
            <!-- 进度条 -->
            <!-- <el-progress v-if="progressFlag" :percentage="loadProgress" /> -->
            <div
              class="mt-2 text-xs text-blue-500 underline cursor-pointer"
              v-if="checkObj.check"
              @click="openError"
              >下载检查结果</div
            >
            <div v-else class="mt-2 text-xs text-red-500"> *检查文件后才可以提交 </div>
          </div>
        </div>
      </div>
      <div class="flex-1 importwrapper">
        <div class="mb-1 text-center step">
          <div class="xuhao">3</div>
          上传数据
        </div>
        <div class="w-full flex items-center justify-center pt-5">
          <div>
            <el-form ref="formRef" inline :model="form" :rules="rules" label-width="120px">
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-form-item class="w-full" label="导入批次：" prop="code">
                    <el-input v-model="form.code" placeholder="请输入" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="13">
                  <el-form-item class="w-full" label="分期是否可修改：" prop="canStages">
                    <el-radio-group v-model="form.canStages">
                      <el-radio value="Y">是</el-radio>
                      <el-radio value="N">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item class="w-full" label="是否共案处理：" prop="mergerCase">
                    <el-radio-group v-model="form.mergerCase">
                      <el-radio value="Y">是</el-radio>
                      <el-radio value="N">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>

                <el-col :span="13">
                  <el-form-item class="w-full" label="最低分期金额：" prop="minAmount">
                    <el-input
                      v-model="form.minAmount"
                      type="number"
                      placeholder="请输入"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="9">
                  <el-form-item class="w-full" label="完成率：" prop="completionRate" label-width="65px">
                    <el-input v-model="form.completionRate" style="width: 100%" type="number">
                      <template #append>‱</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item class="w-full" label="折扣：" prop="discount" label-width="55px">
                    <el-input v-model="form.discount" placeholder="请输入" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item class="w-full" label="分期最大期数：" prop="maxStagesNum"  label-width="105px">
                    <el-input
                      v-model.number="form.maxStagesNum"
                      placeholder="请输入"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div class="flex justify-end">
              <el-button
                type="primary"
                @click="submitData"
                :loading="checkObj.submitloading"
                :disabled="!form.path || !checkObj.checksuccess"
                >上传</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>
    <div>
      <ProTable
        :config="config"
        :api="importLoanPage"
        ref="ProTableRef"
        :paramCallback="paramCallback"
      >
        <!-- 表格 header 按钮 -->
        <!-- <template #left_buttons>
          <el-button type="primary">新增菜单 </el-button>
        </template> -->
      </ProTable>
    </div>
    <caseDetailModal ref="caseDetailModalRef" />
    <errorModal ref="errorModalRef" />
  </div>
</template>

<script setup lang="jsx" name="import">
  import { getAppEnvConfig } from '@/utils/env';

  import caseDetailModal from './components/caseDetailModal.vue';
  import errorModal from './components/errorModal.vue';
  import { reactive, ref } from 'vue';
  import { computed, onMounted } from 'vue';
  import { ElButton, ElMessage, ElTag } from 'element-plus';
  import { Upload, ArrowRight } from '@element-plus/icons-vue';
  import { inject } from 'vue';
  import { LoanSubmit, importLoanPage, checkLoanExcel } from '@/api/import';
  const checkDiscount = (rule, value, callback) => {
    if (isNaN(Number(value))) {
      callback(new Error('请输入数字值'));
    } else {
      if (Number(value) && (Number(value) > 10 || Number(value) < 0)) {
        callback(new Error('折扣应该0到10'));
      } else {
        callback();
      }
    }
  };
  const checkmaxStagesNum = (rule, value, callback) => {
    if (isNaN(Number(value)) || Number(value) % 1 !== 0) {
      callback(new Error('请输入整数值'));
    } else {
      callback();
    }
  };
  const rules = ref({
    discount: [{ validator: checkDiscount, trigger: 'blur' }],
    // minAmount: [
    //   { validator: checkminAmount, trigger: 'blur' },
    // ],
    maxStagesNum: [{ validator: checkmaxStagesNum, trigger: 'blur' }],
  });
  const downloadfile = inject('download');
  const formRef = ref();
  const envs = getAppEnvConfig();
  const ProTableRef = ref();
  const progressFlag = ref(false);
  const proTable = ref(undefined);
  const options = ref([]);
  const loadProgress = ref(0);
  const caseDetailModalRef = ref();
  const errorModalRef = ref();
  const uploadRef = ref();
  const isFold = ref(true);
  const checkObj = reactive({
    submitloading: false,
    checkloading: false,
    check: false,
    checksuccess: false,
    result: {
      success: null,
      error: null,
      loanErrors: [],
    },
  });
  const paramCallback = (param) => {
    const obj = JSON.parse(JSON.stringify(param));
    if (obj['createTime']) {
      if (obj['createTime'][0]) obj['createTimeBegin'] = obj['createTime'][0];
      if (obj['createTime'][1]) obj['createTimeEnd'] = obj['createTime'][1];
      delete obj['createTime'];
    }
    return obj;
  };
  const openError = () => {
    errorModalRef.value.openModal(JSON.parse(JSON.stringify(checkObj.result.loanErrors)));
  };
  const config = reactive({
    columns: [
      {
        field: 'code',
        title: '导入批次',
        width: 100,
        showOverflow: 'tooltip',
        search: { el: 'input', props: { clearable: true } },
      },
      {
        field: 'maxStagesNum',
        title: '分期最大期数',
        width: 120,
        showOverflow: 'tooltip',
        search: { el: 'input', props: { clearable: true } },
      },
      {
        field: 'minAmount',
        title: '最低分期金额',
        width: 120,
        showOverflow: 'tooltip',
        search: { el: 'input', props: { clearable: true } },
      },
      {
        field: 'completionRate',
        title: '完成率',
        width: 120,
        showOverflow: 'tooltip'
      },
      {
        field: 'mergerCase',
        title: '是否共案处理',
        showOverflow: 'tooltip',
        width: 110,
        slots: {
          default: ({ row }) => {
            return <ElTag>{row.mergerCase == 'Y' ? '是' : '否'}</ElTag>;
          },
        },
      },
      {
        field: 'canStages',
        title: '分期是否可修改',
        showOverflow: 'tooltip',
        width: 110,
        slots: {
          default: ({ row }) => {
            return <ElTag>{row.canStages == 'Y' ? '是' : '否'}</ElTag>;
          },
        },
      },
      {
        field: 'totalCaseNum',
        showOverflow: 'tooltip',
        width: 100,
        title: '案件总数',
      },
      {
        field: 'totalAmount',
        showOverflow: 'tooltip',
        width: 120,
        title: '案件总金额',
      },
      {
        field: 'totalBorrowerNum',
        showOverflow: 'tooltip',
        width: 100,
        title: '客户总数',
      },
      {
        field: 'discount',
        title: '折扣',
        showOverflow: 'tooltip',
        width: 80,
      },
      {
        field: 'totalPengNum',
        title: '撞库次数',
        showOverflow: 'tooltip',
        width: 100,
        slots: {
          default: ({ row }) => {
            return (
              <>
                <ElButton link type="primary" onClick={() => linkZK(row)}>
                  {row.totalPengNum}
                </ElButton>
              </>
            );
          },
        },
      },
      {
        field: 'action',
        title: '文件地址',
        showOverflow: 'tooltip',
        width: 80,
        slots: {
          default: ({ row }) => {
            return (
              <>
                <ElButton link type="primary" onClick={() => downfile(row)}>
                  下载
                </ElButton>
              </>
            );
          },
        },
      },
      {
        field: 'createTime',
        width: 140,
        showOverflow: 'tooltip',
        title: '创建日期',
        search: {
          el: 'date-picker',
          props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
        },
      },
    ],
  });
  const form = reactive({
    path: '',
    code: '',
    maxStagesNum: '',
    completionRate: '',
    canStages: 'Y',
    minAmount: '',
    mergerCase: 'Y',
    discount: '',
  });
  const upload = reactive({
    // 是否禁用上传
    isUploading: false,
    // 上传的地址
    url: envs.VITE_GLOB_API_URL_PREFIX + '/sys/upload',
  });
  console.log('upload', upload);
  const uploadVideoProcess = (event, file, fileList) => {
    upload.isUploading = true;
  };
  const downloadtemplate = () => {
    downloadfile('/LoanExcel/downloadTemplate', {}, '模版.xls');
  };
  const checkData = () => {
    checkObj.checkloading = true;
    checkLoanExcel({
      fileUrl: form.path,
    })
      .then((res) => {
        if (res.success) {
          checkObj.result.success = res.result.success;
          checkObj.result.error = res.result.error;
          if (checkObj.result.error === 0) {
            checkObj.checksuccess = true;
          }
          checkObj.result.loanErrors = res.result.loanErrors;
          checkObj.check = true;
        }
        checkObj.checkloading = false;
      })
      .catch((e) => {
        checkObj.checkloading = false;
      });
  };

  const handleFileSuccess = (response, file, fileList) => {
    if (!response.success) {
      ElMessage.error({
        message: response.message || '检查失败',
        plain: true,
      });
      upload.isUploading = false;
      uploadRef.value.clearFiles();
    }
    if (response.success) {
      ElMessage.success({
        message: '上传成功',
        plain: true,
      });
      form.path = response.message;
      upload.isUploading = false;
    }
  };
  const handleRemove = () => {
    form.path = '';
    checkObj.check = false;
    checkObj.checksuccess = false;
  };
  const linkZK = (row) => {
    caseDetailModalRef.value.openModal(JSON.parse(JSON.stringify(row)));
  };
  const downfile = (row) => {
    const name = row.file.slice(row.file.lastIndexOf('/') + 1, row.file.length);
    downloadfile('/sys/static/' + row.file, {}, name);
  };
  const query = () => ProTableRef.value?.search();
  const submitData = async () => {
    try {
      if (!form.maxStagesNum)
        return ElMessage.warning({
          message: '分期最大期数必填',
          plain: true,
        });
      checkObj.submitloading = true;
      // if (!form.minAmount) return ElMessage.warning({
      //   message: '最低分期金额必填',
      //   plain: true,
      // });
      await formRef.value.validate();
      await LoanSubmit({
        file: form.path,
        code: form.code,
        maxStagesNum: form.maxStagesNum,
        completionRate: form.completionRate,
        canStages: form.canStages,
        minAmount: form.minAmount,
        mergerCase: form.mergerCase,
        discount: form.discount,
      }).then((res) => {
        ElMessage.success({
          message: '提交成功',
          plain: true,
        });
        uploadRef.value.clearFiles();
        form.path = '';
        query();
        form['path'] = '';
        form['code'] = '';
        form['maxStagesNum'] = '';
        form['completionRate'] = '';
        form['minAmount'] = '';
        form['mergerCase'] = 'Y';
        form['canStages'] = 'Y';
        form['discount'] = '';
        checkObj.submitloading = false;
      });
    } catch {
      checkObj.submitloading = false;
    }
  };
  onMounted(() => {
    formRef.value.clearValidate();
    query();
  });
</script>
<style lang="scss" scoped>
  .importwrapper {
    :deep(.el-form-item) {
      margin-bottom: 4px !important;
    }
  }
  .xuhao {
    background-image: url('./step.svg');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    -moz-background-size: 100% 100%;
    width: 30px;
    line-height: 30px;
    margin-right: 5px;
    height: 30px;
  }
  .step {
    border-bottom: 1px solid #e3e3e3;
    height: 45px;
    display: flex;
    position: relative;
    width: 100%;
    align-items: center;
    justify-content: center;
    line-height: 45px;
  }
  .jt {
    position: absolute;
    top: -7px;
    right: 0;
  }
</style>
