<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :ok-button-props="{ style: { display: 'none' } }"
    okText="保存"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading" style="background: #e6e9f1 !important;">
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="tableName"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :columns="columns"
        :dataSource="dataSource">
<!--        :locale="myLocale"-->

        <!-- 字符串超长截取省略号显示-->
      </a-table>
      <a-button type="primary" style="width:50%;" @click="exportTool(1)">导出csv</a-button>
      <a-button type="primary" style="width:50%;" @click="exportTool(2)">导出txt</a-button>
    </a-spin>
  </a-modal>
</template>

<script>
import moment from "moment"
import axios from 'axios'
import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID } from "@/store/mutation-types"
import { metaDataTypeTree } from '@/api/metaData'

  export default {
    name: "tablelist",
    components: {
    },
    data () {
      return {
        title:"导出表数据",
        visible: false,
        confirmLoading: false,
        queryParam: {
          sourceType: null,
          schemaMass: null,
          massKey: null,
          mdl: null,
          hn: null
        },
        dataSource:[],
        selectedRowKeys: [],
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'id',
            width:60,
            align:"id",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title: '报文名',
            align:"center",
            dataIndex: 'massName',
          },
          {
            title: '表名',
            align:"center",
            dataIndex: 'tableName'
          },
        ],
      }
    },
    created () {
      
    },
    methods: {
      add (sourceType, schemaMass, mdl, hn) {
        this.visible =true;
        this.queryParam.sourceType = sourceType;
        this.queryParam.schemaMass = schemaMass;
        this.queryParam.mdl = mdl;
        this.queryParam.hn = hn;
        this.getTableInfo();
      },
      getTableInfo(){
        metaDataTypeTree(this.queryParam).then(res => {
          if (res.code == 200) {
            var keys = Object.keys(res.result)
            keys.forEach((element, index) => {
              this.dataSource = res.result[element]
            });
          }
        })
      },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
      },
      exportTool(exportType){
        if(this.queryParam.schemaMass == ""){
            this.$message.warning("参数错误请重新打开导出");
            return;
        }
        if(this.selectedRowKeys.length <= 0){
            this.$message.warning("至少选择一个需要导出的表");
            return;
        }
        let apiBaseUrl = window._CONFIG['domianURL'] || "/jeecg-boot";
        const service = axios.create({
          baseURL: apiBaseUrl, // api base_url
          timeout: 300000 // 请求超时时间
        })
        service.interceptors.request.use(config => {
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token) {
            config.headers[ 'X-Access-Token' ] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
          }
          //update-begin-author:taoyan date:2020707 for:多租户
          let tenantid = Vue.ls.get(TENANT_ID)
          if (!tenantid) {
            tenantid = 0;
          }
          config.headers[ 'tenant_id' ] = tenantid
          //update-end-author:taoyan date:2020707 for:多租户
          if(config.method=='get'){
            if(config.url.indexOf("sys/dict/getDictItems")<0){
              config.params = {
                _t: Date.parse(new Date())/1000,
                ...config.params
              }
            }
          }
          return config
        },(error) => {
          return Promise.reject(error)
        })
        console.log(this.queryParam.sourceType)
        service({
          url: "/dataManager/DmExportTable?sourceType="+this.queryParam.sourceType+"&mdl="+this.queryParam.mdl+"&hn="+this.queryParam.hn+"&schemaMass="+this.queryParam.schemaMass+"&tableNames="+this.selectedRowKeys+"&exportType="+exportType,
          params: {},
          method:'post' ,
          responseType: 'blob'
        }).then((data) => {
          if (!data || data.size === 0) {
            this.$message.warning('文件下载失败')
            return
          }
          let filename = '1.zip'; // 默认文件名
          console.log(data)
          const disposition = data.headers['content-disposition'];
            // 处理编码文件名（如UTF-8''%E6%96%87%E4%BB%B6.txt）
          const filenameRegex = /filename\*?=((UTF-8'')([\w%\-\.]+)|(['"]?)([^;\n]*)\4)/i;
          const matches = disposition.match(filenameRegex);
          if (matches) {
            // 优先取编码后的文件名
            filename = matches[3] || matches[5];
            filename = decodeURIComponent(filename); // 解码
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data.data]), filename)
          } else {
            let url = window.URL.createObjectURL(new Blob([data.data]))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', filename)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          }
        })

      },
      onOk(value) {
        this.$emit('ok');
      },
      close () {
        this.$emit('ok');
        this.visible = false;
      },
      handleOk () {
        this.$emit('ok');
        this.close();
      },
      handleCancel () {
        this.$emit('ok');
        this.close()
      },
    }
  }
</script>

<style scoped>
.disabled{
  pointer-events: none;
}
</style>