<template>
  <div class="datasource-table-list">
    <div class="left">
      <div class="btns">
        <el-button icon="el-icon-edit" size="mini" type="primary" @click="showCategory = true">编辑分类</el-button>
        <el-button icon="el-icon-plus" size="mini" type="success" @click="onEditCategory(null)">添加分类</el-button>
      </div>
      <el-input
        v-model="categoryKey"
        placeholder="搜索分类"
        size="mini"
        style="margin-bottom: 10px"
        @input="onSearchCategory"
      ></el-input>
      <el-menu :default-active="nowCategoryId" @select="onSelectCategory">
        <el-menu-item :index="0">
          <div class="name" style="flex: 1">全部</div>
        </el-menu-item>
        <el-menu-item v-for="category in categoryListSearched" :key="category.id" :index="category.id">
          <div class="name" style="flex: 1">{{ category.categoryName }}</div>
        </el-menu-item>
      </el-menu>
    </div>
    <div class="right">
      <div class="top">
        <div>
          <el-input
            v-model="tableKey"
            clearable
            placeholder="请输入完整表名"
            size="mini"
            style="width: 200px"
          ></el-input>
          <el-button icon="el-icon-search" size="mini" type="primary" @click="getTableList">搜索</el-button>
        </div>
        <div>
<!--          <el-button plain size="mini" type="primary" @click="showUpload = true">文件上传</el-button>-->
<!--          <el-button plain size="mini" type="warning" @click="clear">清理数据表缓存</el-button>-->
        </div>
      </div>
      <div class="main">
        <el-table :data="tableList" border size="mini" :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
                  :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}">
          <el-table-column label="表名" prop="tableViewName"></el-table-column>
          <el-table-column label="备注" prop="tableComments"></el-table-column>
          <el-table-column label="分类" prop="categoryName"></el-table-column>
<!--          <el-table-column align="center" label="操作" width="560px">-->
          <el-table-column align="center" label="操作" width="300px">
            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click="onTableEdit(row)">编辑</el-button>
              <el-button size="mini" type="text" @click="tableFieldPreview(row)">字段预览</el-button>
              <el-button size="mini" type="text" @click="tableDataPreview(row)">数据预览</el-button>
<!--              <el-button plain size="mini" type="primary" @click="batchUpload(row)">批量导入</el-button>-->
<!--              <el-button plain size="mini" type="warning" @click="onShowBlood(row)">查看血缘</el-button>-->
<!--              <el-button plain size="mini" type="success" @click="onAddCube(row)">创建数据集</el-button>-->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page.sync="page.current"
        :page-size="page.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="page.total"
        background
        class="my-paging"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="sizeChange"
        @current-change="getTableList"
      ></el-pagination>
    </div>
    <el-dialog
      :visible.sync="showFieldPreview"
      append-to-body
      custom-class="table-field-preview-dialog"
      title="字段预览"
      width="80%"
    >
      <el-table :data="tableFieldData" border height="600px" size="mini" :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
                :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}">
        <el-table-column label="字段名称" prop="columnName"></el-table-column>
        <el-table-column label="字段类型" prop="dataType"></el-table-column>
        <el-table-column label="字段长度" prop="columnSize"></el-table-column>
        <el-table-column label="字段注释" prop="columnComments"></el-table-column>
      </el-table>
    </el-dialog>
    <blood v-model="showRelation" :table="table" type="table"></blood>
    <el-dialog :visible.sync="showCategory" append-to-body title="分类列表" width="600px">
      <el-table :data="categoryList" border size="mini">
        <el-table-column label="分类名" prop="categoryName"></el-table-column>
        <el-table-column label="分类描述" prop="remark"></el-table-column>
        <el-table-column align="center" label="操作" width="150px">
          <template v-slot="{ row }">
            <el-button plain size="mini" type="primary" @click="onEditCategory(row)">编辑</el-button>
            <el-button plain size="mini" type="danger" @click="categoryDel(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog :visible.sync="showCategoryEdit" append-to-body title="分类编辑" width="500px">
      <el-form label-width="80px" size="mini">
        <el-form-item label="分类名称">
          <el-input v-model="categoryForm.categoryName"></el-input>
        </el-form-item>
        <el-form-item label="分类描述">
          <el-input v-model="categoryForm.remark" :rows="3" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-btns">
        <el-button size="small" @click="showCategoryEdit = false">取消</el-button>
        <el-button size="small" type="primary" @click="categorySubmit">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showEdit" append-to-body title="表信息编辑" width="400px">
      <el-form label-width="80px" size="mini">
        <el-form-item label="表名">
          <el-input v-model="nowTable.tableViewName" class="my-disabled" disabled></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="nowTable.tableComments"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="nowTable.categoryId">
            <el-option :value="0" label="全部"></el-option>
            <el-option
              v-for="(item, i) of categoryList"
              :key="i"
              :label="item.categoryName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-btns">
        <el-button size="mini" type="primary" @click="onEditConfirm">确定</el-button>
        <el-button size="mini" @click="showEdit = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="`表【${nowTable.tableViewName}】数据预览`"
      :visible.sync="showDataPreview"
      append-to-body
      custom-class="table-data-preview-dialog"
      width="80%"
    >
      <el-table :data="tableDataData" border height="600px" size="mini" stripe
                :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
                :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}">
        <el-table-column v-for="(item, i) of tableDataColumn" :key="i" :label="item" :prop="item"></el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="dataPage.current"
        :page-size="dataPage.size"
        :page-sizes="[10, 40, 50, 100]"
        :total="dataPage.total"
        background
        class="my-paging"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="getTableData"
        @size-change="dataSizeChange"
      ></el-pagination>
    </el-dialog>
  </div>
