<template>
  <div class="height100 userDefined-weiduNorm">
    <div class="biUserDefinedForm-add__title flexbox">
      <div class="flex text">
        <span @click="tabClick('tab1')" ref="tab1">数据源</span>
        <span @click="tabClick('tab2')" ref="tab2">维度指标</span>
      </div>
    </div>
    <!-- 数据源树 -->
    <div
      class="tab-content bi-def-dataSource-tree"
      v-show="currentTab==='tab1'"
      ref="biDefDataSourceTree"
    >
      <div class="search-tree flexbox">
        <div class="input flex">
          <ts-input v-model="keywords" placeholder="请输入关键字查询" @change="change($event)"></ts-input>
        </div>
      </div>
      <div class="third_mapping_tree flex tree__box">
        <vxe-table
          resizable
          height="100%"
          highlight-hover-row
          highlight-current-row
          :show-overflow="true"
          min-height="400"
          :show-header-overflow="true"
          row-key
          :show-header="false"
          ref="xTree"
          border="inner"
          :emptyText="emptyText"
          :tree-config="{lazy: true, children: 'children', hasChild: 'hasChild', line: true,loadMethod: treeObj.loadMethod,accordion:true}"
          :data="dataSourceTree"
          @toggle-tree-expand="toggleExpandChangeEvent"
        >
          <vxe-table-column :field="treeObj.textName" tree-node>
            <template v-slot="{ row }">
              <span class="tree-text__box" :title="row[treeObj.textName]">
                <template v-if="row.children && row.children.length">
                  <i
                    class="tree-node-icon"
                    :class="$refs.xTree.isTreeExpandByRow(row) ? treeObj.iconOpen : treeObj.iconClose"
                  ></i>
                </template>
                <template v-else>
                  <i class="tree-node-icon" :class="treeObj.iconNormal"></i>
                </template>
                <span
                  class="tree__text"
                  v-if="row.nodeType=='columnDefine'"
                  @dragstart="dragstart($event,'target',row)"
                  draggable="true"
                >{{ row[treeObj.textName] }}</span>
                <span
                  class="tree__text"
                  v-else-if="(row.queryName=='字段'&& row.children[0].nodeType !='dataset') || row.nodeType=='dataset'"
                  @dragstart="dragstart($event,'target',row)"
                  draggable="true"
                >{{ row[treeObj.textName] }}</span>
                <span class="tree__text" v-else>{{ row[treeObj.textName] }}</span>
              </span>
            </template>
          </vxe-table-column>
        </vxe-table>
        <!-- <ts-tree
          :source="treeObj"
          width="100%"
          height="100%"
          row-id="id"
          :is-border="false"
          :expandAll="false"
          :search-words="keywords"
          ref="thirdMappingTree"
          @radioChange="onTreeSelectRow"
        ></ts-tree>-->
      </div>
    </div>
    <!-- 维度指标 -->
    <div class="tab-content" v-show="currentTab==='tab2'">
      <div class="leftH50 flexYbox">
        <div class="search-tree flexbox">
          <div class="input flex">
            <ts-input
              placeholder="请选择维度"
              name="item.name"
              suffix-icon="iconfont icon-Group-14"
              @click="weiduOpen"
              :readonly="true"
            ></ts-input>
          </div>
        </div>
        <!-- 下拉框 -->
        <div style="position:relative;height:calc(100% - 30px)">
          <w-select :data="weidu" @change="weiduchange" :selectType="'weidu'" ref="weiduSelect"></w-select>
          <!-- 维度列表 -->
          <div
            class="flex biUserDefinedForm-add__listbox"
            style="position:absolute;left:0;top:0;width:100%"
          >
            <div
              v-for="(item, index) in condition"
              :key="index"
              class="biUserDefinedForm-add__slist"
              @click="conditionClick(item.dimensionId)"
            >{{item._name}}</div>
          </div>
        </div>
      </div>
      <div class="leftH50" style="border-top: 1px solid var(--border_color);">
        <div class="biUserDefinedForm-add__title flexbox" style="border-top: 1px #ffffff solid;">
          <div class="flex text">
            <span :class="{ active: norm_acv == 1 }" v-on:click="normAacFn(1)">指标</span>
            <span :class="{ active: norm_acv == 2 }" v-on:click="normAacFn(2)">通用指标</span>
          </div>
        </div>
        <div :style="{ display: norm_acv == 1 ? 'block':'none' }">
          <div class="search-tree flexbox">
            <div class="input flex">
              <ts-input
                placeholder="请选择指标"
                name="item.name"
                suffix-icon="iconfont icon-Group-14"
                @click="normOpen"
                :readonly="true"
              ></ts-input>
            </div>
            <i class="fa fa-search icons" aria-hidden="true"></i>
          </div>
          <w-select :data="norm" @change="normchange" :selectType="'norm'" ref="normSelect"></w-select>
          <div class="biUserDefinedForm-add__listT">
            <i class="iconfont icon-hezixiangzi" aria-hidden="true"></i> 已选指标
          </div>
          <div class="flex biUserDefinedForm-add__listbox">
            <div
              class="biUserDefinedForm-add__slist"
              v-for="(item,index) in target"
              :key="index"
              type="target"
              :uuid="item._id"
            >
              <span @dragstart="dragstart($event,'target',item)" draggable="true">{{ item._name }}</span>
            </div>
          </div>
        </div>
        <div :style="{ display: norm_acv == 2 ? 'block':'none' }">
          <div class="biUserDefinedForm-add__listT">
            <i class="iconfont icon-hezixiangzi" aria-hidden="true"></i> 通用指标
          </div>
          <div class="flex biUserDefinedForm-add__listbox common-target">
            <div
              v-for="(item,index) of targetDrags"
              :key="index"
              class="biUserDefinedForm-add__slist"
              :uuid="item.uuid"
              type="target"
            >
              <span @dragstart="dragstart($event,'target',item)" draggable="true">{{item.name}}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import wSelect from './weiduSelect'
