<template>
  <div class="comp-sql-editor">
    <div class="dbsours">
      <div>
        数据源选择：
        <el-select v-model="datasourceId" size="mini" style="width: 150px" @change="onDsChange">
          <el-option v-for="(attr, i) of dbSourceList" :key="i" :label="attr.dsDb" :value="attr.id"></el-option>
        </el-select>
      </div>
      <el-input v-model="tableSearchKey" style="margin-top: 10px" clearable placeholder="搜索数据表" size="mini"
                @input="onSelectTable"></el-input>
      <el-collapse class="dbsoursTable" v-model="activeName" accordion @change="tableListChange"
                   v-loading="dbsoursTableLoading">
        <el-collapse-item v-for="(table, i) of tableListed" :key="i" :name="table.tableViewName">
          <template slot="title">
            <div class="tableListColumns" :title="(table.tableComments || '未命名') + ' ' + table.tableViewName"
                 style="width: 190px">
              {{ (table.tableComments || "未命名") + " " + table.tableViewName }}
            </div>
            <i class="el-icon-document-copy" @click.stop.prevent @click="onInsertField(table.tableViewName)"></i>
          </template>
          <div v-loading="columnsLoading">
            <div class="tableListColumns tableListchild" v-for="(z, x) in tableListColumns" :key="x">
              {{ z.columnName }}
              <i class="el-icon-document-copy" @click="onInsertField(z.columnName)"></i>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div class="main">
      <div class="label label-title">
        <aceEditor ref="editor" :font-size="16" :value="value" @change="onChange" height="500" lang="sql" snippets wrap />
      </div>
    </div>
    <div class="panel" style="margin-right: 10px">
      <div class="label">点击引用字段</div>
      <div class="search-box">
        <el-input v-model="computedSearchKey" clearable placeholder="输入以搜索" size="mini"></el-input>
      </div>
      <div class="fields">
        <div class="tab">维度</div>
        <template v-for="field of tobeChooseWeiduSearched">
          <div :key="field.columnTitle"
               :title="field.columnName" class="weidu" @click="onComputedAddField(field)">
            {{ field.columnTitle + "【" + field.columnName + "】" }}
          </div>
        </template>
        <div class="tab">指标</div>
        <template v-for="field of tobeChooseZhibiaoSearched">
          <div :key="field.columnTitle"
               :title="field.columnName" class="zhibiao" @click="onComputedAddField(field)">
            {{ field.columnTitle + "【" + field.columnName + "】" }}
          </div>
        </template>
      </div>
    </div>
    <div class="panel">
      <el-popover ref="paramSelector" placement="bottom-start" trigger="click">
        <el-cascader-panel v-model="nowParam" :options="paramList"
                           :props="{ expandTrigger: 'click', emitPath: false, value: 'paramKey' }"
                           @change="onSetParam"></el-cascader-panel>
        <span slot="reference" class="label" style="color: #409eff; cursor: pointer"> <i class="el-icon-plus"></i> 添加全局参数 </span>
      </el-popover>
      <div class="label">点击引用函数</div>
      <div class="search-box">
        <el-select v-model="funcAttr" size="mini" style="width: 110px">
          <el-option v-for="(attr, i) of funcAttrList" :key="i" :label="attr.message" :value="attr.value"></el-option>
        </el-select>
        <el-input v-model="funcKey" clearable placeholder="搜索" size="mini" style="width: 90px"
                  @input="onSearchFunc"></el-input>
      </div>
      <div class="functions">
        <div v-for="(func, i) of functionListSearched" :title="func.description" class="func"
             @click="onComputedAddFunc(func.method)">
          {{ func.name }}
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import aceEditor from "@/components/AceEditor/index.vue";
import { listViewsByDataSource } from "@/api/workFlow/FlowEngine";
import { reportdatasourcePage } from "@/api/newbi/report";
import { listColumnsByDatasource } from "@/components/Dataset-filter/report";
import { cubeFieldList, jsfuncAttrList } from "@/api/newbi/dataset";
import { categoryList, paramList } from "@/api/newbi/globalParams";
import { funcList } from "@/api/newbi/func";
export default {
  components: { aceEditor },
  model: { prop: "value", event: "change" },
  props: ["cubeId", "value"],
  data() {
    return {
      datasourceId: "",
      tableSearchKey: "",
      dbsoursTableLoading: false,
      tableList: [],
      tableListed: [],
      dbSourceList: [],
      activeName: "",
      columnsLoading: false,
      tableListColumns: [],
      computedSearchKey: "",
      tobeChooseWeidu: [],
      tobeChooseZhibiao: [],
      nowParam: [],
      paramList: [],
      funcAttr: -1,
      funcAttrList: [],
      funcKey: "",
      functionListSearched: []
    };
  },
  computed: {
    // 计算字段编辑框里维度字段
    tobeChooseWeiduSearched() {
      let key = this.computedSearchKey;
      return this.tobeChooseWeidu.filter((i) => {
        return i.columnName.toUpperCase().includes(key) || i.columnTitle.includes(key);
      });
    },
    // 计算字段编辑框里指标字段
    tobeChooseZhibiaoSearched() {
      let key = this.computedSearchKey;
      return this.tobeChooseZhibiao.filter((i) => {
        return i.columnName.toUpperCase().includes(key) || i.columnTitle.includes(key);
      });
    }
  },
  created() {
    this.getInitData();
    this.getGlobalData();
  },
  methods: {
    onChange(val) {
      this.$emit("change", val);
    },
    onSearchFunc() {
      let { name } = this.funcAttrList.find((i) => i.value == this.funcAttr);
      let funcKey = this.funcKey.toLowerCase();
      let list = [];
      if (this.funcAttr == -1) {
        list = [...this.functionList];
      } else {
        list = this.functionList.filter((i) => i.funcAttr == name);
      }
      this.functionListSearched = list.filter((i) => {
        let name = i.name.toLowerCase();
        let description = i.description.toLowerCase();
        return name.includes(funcKey) || description.includes(funcKey);
      });
    },
    onDsChange(val) {
      this.tableSearchKey = "";
      this.dbsoursTableLoading = true;
      listViewsByDataSource({ datasourceId: val, current: 1, size: 10000 }).then((res) => {
        this.tableList = res.data.data.records;
        this.tableListed = res.data.data.records;
        this.dbsoursTableLoading = false;
      });
    },
    onSelectTable(val) {
      this.tableListed = this.tableList.filter((i) => (i.tableComments && i.tableComments.includes(val)) || i.tableViewName.includes(val));
    },
    tableListChange(val) {
      if (val) {
        this.columnsLoading = true;
        listColumnsByDatasource({ tableViewName: val, datasourceId: this.datasourceId }).then((res) => {
          this.tableListColumns = res.data.data;
          this.columnsLoading = false;
        });
      }
    },
    onInsertField(table) {
      this.$refs.editor.editor.insert(table);
    },
    onComputedAddField(field) {
      this.$refs.editor.editor.insert(`[${field.columnName}]`);
    },
    onSetParam(val) {
      this.$refs.editor.editor.insert(`\${${val}}`);
    },
    onComputedAddFunc(method) {
      this.$refs.editor.editor.insert(method);
    },
    getGlobalData() {
      categoryList({ size: 10000, current: 1 }).then((res) => {
        let list = res.data.data.records;
        let parents = list.filter((i) => !i.parentId);
        let categoryList = [];
        list.forEach((i) => {
          i.children = [];
          if (i.parentId) {
            let parent = parents.find((j) => j.id == i.parentId);
            parent.hasChild = true;
            i.label = parent.typeName + " / " + i.typeName;
            categoryList.push(i);
          } else {
            i.label = i.typeName;
          }
        });
        categoryList = categoryList.concat(parents.filter((i) => !i.hasChild));
        paramList({ size: 10000, current: 1 }).then((res) => {
          let params = res.data.data.records;
          params.forEach((i) => {
            i.label = i.paramName;
            let parent = categoryList.find((j) => j.id == i.typeId);
            parent.children.push(i);
          });
          this.paramList = categoryList;
        });
      });
    },
    getInitData() {
      reportdatasourcePage({ current: 1, size: 1000 }).then((res) => {
        this.dbSourceList = res.data.data.records;
      });
      cubeFieldList({ cubeDataId: this.cubeId }).then((res) => {
        let tableFieldsWeidu = res.data.data.filter((i) => i.dimensionType === "WEIDU").sort((a, b) => a.sortNum - b.sortNum);
        let tableFieldsZhibiao = res.data.data.filter((i) => i.dimensionType === "ZHIBIAO").sort((a, b) => a.sortNum - b.sortNum);
        this.tobeChooseWeidu = tableFieldsWeidu.filter((i) => i.columnAttr == "NORMAL");
        this.tobeChooseZhibiao = tableFieldsZhibiao.filter((i) => i.columnAttr == "NORMAL");
      });
      jsfuncAttrList().then((res) => {
        let list = res.data.data;
        list.unshift({ value: -1, name: "", message: "全部类型" });
        this.funcAttrList = list;
      });
      funcList({ dsType: "mysql" }).then((res) => {
        logjson(res.data.data)
        this.functionList = res.data.data;
        this.functionListSearched = [...this.functionList];
        this.funcAttr = -1;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.comp-sql-editor {
  display: flex;
  height: 500px;
  overflow-y: hidden;
  .dbsoursTable {
    height: calc(100% - 75px);
    width: 238px;
    overflow-y: auto;
    padding-top: 10px;
    cursor: pointer;
    font-size: 12px;
    .tableListColumns {
      padding-left: 10px;
      line-height: 27px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      //使i图标居中靠右
      i {
        float: right;
        margin-top: 7px;
        margin-right: 8px;
      }
    }
    .tableListchild {
      background-color: #efefef;
      padding-left: 20px;
      margin-bottom: 5px;
    }
  }
  .main {
    flex: 1;
    margin: 0 10px;
    .label-title {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  .panel {
    flex: 0 0 200px;
    width: 200px;
    font-size: 12px;
    .tab {
      line-height: 30px;
    }
    .functions,
    .fields {
      overflow-y: auto;
      padding: 0 10px 10px;
      background-color: #fff;
    }
    .fields {
      height: calc(100% - 70px);
    }
    .functions {
      height: calc(100% - 100px);
    }
    .search-box {
      height: 35px;
    }
    .weidu {
      line-height: 24px;
      box-sizing: border-box;
      border: 1px solid #1d54d5;
      background-color: #e4eafa;
      padding: 0 10px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin: 3px 0;
      cursor: pointer;
    }
    .zhibiao {
      line-height: 24px;
      box-sizing: border-box;
      border: 1px solid #00b375;
      background-color: #d4f2e8;
      padding: 0 10px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin: 3px 0;
      cursor: pointer;
    }
    .func {
      line-height: 24px;
      box-sizing: border-box;
      border: 1px solid #ccc;
      padding: 0 10px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin: 3px 0;
      cursor: pointer;
    }
  }
}
</style>
