<template>
  <div class="table-box">
    <div class="card flex mb-2">
      <div class="flex-1 pr-3">
        <div class="mb-1">1、上传文件</div>
        <div>
          <el-upload
            class="avatar-uploader"
            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">上传文件</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 class="flex-1">
        <div class="mb-1">2、检查数据</div>
        <div>
          <div class="flex items-center">
            <el-button type="danger" @click="checkData" :disabled="!form.path">检查</el-button>
            <span class="ml-2" v-if="checkObj.check">
              <span class="mr-2 text-gray-400">通过{{ checkObj.result.success }}条</span>
              <span class="text-gray-400">失败{{ checkObj.result.error }}条</span>
            </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>
      </div>
      <div class="flex-1 importwrapper">
        <div class="mb-1 text-center">3、上传数据</div>
        <div class="pr-4">
          <el-form ref="formRef" inline :model="form" :rules="rules" label-width="85px">
            <el-form-item class="w-full" label="导入编号：" prop="code">
              <el-input v-model="form.code" placeholder="请输入" style="width: 100%" />
            </el-form-item>
            <el-form-item class="w-full" label="委案合同：" prop="contractNo">
              <el-input v-model="form.contractNo" placeholder="请输入" style="width: 100%" />
            </el-form-item>
            <el-form-item class="w-full" label="折扣：" prop="discount">
              <el-input v-model="form.discount" placeholder="请输入" style="width: 100%" />
            </el-form-item>
          </el-form>
          <el-button
            type="primary"
            @click="submitData"
            :disabled="!form.path || !checkObj.checksuccess"
            >上传</el-button
          >
        </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 } from 'element-plus';
  import { Upload } from '@element-plus/icons-vue';
  import { inject } from 'vue';
  import { LoanSubmit, importLoanPage, checkLoanExcel } from '@/api/import';

  const downloadfile = inject('download');
  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({
    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: '导入编号',
        search: { el: 'input', props: { clearable: true } },
      },
      {
        field: 'contractNo',
        title: '委案合同',
        search: { el: 'input', props: { clearable: true } },
      },
      {
        field: 'code',
        title: '资产类型',
        enum: options,
        search: { el: 'select', props: { filterable: true } },
        fieldNames: { label: 'genderLabel', value: 'genderValue' },
      },
      {
        field: 'totalCaseNum',
        title: '案件总数',
      },
      {
        field: 'totalAmount',
        title: '案件总金额',
      },
      {
        field: 'totalBorrowerNum',
        title: '客户总数',
      },
      {
        field: 'discount',
        title: '折扣',
        width: 80,
      },
      {
        field: 'totalPengNum',
        title: '撞库次数',
        width: 100,
        slots: {
          default: ({ row }) => {
            return (
              <>
                <ElButton link type="primary" onClick={() => linkZK(row)}>
                  {row.totalPengNum}
                </ElButton>
              </>
            );
          },
        },
      },
      {
        field: 'action',
        title: '文件地址',
        width: 200,
        slots: {
          default: ({ row }) => {
            return (
              <>
                <ElButton link type="primary" onClick={() => downfile(row)}>
                  下载
                </ElButton>
              </>
            );
          },
        },
      },
      {
        field: 'createTime',
        title: '创建日期',
        search: {
          el: 'date-picker',
          props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
        },
      },
    ],
  });
  const form = reactive({
    path: '',
    code: '',
    contractNo: '',
    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 = () => {
    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;
      }
    });
  };

  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(envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + row.file, {}, name);
  };
  const query = () => ProTableRef.value?.search();
  const submitData = () => {
    LoanSubmit({
      file: form.path,
      code: form.code,
      contractNo: form.contractNo,
      discount: form.discount,
    }).then((res) => {
      ElMessage.success({
        message: '提交成功',
        plain: true,
      });
      uploadRef.value.clearFiles();
      form.path = '';
      query();
      form['path'] = '';
      form['code'] = '';
      form['contractNo'] = '';
      form['discount'] = '';
    });
  };
  onMounted(() => {
    query();
  });
</script>
<style lang="scss" scoped>
  .importwrapper {
    :deep(.el-form-item) {
      margin-bottom: 3px !important;
    }
  }
</style>
