<template>
  <el-dialog
    title="导出"
    :visible.sync="visibleDialog"
    width="400px"
    class="export-dialog"
    @close="close"
  >
    <el-form
      ref="form"
      :model="form"
      label-width="60px"
    >
      <el-row>
        <el-form-item label="范围">
          <el-radio-group v-model="form.exportScope">
            <el-radio label="page">导出当前页</el-radio>
            <el-radio label="all">导出全部</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="类型">
          <el-radio-group v-model="form.exportType">
            <el-radio label="xls">Excel</el-radio>
            <el-radio label="csv">CSV</el-radio>
            <el-radio label="txt">TxT</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
    >
      <el-button
        type="primary"
        class="btn"
        @click="submitExport"
      >{{
        $t("button.confirm")
      }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { commonMore } from '../../utils/index';
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    exportParams: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      visibleDialog: false,
      form: {
        exportType: 'csv',
        exportScope: 'all',
      },
    };
  },
  watch: {
    showDialog: {
      handler(nv) {
        this.visibleDialog = nv;
      },
    },
  },
  mounted() {},
  methods: {
    close() {
      console.log('关闭了');
      this.visibleDialog = false;
      this.$emit('update:showDialog', false);
      this.form = {
        exportType: 'csv',
        exportScope: 'all',
      };
    },
    async submitExport() {
      const params = { ...this.form, ...this.exportParams };
      if (this.form.exportScope === 'all') {
        delete params.pageStart;
        delete params.pageLimit;
      }
      console.log(params, 'ppp');
      const exportParams = commonMore.dataHandler(params);

      const res = await this.$apis.exportData(exportParams);
      console.log(res, 'res');
      this.download(res.data.result);
    },
    download(ticket) {
      const action = window.origin.replace(/^https?:/, '') + '/dcs/baseQuery/download.action';
      // ticket = '8572f582-f927-40f1-b487-27ce3b4e5119'
      const url = `${action}?queryParam.ticket=${ticket}`;
      console.log(action, 'aaa');
      fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/vnd.ms-excel;charset=UTF-8',
        },
      })
        .then(async(response) => {
          if (!response.ok) {
            const text = await response.text();
            throw new Error(text);
          }
          // 关键：确保服务器暴露 Content-Disposition 头
          const contentDisposition = response.headers.get(
            'Content-Disposition',
          );
          let filename = '导出文件.csv'; // 默认值

          if (contentDisposition) {
            // 关键步骤：提取并解码 Java URLEncoder 编码的文件名
            const filenameMatch = contentDisposition.match(
              /filename=("?)([^";]+)\1/i,
            );
            if (filenameMatch && filenameMatch[2]) {
              // 替换 "+" 为 "%20"（解决 Java URLEncoder 的空格编码问题）
              const encodedName = filenameMatch[2].replace(/\+/g, '%20');
              // 解码 URL 编码
              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);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.export-dialog{
  :deep(.el-form-item__content){
    line-height:40px
  }
}
</style>