export default {
  components: { wSelect },
  props: {
    biCustom: {
      type: Object,
      default: function() {
        return {
          weidu: [],
          norm: [],
          c_norm: [],
          currentTab: 'tab1',
          expandNode: {}
        }
      }
    }
  },
  data() {
    return {
      emptyText: '--暂无数据--',
      currentTab: this.biCustom.currentTab,
      keywords: '', // 树的关键字搜索
      targetDrags: [
        // 通用指标
        { uuid: '1', name: '均次', isCommon: true },
        { uuid: '2', name: '同比', isCommon: true },
        { uuid: '3', name: '环比', isCommon: true },
        { uuid: '4', name: '占比', isCommon: true },
        { uuid: '5', name: '去年同期', isCommon: true },
        { uuid: '6', name: '上期', isCommon: true },
        { uuid: '7', name: '合并列', isCommon: true }
      ],
      dataSourceTree: [],
      // treeObj:
      condition: this.biCustom.weidu || [],
      target: this.biCustom.norm || [],
      weidu: [],
      weidu_o: 1,
      norm: [],
      norm_o: 1,
      norm_acv: 1,
      weiduSelect: [] // 维度
    }
  },
  created() {},
  mounted() {
    this.tabClick(this.biCustom.currentTab || 'tab1')
    this.$nextTick(() => {
      this.getDataSourceTree('init')
      this.initData()
    })
  },
  computed: {
    treeObj() {
      return {
        data: this.dataSourceTree,
        lazy: true,
        hasChild: 'hasChild',
        loadMethod: this.loadMethod,
        dataType: 'local',
        textName: 'queryName',
        childName: 'children',
        type: '',
        iconOpen: 'iconfont icon-wenjianjia',
        iconClose: 'iconfont icon-wenjianjia1',
        iconNormal: 'iconfont icon-guanjianci'
      }
    }
  },
  methods: {
    // 键盘按下，数据源关键字搜索
    change(e) {
      this.keywords = e.value
      // 回车
      this.getDataSourceTree()
    },
    // 头部tab切换
    tabClick(tabId) {
      this.$refs.tab1.classList.remove('active')
      this.$refs.tab2.classList.remove('active')
      this.$refs[tabId].classList.add('active')
      this.currentTab = tabId
      this.biCustom.currentTab = tabId
    },
    // 树结构的懒加载
    loadMethod({ row }) {
      let _this = this
      if (row.children.length == 1 && row.hasChild == 'level1') {
        row.children = [
          { queryName: '参数', children: [], hasChild: 'level2' },
          { queryName: '字段', children: [], hasChild: 'level2' }
        ]
        if (row.conditionDefine) {
          // 参数
          for (let con of JSON.parse(row.conditionDefine)) {
            con.parent = {
              queryName: row.queryName,
              id: row.id,
              serviceType: row.serviceType
            }
            con.queryName = con.title + '(' + con.columnType + ')'
            con.nodeType = 'conditionDefine'
            row.children[0].children.push(con)
          }
        }
        if (row.columnDefine) {
          // 字段
          for (let col of JSON.parse(row.columnDefine)) {
            col.parent = {
              queryName: row.queryName,
              id: row.id,
              serviceType: row.serviceType
            }
            col.queryName = col.name + '(' + col.type + ')'
            if (row.serviceType == '2') {
              // 结果集
              col.nodeType = 'dataset'
              col.children = []
              for (let table of col.tableColumns) {
                table.nodeType = 'columnDefine'
                table.parent = {
                  queryName: row.queryName,
                  id: row.id,
                  resultName: col.name,
                  serviceType: row.serviceType
                }
                table.queryName = table.title + '(' + table.type + ')'
                col.children.push(table)
              }
            } else {
              col.nodeType = 'columnDefine'
            }
            row.children[1].children.push(col)
          }
        }
      }
      return new Promise(function(resolve, reject) {
        resolve(row.children)
      })
    },
    // 展开节点
    toggleExpandChangeEvent({ row, expanded }) {
      // 根节点
      if (row.hasChild == 'level1') {
        this.$nextTick(() => {
          this.biCustom.expandNode = JSON.parse(JSON.stringify(row))
        })
      }
    },
    // 左侧树的选中回调
    onTreeSelectRow(o) {},
    // 获取数据源数据
    getDataSourceTree(val) {
      let _this = this
      _this.emptyText = '数据加载中...'
      let data = { condition: this.keywords, pageSize: 2000 }
      this.$api({
        url: '/ts-query/api/user/define/service/list',
        method: 'post',
        data: JSON.stringify(data),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
        }
      })
        .then(function(response) {
          // 请求成功
          if (response.rows) {
            for (let row of response.rows) {
              row.hasChild = 'level1'
            }
            // 默认回显展开上次保存的节点
            // if (
            //   _this.biCustom.currentTab == 'tab1' &&
            //   Object.keys(_this.biCustom.expandNode).length > 0
            // ) {
            //   _this.$refs.xTree.setTreeExpand(_this.biCustom.expandNode, true)
            // }
            if(val && val == 'init'){
                _this.$store.commit('setDataSource',response.rows)
             }
            _this.dataSourceTree = [...response.rows]
            _this.dataSourceTree = _this.changeDateTree(_this.dataSourceTree)

            _this.emptyText = '--暂无数据--'
          } else {
            _this.$utils.msg(_this, response.message, 'error')
          }
        })
        .catch(function(error) {
          // 请求失败
          _this.emptyText = '--暂无数据--'
          _this.$utils.msg(_this, error.message, 'error')
        })
    },
    // 拖拽指标
    dragstart(ev, type, item) {
      this.$eventBus.$emit('dragstart', ev, type, item)
    },
    // 初始化
    initData() {
      if (this.condition.length == 0) {
        this.condition = [{ dimensionName: 'DIM_DATE_DAY' }] //设定初始值时间为必须
      }
      let self = this
      this.$api({
        url: '/ts-bi/api/bi/cube/queryDimension',
        method: 'get',
        data: {}
      })
        .then(function(response) {
          if (response.success) {
            let o = response.object || []
            let d = null
            var temp = o[0]
            for (var i in o) {
              var v = o[i]
              v.selected = 1 //未选中
              v._name = v.description
              v._id = v.dimensionId
              if (v.dimensionName === 'DIM_DATE_DAY') {
                //把时间放在第一个
                o[0] = o[i]
                o[i] = temp
              }
              for (let item of self.condition) {
                if (
                  v.dimensionName == 'DIM_DATE_DAY' ||
                  item.dimensionName == v.dimensionName
                ) {
                  self.weiduSelect.push(v)
                  v.selected = v.dimensionName == 'DIM_DATE_DAY' ? 3 : 2 //3默认无法取消
                  break
                }
              }
            }
            self.weidu = o
            self.biCustom.weidu = self.weiduSelect
            self.conditionClick(['DIM_DATE_DAY'])
            self.condition = self.weiduSelect
          } else {
            self.$utils.msg(self, response.errMessage)
          }
        })
        .catch(function(error) {
          self.$utils.msg(self, error.errMessage)
        })
    },
    changeDateTree(arr) {
      var map = {},
        dest = []
      for (var i = 0; i < arr.length; i++) {
        var ai = arr[i]
        ai.children = [{}]
        ai.topicCateName = ai.topicCateName ? ai.topicCateName : '其它'
        if (!map[ai.topicCateName]) {
          dest.push({
            queryName: ai.topicCateName,
            hasChild: 'level0',
            children: [ai]
          })
          map[ai.topicCateName] = ai
        } else {
          for (var j = 0; j < dest.length; j++) {
            var dj = dest[j]
            if (dj.queryName == ai.topicCateName) {
              dj.children.push(ai)
              break
            }
          }
        }
      }
      let otherValue = dest.find(ev => ev.queryName == '其它')
      if (otherValue) {
        let otheri = dest.findIndex(res => res.queryName == '其它')
        dest.splice(otheri, 1)
        dest.push(otherValue)
      }
      
      return dest
    },
    conditionClick(arr, type) {
      let _this = this
      this.$api({
        url: '/ts-bi/api/bi/BiReportTarget/queryTargetIntersectionByDimensions',
        method: 'post',
        data: {
          dimensions: JSON.stringify(arr)
        }
      })
        .then(function(response) {
          if (response.success) {
            for (let v of response.object) {
              v.selected = 1
              v._name = v.targetName
              v._id = v.id
              if (type != 'change') {
                //维度框改变，指标框跟着改变
                for (let item of _this.target) {
                  if (item._id == v._id) {
                    v.selected = 2
                    break
                  }
                }
              }
            }
            _this.norm = response.object
            if (type == 'change') {
              //维度框改变，指标框跟着改变
              _this.normchange([])
            }
          } else {
            _this.$utils.msg(_this, response.errMessage, 'error')
          }
        })
        .catch(function(error) {
          _this.$utils.msg(_this, error.errMessage, 'error')
        })
    },
    weiduOpen() {
      this.weidu_o = this.weidu_o === 2 ? 1 : 2
      this.$refs.weiduSelect.open(this.weidu_o)
    },
    weiduchange(o) {
      let arr = []
      this.weiduSelect = o
      this.condition = o
      o.forEach((v, i) => {
        arr.push(v.dimensionName)
      })
      this.conditionClick(arr, 'change')
      this.weidu_o = 1
      this.biCustom.weidu = this.weiduSelect
    },
    normOpen() {
      this.norm_o = this.norm_o === 2 ? 1 : 2
      this.$refs.normSelect.open(this.norm_o)
    },
    normchange(o) {
      this.norm_o = 1
      this.target = o
      this.biCustom.norm = o
    },
    normAacFn(i) {
      this.norm_acv = i
    }
  },
  watch: {
    // dataSourceTree: {
    //   handler() {
    //     console.log('222222')
    //   },
    //   deep: true
    // },
    biCustom: {
      handler(val) {
        this.$eventBus.$emit('biCustomChange', { target: this.biCustom })
      },
      deep: true
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .vxe-table {
  font-size: 12px;
}
.userDefined-weiduNorm {
  .tab-content {
    height: calc(100% - 30px);
    .center {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .third_mapping_tree {
      height: calc(100% - 30px);
      width: 100%;
      overflow-x: auto;
      overflow-y: auto;
      .form__box {
        height: calc(100% - 6px);
      }
      .tree__text {
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      /deep/.vxe-table--body,
      /deep/.c--tooltip {
        width: 100% !important;
      }
    }
  }
  .leftH50 {
    height: 50%;
  }
  .biUserDefinedForm-add__listT {
    padding: 5px 10px;
    font-size: 12px;
  }
  border-right: 1px solid var(--border_color);
  .search-tree {
    > div {
      margin: 5px 10px 0 10px;
    }
    .form__box {
      margin-bottom: 0px;
    }
    .vxe-input--inner {
      border-radius: 15px !important;
    }
  }
  .biUserDefinedForm-add__slist {
    font-size: 12px;
    height: 30px;
    line-height: 30px;
    padding: 0 10px 0 20px;
    span {
      cursor: move;
    }
  }

  .biUserDefinedForm-add__slist:hover {
    background-color: #f1f1f1;
  }

  .biUserDefinedForm-add__title {
    height: 30px;
    line-height: 30px;
    overflow: hidden;
    border-bottom: 1px solid var(--border_color);
    padding: 0 5px;
    background: #f0f7ff;
    font-size: 13px;
    span {
      cursor: pointer;
      padding: 0 5px;
      margin: 0 5px;
    }
    span:hover {
      color: var(--base-acv);
    }
    .active {
      color: var(--base-acv);
      font-weight: bold;
    }
  }
}
</style>
