<template>
  <div class="page-view border-radius-5">
    <div class="flex-row bg-white px-15 border-radius-5">
      <!--      <el-page-header content="" @back="handleBack" />-->
      <app-filter ref="app-filter" :model="filters" class="flex-1" @query="onQuery"
                  @reset="onReset(true, { clusterId: $route.query.id })"
      >
        <app-filter-item label="表资源名称" prop="name">
          <el-input v-model="filters.name" clearable placeholder="请输入"
                    @keyup.enter.native="$refs['app-filter'].query"
          />
        </app-filter-item>
        <!--        <app-filter-item label="资源编码" prop="pointCode">-->
        <!--          <el-input v-model="filters.code" clearable placeholder="请输入" @keyup.enter.native="$refs['app-filter'].query" />-->
        <!--        </app-filter-item>-->
      </app-filter>
    </div>

    <div class="flex-1 bg-white flex-col border-radius-5 pa-11 mt-11">
      <app-table
        :column="columns"
        :pagination="pagination"
        :table-data="tableData"
        :table-loading="tableLoading"
        :total="total"
        @row-dblclick="editSource"
        @pagination-change="onPaginationChange"
      >
        <template #deployed="scope">
          <el-tag :type="scope.row['deployed'] === 1 ? '' : 'danger'">{{ scope.row['deployed'] === 1 ? '已发布' : '未发布'
          }}
          </el-tag>
        </template>
      </app-table>
    </div>

    <app-dialog v-model="downVisible" append-to-body class="down-dialog" hide-footer title="数据导入" width="400px">
      <div class="mb-35">请先下载模板，填写完成后再导入</div>
      <div class="btn-row flex-row-e-c">
        <el-button :loading="uploadLoading" class="mr-10" icon="el-icon-download" size="mini" type="text"
                   @click="downLoad"
        > 下载模板
        </el-button>
        <el-upload
          ref="upload"
          :action="actionUrl"
          :data="uploadFilter"
          :headers="headers"
          :multiple="false"
          :show-file-list="false"
          v-bind="{ ...UPLOAD_CONFIG }"
        >
          <el-button :loading="uploadLoading" icon="el-icon-upload2" size="mini" type="primary">导入表数据</el-button>
        </el-upload>
      </div>
    </app-dialog>
    <!--    <trigger-dialog v-model="triggerVisible" :data="currentRow" title="查看触发器" @confirm="refresh" />-->
    <detail-dialog v-model="dialogVisible" :data="currentRow" :title="dialogTitle" />
    <!--    <manual-dialog v-model="manualVisible" :cluster-id="filters.clusterId" :data="currentRow" :title="manualTitle" @confirm="refresh" />-->
  </div>
</template>

<script>
import companyAPI from '@/api/business/dataCollectCompany';
import API from '@/api/business/dataCollectItem';
import tableMixin from '@/mixins/table.js';

import DetailDialog from './DetailDialog';
// import ManualDialog from './ManualDialog';
// import TriggerDialog from './TriggerDialog'; downLoadFile
import { mapState } from 'vuex';
import DICT from '@/utils/dict';