</template>
<script>
import * as report from '@/api/report/report';
import * as classification from '@/api/classification/classification';
import APP_CONFIG from "../../../public/config";

export default {
  computed: {
    APP_CONFIG() {
      return APP_CONFIG
    }
  },
  data() {
    return {
      datasourceId: 0,
      showCategoryEdit: false,
      categoryForm: {},
      categoryEditType: 'add',
      showCategory: false,
      categoryKey: '',
      nowCategoryId: 0,
      categoryList: [],
      categoryListSearched: [],
      tableKey: '',
      tableList: [],
      page: { current: 1, size: 20, total: 0 },
      showFieldPreview: false,
      tableFieldData: [],
      showRelation: false,
      table: {},
      showEdit: false,
      nowTable: {},
      showDataPreview: false,
      dataPage: { current: 1, size: 40, total: 0 },
      tableDataColumn: [],
      tableDataData: [],
      uploadBoxVisible:false,
      showUpload: false,
    }
  },
  created() {
    this.datasourceId = this.$route.query.id;
    this.getCategoryList();
  },
  methods: {
    dataSizeChange(size) {
      this.dataPage.size = size;
      this.getTableData();
    },
    tableDataPreview(table) {
      this.nowTable = table;
      this.dataPage.current = 1;
      this.showDataPreview = true;
      this.getTableData();
    },
    getTableData() {
      let { current, size } = this.dataPage;
      let data = { current, size, tableName: this.nowTable.tableViewName, datasourceId: this.datasourceId };
      report.tableDataPreview(data).then(res => {
        let { records, total } = res.data;
        this.tableDataColumn = records.length ? Object.keys(records[0]) : [];
        this.tableDataData = records;
        this.dataPage.total = total;
      });
    },
    onTableEdit(table) {
      this.nowTable = table;
      this.showEdit = true;
    },
    onEditConfirm() {
      let data = { ...this.nowTable };
      delete data.categoryName;
      classification.updateTableComment(data).then(res => {
        this.$message.success('已保存');
        this.getTableList();
        this.showEdit = false;
      });
    },
    // 字段预览
    tableFieldPreview(e) {
      report.listColumnsByDatasource(e).then(res => {
        this.tableFieldData = res.data;
        this.showFieldPreview = true;
      });
    },
    // 获取分类列表
    getCategoryList() {
      this.categoryKey = '';
      classification.classList({ datasourceId: this.datasourceId }).then(res => {
        this.categoryList = res.data;
        this.categoryListSearched = [...this.categoryList];
        this.nowCategoryId = 0;
        this.getTableList();
      });
    },
    // 编辑分类
    onEditCategory(category) {
      if (category) {
        this.categoryForm = { ...category };
        this.categoryEditType = 'edit';
      } else {
        this.categoryForm = { categoryName: '', remark: '', datasourceId: this.$route.query.id };
        this.categoryEditType = 'add';
      }
      this.showCategoryEdit = true;
    },
    // 保存分类
    categorySubmit() {
      if (!this.categoryForm.categoryName) {
        return this.$message({ type: 'warning', message: '请输入分类名' });
      }
      let data = { ...this.categoryForm };
      let task;
      if (this.categoryEditType == 'add') {
        task = classification.addClassList(data);
      } else {
        task = classification.editClassList(data);
      }
      task.then(() => {
        this.$message({ type: 'success', message: '已提交' });
        this.showCategoryEdit = false;
        this.getCategoryList();
      });
    },
    // 删除分类
    categoryDel(id) {
      this.$confirm('确定删除此分类?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          classification.delClassList(id).then(() => {
            this.getCategoryList(); //左侧分类数据
            this.$message({ type: 'success', message: '已删除' });
          });
        })
        .catch(() => {});
    },
    // 获取数据表列表
    getTableList() {
      let { current, size } = this.page;
      let data = { datasourceId: this.datasourceId, current, size };
      if (this.tableKey) data.tableName = this.tableKey;
      if (this.nowCategoryId) data.classifyId = this.nowCategoryId;
      report.listViewsByDataSource(data).then(res => {
        if (!res.data) {
          this.page.total = 0;
          this.tableList = [];
          return;
        }
        let { records, total } = res.data;
        records.forEach(item => {
          let now = this.categoryList.find(i => i.id == item.categoryId);
          if (now) item.categoryName = now.categoryName;
          else item.categoryName = '-';
        });
        this.page.total = total;
        this.tableList = records;
      });
    },
    clear() {
      this.nowCategoryId = 0;
      this.tableKey = '';
      const loading = this.$loading({
        lock: true,
        text: '正在清理缓存',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      this.tableList = [];
      report.baseInforemoveBaseInfoCache({ datasourceId: this.datasourceId }).then(res => {
        this.getCategoryList();
        loading.close();
      });
    },
    sizeChange(size) {
      this.page.size = size;
      this.getTableList();
    },
    onSelectCategory(id) {
      this.nowCategoryId = id;
      this.getTableList();
    },
    onSearchCategory() {
      this.categoryListSearched = this.categoryList.filter(i => i.categoryName.includes(this.categoryKey));
    },
  },
};
</script>
<style lang="scss" scoped>
.datasource-table-list {
  height: 100%;
  padding-left: 10px;
  display: flex;
  overflow: hidden;
  background: #fff;

  .left {
    flex: 0 0 260px;
    padding-right: 10px;
    border-right: 1px solid #ccc;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .btns {
      margin: 10px 0;
      display: flex;
      justify-content: space-between;

      .el-button {
        width: 125px;
      }
    }

    .el-menu {
      flex: 1;
      overflow-y: auto;

      .el-menu-item {
        padding: 0 5px 0 10px;
        display: flex;
        align-items: center;
        height: 50px;
        line-height: 50px;

        .name {
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
    }
  }

  .right {
    flex: 1;
    padding: 10px;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 10px;
    }

    .main {
      flex: 1;
      overflow-y: auto;
    }
  }
}

.table-field-preview-dialog {
  .el-dialog__body {
    height: 700px;
  }
}

.table-data-preview-dialog {
  .el-dialog__body {
    height: 700px;
  }
}
</style>
>
