<template>
  <div class="blank-page page-view w-100 h-100">
    <div class="header pa-15 flex">明细层数据管理：{{ origintTableData.name || '' }}</div>
    <div class="footer flex-row-s-c">
      <el-popover v-model="uploadVisible" placement="bottom" trigger="hover">
        <p>请先下载模板，填写完成后上传</p>
        <div class="text-c flex-row-c">
          <el-button class="mr-10" @click="download" type="primary" plain>下载模板</el-button>
          <el-upload
            ref="upload"
            :action="actionUrl"
            :before-upload="beforeUpload"
            :data="importData"
            :headers="headers"
            :multiple="false"
            :on-error="handleError"
            :on-success="handleSuccess"
            :show-file-list="false"
          >
            <el-button size="mini" type="warning" plain>导入数据</el-button>
          </el-upload>
        </div>
        <el-button slot="reference" :loading="uploadLoading" class="ml-10" icon="el-icon-upload2" type="primary"> 导入数据 </el-button>
      </el-popover>
    </div>
    <div class="flex-1 mx-15 mb-15 pa-15 bg-white border-radius-5 flex-col overflow-h">
      <template v-if="columns.length">
        <app-table
          :column="columns"
          :pagination="pageOption"
          :table-data="tableData"
          :table-loading="tableLoading"
          :total="total"
          @pagination-change="onPaginationChange"
          @row-dblclick="handleDetail"
        >
        </app-table>
      </template>
      <template v-else>
        <div class="flex-row-c h-100 w-100">
          <el-empty></el-empty>
        </div>
      </template>
    </div>
    <viewDetailDialog v-model="viewVisible" :data="viewData" :title="viewDialogTitle"></viewDetailDialog>
  </div>
</template>
<script>
import API from '@/api/business/dataDWCatalog';
import tableMixin from '@/mixins/table.js';
import viewDetailDialog from './viewDetailDialog.vue';
import { mapState } from 'vuex';
export default {
  name: 'DWDetaileDataQuery',
  components: { viewDetailDialog },
  mixins: [tableMixin],
  computed: {
    actionUrl: (_) => `${window.context.portal}/biz/dataResource/dwTable/v1/importMain`,
    ...mapState({
      headers: (state) => ({
        Authorization: `Bearer ${state.login.currentUser.token}`,
      }),
    }),
  },
  data() {
    return {
      columns: [],
      tableLoading: false,
      total: 0,
      filters: {
        order: '',
        param: {},
      },
      pageOption: {
        // 分页初始化数据
        pageNo: 1,
        pageSize: 20,
      },
      origintTableData: {},
      tableData: [],

      uploadLoading: false,
      uploadVisible: false,
      importData: { tableId: '' },

      viewVisible: false,
      viewData: {},
      viewDialogTitle: '',
    };
  },
  watch: {
    '$route.query': {
      immediate: true,
      deep: true,
      handler(data) {
        this.initData(data); // 获取url上传递的参数
      },
    },
  },
  methods: {
    /**
     * @description: dialog每次显示时触发的init方法
     * @param {*} data 传入data
     * @return {*}
     */
    initData(data) {
      this.origintTableData = { ...data };
      this.importData.tableId = this.origintTableData.id || '';
      if (data.id) {
        this.filters.tableId = data.id;
        this.getData();
      }
    },
    async getData() {
      try {
        this.tableLoading = true;
        const params = {
          ...this.filters,
          ...this.pageOption,
        };

        let QueryAPI;
        if (this.origintTableData.tableClass === '1') {
          // 物理表
          QueryAPI = API.queryWLTableData;
        } else if (this.origintTableData.tableClass === '2') {
          // 动态表
          QueryAPI = API.queryDTTableData;
        }

        const { data = [], field = {}, total = 0 } = await QueryAPI(params);

        if (this.origintTableData.tableClass === '2') {
          this.tableData = data.map((item) => {
            return JSON.parse(item?.DATA_JSON_ || '');
          });
        } else {
          this.tableData = data || [];
        }
        this.total = total || 0;
        this.columns = [];
        for (const [key, value] of Object.entries(field)) {
          this.columns.push({
            label: value,
            prop: key,
            minWidth: '120',
          });
        }
      } catch (e) {
        console.log(e);
      } finally {
        this.tableLoading = false;
      }
    },
    handleDetail(row) {
      console.log(row, 'handleDetail');
      this.viewVisible = true;
      this.viewData = { formData: row, columns: this.columns };
      this.viewDialogTitle = '数据详情：' + this.origintTableData.name;
    },
    // 分页触发
    onPaginationChange(page) {
      this['filter'] = {
        ...this['filter'],
        ...page,
      };
      this.pageOption = page;
      this.getData();
    },
    download() {
      API.downloadDataModel(this.origintTableData.id)
        .then((_) => this.$message.success('下载数据导入模板成功'))
        .finally((_) => {});
    },
    //  导入文件上传前
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        this.uploadLoading = true;
        const { size, name } = file;
        this.$confirm(`请确认是否导入 “${name}” ？`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then((_) => {
            let passedOrNot = true; // 是否通过验证
            const typeRegular = /\.(xls|xlsx)$/i;
            const verification = [
              {
                condition: !typeRegular.test(name),
                result: () => this.$message.error('只能上传xls或xlsx文件类型'),
              },
            ];
            verification.forEach((item) => {
              if (item.condition) {
                item.result();
                passedOrNot = false;
                this.uploadLoading = false;
              }
            });

            passedOrNot ? resolve() : reject();
          })
          .catch((_) => {
            reject();
            this.uploadLoading = false;
            this.$message.warning('已取消上传');
          });
      });
    },
    // 导入文件上传成功
    handleSuccess(res) {
      if (res.state) {
        this.$message.success('导入成功');
        this.uploadLoading = false;
        this.getData();
      } else {
        this.$message.error(res.message);
      }
    },
    // 导入文件上传失败
    handleError(err) {
      if (err) {
        let errData = err.toString().replace('Error:', '');
        errData = JSON.parse(errData);
        this.$message.error(errData.message || '导入失败，请重试');
      } else {
        this.$message.error('导入失败，请重试');
      }
      this.uploadLoading = false;
    },
  },
};
</script>
<style></style>
