<template>
  <div>
    <el-dialog
      title="导入"
      :visible.sync="visibleDialog"
      width="640px"
      @close="close"
    >
      <el-upload
        drag
        v-bind="$attrs"
        :show-file-list="false"
        :accept="fileConfig?.accept||'.xls,.xlsx'"
        :auto-upload="false"
        :on-change="uploadChange"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div
          slot="tip"
          class="el-upload__tip"
        >
          <div>请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除
            <el-button
              type="text"
              :size="$buttonSize"
              @click="downloadTemplate"
            >下载模板</el-button></div>
          <div style="margin-bottom:16px">文件后缀名必须为xls 或xlsx（即Excel格式），文件大小不得大于1GB</div>
          <div class="file-list">
            <div
              v-for="(v,i) in fileList"
              :key="i"
              class="file-li"
            >
              <div>
                {{ v.name }}
                <el-button
                  v-if="v.data.notImportableNum>0"
                  type="text"
                  :size="$buttonSize"
                  @click="viewReason(v)"
                >查看原因</el-button>
              </div>
              <div class="right-status">
                <i
                  :class="v.data.notImportableNum>0?'el-icon-error':'el-icon-success'"
                  :style="v.data.notImportableNum>0?'color:red':'color:green'"
                />
              </div>
              <div class="right-btn">
                <i
                  class="el-icon-delete-solid"
                  @click="deleteFileItem(v,i)"
                />
              </div>
              <!-- <el-progress
                v-if="v.process!=100"
                :percentage="v.process"
              /> -->
            </div>
          </div>

        </div></el-upload>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          :size="$buttonSize"
          @click="close"
        >{{
          $t("button.cancel")
        }}</el-button>
        <el-button
          type="primary"
          :size="$buttonSize"
          @click="submit"
        >{{
          $t("button.confirm")
        }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="查看原因"
      :visible.sync="failDialog"
      width="640px"
      @close="failClose"
    >
      <div class="import-false">
        <div class="false-box">
          <span class="fail-text">导入失败明细</span>
          <span class="fail-num">总数</span><span>{{ failObj.failNum+failObj.successNum }}</span>
          <span class="fail-num">通过</span><span style="color: rgba(32, 201, 139, 1);font-size: 16px;">{{ failObj.successNum }}</span>
          <span class="fail-num">失败</span><span style="color: rgba(233, 86, 82, 1);font-size: 16px;">{{ failObj.failNum }}</span>
        </div>
        <p style="margin-top:16px">以下是本次导入失败的列表详情，请修改后重新导入<el-button
          type="text"
          :size="$buttonSize"
          @click="downLoadReason"
        >下载失败原因</el-button></p>
        <el-table :data="failObj.list">
          <el-table-column
            v-for="v in tableColumns"
            :key="v.prop"
            :prop="v.prop"
            :label="v.label"
            :width="v.width"
          />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    fileConfig: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      visibleDialog: false,
      processData: {},
      fileList: [],
      failObj: {},
      failDialog: false,
      tableColumns: [],
    };
  },
  watch: {
    showDialog: {
      handler(nv) {
        this.visibleDialog = nv;
      },
    },
  },
  mounted() {},
  methods: {
    failClose() {
      this.failObj = {};
    },
    viewReason(row) { // 查看原因
      this.failObj = row.data;
      console.log(this.failObj, 'failObj');
      this.failDialog = true;
    },
    downLoadReason() { // 下载失败原因

    },
    deleteFileItem(v, i) {
      this.fileList.splice(i, 1);
    },
    close() {
      this.visibleDialog = false;
      this.fileList = [];
      this.failObj = {};
      this.processData = {};
      this.$emit('update:showDialog', false);
    },
    jyFile(file) { // 校验文件
      console.log(file, 'file');
      const maxSize = this.fileConfig?.size ? this.fileConfig?.size * 1024 * 1024 : 1024 * 1024 * 1024; // 10MB，根据你的需求设置最大文件大小
      if (file.size > maxSize) {
        this.$message.warning(`文件大小超过了${maxSize / (1024 * 1024)}MB的限制`);
        return false;
      }
      return true;
    },
    async uploadChange(e, fileList) {
      const file = e.raw;
      if (!this.jyFile(file)) return;
      console.log(file, fileList, this.fileConfig, 'file');
      const fileData = new FormData();
      for (const key in this.fileConfig.uploadParams) {
        if (Object.hasOwnProperty.call(this.fileConfig.uploadParams, key)) {
          fileData.append(key, key === 'param' ? JSON.stringify(this.fileConfig.uploadParams[key]) : this.fileConfig.uploadParams[key]);
        }
      }
      fileData.append('file', file);
      // const res = await this.$apis.importCheck(params);
      const url = window.origin.replace(/^https?:/, '') + (process.env.NODE_ENV !== 'production' ? '/dev' : '') + '/pub/baseData/importCheck.action';
      console.log(url, 'uuu');
      fetch(url, {
        method: 'POST',
        body: fileData,
      }).then(response => response.json()) // 假设服务器返回 JSON 数据
        .then(async res => {
          await this.$apis.getProcess({ importKey: res.data.result }).then(res => {
            this.processData = res.data.result;
            this.fileList = [...this.fileList, { name: file.name, process: res.data.result.progress, data: res.data.result }];
            console.log(this.fileList, '文件');
            this.tableColumns = [
              { label: '行号', prop: 'line', width: 100 },
              ...res.data.result.columns.map(v => {
                return {
                  label: v.title,
                  prop: v.field,
                };
              }),
              { label: '失败原因', prop: 'reason' },
            ];
            console.log(this.tableColumns, 'this.tableColumns ');
          });
          this.$emit('importCallBack', file);
        });
    },
    async downloadTemplate() {
      const { data, fileName } = await this.$apis.downLoadTemplate({ moduleName: this.fileConfig.uploadParams.moduleName });
      console.log(data, fileName, 'flfl');
      const link = document.createElement('a');
      link.href = URL.createObjectURL(data);
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
      // const url = window.origin.replace(/^https?:/, '') + (process.env.NODE_ENV !== 'production' ? '/dev' : '') + `/pub/baseData/downloadTemplate.action?moduleName=${this.fileConfig.uploadParams.moduleName}`;
      // fetch(url, {
      //   method: 'GET',
      // })
      //   .then(async(response) => {
      //     if (!response.ok) {
      //       const text = await response.text();
      //       throw new Error(text);
      //     }
      //     const contentDisposition = response.headers.get(
      //       'Content-Disposition',
      //     );
      //     let filename = '导出文件.csv'; // 默认值
      //     if (contentDisposition) {
      //       const filenameMatch = contentDisposition.match(
      //         /filename=("?)([^";]+)\1/i,
      //       );
      //       if (filenameMatch && filenameMatch[2]) {
      //         const encodedName = filenameMatch[2].replace(/\+/g, '%20');
      //         filename = decodeURIComponent(encodedName);
      //       }
      //     }
      //     return response.blob().then((blob) => ({ blob, filename }));
      //   })
      //   .then(({ blob, filename }) => {
      //     console.log(blob, filename, '文件信息');
      //     const link = document.createElement('a');
      //     link.href = URL.createObjectURL(blob);
      //     link.download = filename; // 动态设置文件名
      //     document.body.appendChild(link);
      //     link.click();
      //     document.body.removeChild(link);
      //     URL.revokeObjectURL(link.href);
      //   })
      //   .catch((error) => {
      //     console.error('下载失败:', error);
      //   });
      // console.log(res, 'res');
    },
    submit() {
      this.$apis.importData({ importKey: this.processData.importKey }).then(res => {

      });
    },
  },
};
</script>

<style lang="scss" scoped>
:deep(.el-upload-dragger),:deep(.el-upload){
  width:100%
}
.import-false{
  color:var(--table-text-color);
  background-color: var(--card-bg);
  .false-box{
    border-radius: 4px;
      opacity: 1;
      height:45px;
      display:flex;
      align-items: center;
  }
}
.fail-text{
  color:var(--color-90);
  margin-right:12px
}
.fail-num{
  color:var(--color-44);
  font-size:12px;
  margin-left:25px
}
.file-li{
  height:24px;
  cursor:pointer;
  display:flex;
  justify-content: space-between;
  align-items: center;
  padding:0 8px;
  font-size:14px;
  .right-btn{
    display: none;
  }
   .right-status{
    display:block
  }
  i{
    font-size:14px
  }
}
.file-li:hover{
  background:var(--card-border);
  .right-btn{
    display:block
  }
  .right-status{
    display:none
  }
}
</style>