export default {
  components: { DetailDialog },
  mixins: [tableMixin],
  props: {
    providerRow: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    const TABLE_CONFIG = {
      columns: [
        { label: '表资源名称', prop: 'name' },
        { label: '表资源编码', prop: 'code', width: '400' },
        {
          label: '数据库表名',
          width: '350',
          prop: 'tableNameEn',
        },
        {
          label: '是否发布',
          prop: 'deployed',
          width: '150',
          align: 'center',
          dataType: 'slot', // 使用插槽
          slot: 'deployed', // 插槽名，搭配 dataType: 'slot' 使用
        },
        {
          dataType: 'option',
          label: '操作',
          width: '280px',
          fixed: 'right',
          operation: [
            {
              name: '导入数据',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-upload2',
              plain: true,
              disabled: (row) => {
                return row.deployed !== 1;
              },
              clickFun: (row) => {
                this.currentRow = row;
                this.downVisible = true;
              },
            },
            {
              name: '查看数据',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-view',
              plain: true,
              disabled: (row) => {
                return row.deployed !== 1;
              },
              clickFun: async (row) => {
                this.currentRow = row;
                this.dialogVisible = true;
                this.dialogTitle = `表数据详情: ${row.name} - ${row.tableNameCh}`;
              },
            },
          ],
        },
      ],
      defaultFilter: [
        {
          operation: 'EQUAL',
          property: '',
          relation: 'AND',
          value: '',
        },
        {
          operation: 'EQUAL',
          property: 'deployed',
          relation: 'AND',
          value: '1',
        },
      ],
      rowData: {},
    };

    const DIALOG_CONFIG = {
      dialogVisible: false,
      dialogTitle: '新增',
      manualVisible: false,
      manualTitle: '新增',
    };

    const UPLOAD_CONFIG = {
      beforeUpload: (file) => {
        return new Promise((resolve, reject) => {
          this.uploadLoading = true;
          const { size, name } = file;
          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();
        });
      },
      onError: (res) => {
        const res_ = JSON.parse(res.message);
        this.$message.error(res_.message || '导入失败，请重试');
        this.uploadLoading = false;
      },
      onSuccess: async (res) => {
        if (res.state) {
          this.$message.success('导入成功');
          this.uploadLoading = false;
          this.downVisible = false;
        } else {
          this.$message.error(res.message);
        }
      },
    };

    return {
      ...TABLE_CONFIG, // table相关
      ...DIALOG_CONFIG, // 主列表dialog相关
      UPLOAD_CONFIG, // 抽屉相关
      downVisible: false,
      uploadLoading: false,
      triggerVisible: false,
      clusterId: '',
    };
  },
  computed: {
    actionUrl: (_) => `${window.context.portal}/biz/dataCollect/clusterTable/v1/importMain`,
    ...mapState({
      headers: (state) => ({
        Authorization: `Bearer ${state.login.currentUser.token}`,
      }),
    }),
    uploadFilter() {
      return this.currentRow?.id
        ? {
          tableId: this.currentRow.id,
        }
        : {};
    },

    dataMethod() {
      return companyAPI.getDataSourceList;
    },
    // initRefresh: () => false,
  },
  methods: {
    handleBack() {
      this.$router.push({
        name: 'dataCollectCompany',
      });
    },
    filterDict(dictKey, val) {
      const def = { label: '', value: val };
      if ([null, undefined, ''].includes(val)) {
        return def;
      }
      return DICT[dictKey].find((item) => item.value === val) || def;
    },
    async downLoad() {
      try {
        this.uploadLoading = true;
        await API.downLoadFile(this.currentRow.id);
      } catch (e) {
        console.log(e.message || '下载失败');
      } finally {
        this.uploadLoading = false;
      }
    },
    addSource() {
      this.manualTitle = '新增';
      this.currentRow = null;
      this.manualVisible = true;
    },
    editSource(row) {
      this.manualTitle = `编辑 - ${row.name}`;
      this.currentRow = row;
      this.manualVisible = true;
    },
    onBeforeGetData(queryParams, formData) {
      this.setFilterValue(this.queryParams, this.defaultFilter, 'deployed', '1');
    },
    delSource(row) {
      this.$confirm(`此操作将永久删除资源项（${row.name}）, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        await API.delSource(row.id);
        this.$message.success('删除成功');
        this.refresh();
      });
    },
    onCompanyConfirm(data) {
      const id = this.tableData.length++;
      if (data?.id) {
        const ind = this.tableData.findIndex((o) => o.id == data.id);
        ind >= 0 && this.tableData.splice(ind, 1, data);
      } else {
        this.tableData.push({ ...data, id });
      }
      this.dialogVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.down-dialog {
  display: flex;
  justify-content: center;
  align-items: center;

  ::v-deep {
    .gz-dialog {
      margin: 0px !important;
      min-height: 0;
    }

    .app-dialog-content {
      height: auto;
    }
  }
}
</style>
