<template>
  <div class="height100 userDefined-left">
    <mTabs class="height100" :value="currentTab" @tagClick="tagClick">
      <mTabPane label="基础组件" :keys="1">
        <!-- 组件 -->
        <tsDragTree
          ref="comTree"
          :isTreeExpand="true"
          :treeData="componentTree"
          @dragstart="dragstart"
          @dragend="dragend"
        ></tsDragTree>
      </mTabPane>
      <mTabPane label="业务组件" :keys="4">
        <tsDragTree
          :emptyText="bsEmptyText"
          ref="businessComTree"
          :isTreeExpand="true"
          :treeData="businessComTree"
          @dragstart="dragstart"
          @dragend="dragend"
          rightIcon="iconfont icon-guihuasheji"
          @rightIconClick="rightIconClick"
        ></tsDragTree>
      </mTabPane>
      <mTabPane label="数据源" :keys="2">
        <tsDragTree
          :isTreeExpand="true"
          ref="dataSourceTree"
          dragType="target"
          :emptyText="dSEmptyText"
          :treeData="dataSourceTree"
          @dragstart="dragstart"
          @dragend="dragend"
          :isLoadMethod="true"
          @searchEvent="searchDSTree"
          :isSelfSearch="true"
          :isColumnSlot="true"
        >
          <template slot="columnSlot" slot-scope="props">
            <span
              class="tree__text"
              v-if="props.row.nodeType=='columnDefine'"
              @dragstart="dragstart($event,'target',props.row)"
              draggable="true"
            >{{ props.row.queryName }}</span>
            <span
              class="tree__text"
              v-else-if="(props.row.queryName=='字段'&& props.row.children[0].nodeType !='dataset') || props.row.nodeType=='dataset'"
              @dragstart="dragstart($event,'target',props.row)"
              draggable="true"
            >{{ props.row.queryName }}</span>
            <span class="tree__text" v-else>{{ props.row.queryName }}</span>
          </template>
        </tsDragTree>
      </mTabPane>
      <!-- 维度指标 -->
      <!-- <mTabPane label="维度" :keys="3">
        <div class="tab-content">
          <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>
      </mTabPane>-->
    </mTabs>
  
    <a class="iconleft view-change-icon" @click="leftViewChange()" v-if="isSmallBiLeftTree">
      <i class="iconfont icon-shousuo1 transition__all_3s"></i>
    </a>
      <a class="iconright view-change-icon" @click="leftViewChange()" v-else>
      <i style="color:var(--base-acv)" class="iconfont icon-shousuo2 transition__all_3s"></i>
    </a>
  </div>
</template>

<script>
import componentJson from './components.json'
import wSelect from './weiduSelect'
export default {
  components: { wSelect },
  props: {
    biCustom: {
      type: Object,
      default: function() {
        return {
          weidu: [],
          norm: [],
          c_norm: [],
          // currentTab: 'tab0',
          expandNode: {}
        }
      }
    }
  },
  data() {
    return {
      targetSourceTree: [],
      treeObjCom: {
        lazy: true,
        hasChild: 'hasChild',
        dataType: 'local',
        childName: 'children',
        iconOpen: 'iconfont icon-wenjianjia',
        iconClose: 'iconfont icon-wenjianjia1',
        iconNormal: 'iconfont icon-guanjianci'
      },
      componentTree: componentJson.componentTree,
      businessComTree: [], //componentJson.businessComTree,
      dSEmptyText: '--暂无数据--',
      bsEmptyText: '--暂无数据--',
      currentTab: 0,
      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: [],
      isSmallBiLeftTree: false, // 收起左边树
      // treeObj:
      condition: this.biCustom.weidu || [],
      target: this.biCustom.norm || [],
      weidu: [],
      weidu_o: 1,
      norm: [],
      norm_o: 1,
      norm_acv: 2,
      weiduSelect: [] // 维度
    }
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      // this.getThemeClassify()
      //获取指标树

      //获取数据源
      // this.getBiType()
      this.getTargetTreeList()
      this.getRoleTreeList() // 获取角色树
      this.getDataSourceTree('init')
      // this.initDimensionData()
      this.getBusinessCom()
      this.$eventBus.$on('getBusinessCom', this.getBusinessCom)
    })
  },
  methods: {
    // getBiType() {
    //   let _this = this
    //   this.$api({
    //     url: '/ts-system/api/dict/item/list/BI_BUSTYPE',
    //     data: {},
    //     method: 'get'
    //   })
    //     .then(res => {
    //       if (res.success && res.object) {
    //         _this.getTargetTree(res.object)
    //       } else {
    //         _this.getTargetTree([])
    //       }
    //     })
    //     .catch(err => {
    //       _this.getTargetTree()
    //     })
    // },
    // 角色树
    getRoleTreeList() {
      const _this = this
      let data = { pageSize: 2000 }
      this.$api({
        url: '/ts-system/api/role/tree',
        method: 'get',
        loading: false,
        data: JSON.stringify(data),
        timeout: 300000, // 指定请求超时的毫秒数
        loading: false
      })
        .then(function(response) {
          // 请求成功
          if (response.success) {
            _this.$store.commit('setRoleTreeList', [...response.object])
          } else {
            _this.$utils.msg(_this, response.message, 'error')
          }
        })
        .catch(function(error) {
          // 请求失败
          _this.$utils.msg(_this, error.message, 'error')
        })
    },
    getTargetTreeList() {
      const _this = this
      let data = { status: '01', pageSize: 2000 }
      this.$api({
        url: '/ts-bi/api/OfBusiCode/distinctCodeList',
        method: 'get',
        loading: false,
        data: JSON.stringify(data),
        timeout: 300000, // 指定请求超时的毫秒数
        loading: false
        // headers: {
        //   'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
        // }
      })
        .then(function(response) {
          // 请求成功
          if (response.success) {
            _this.targetSourceTree = [...response.object]
            _this.$store.commit('setTargetSource', _this.targetSourceTree)
          } else {
            _this.$utils.msg(_this, response.message, 'error')
          }
        })
        .catch(function(error) {
          // 请求失败
          _this.$utils.msg(_this, error.message, 'error')
        })
    },
    // 拖拽指标
    dragstart(ev, type, item) {
      this.$eventBus.$emit('dragstart', ev, type, item)
    },
    // 拖拽停止
    dragend(ev, type, item) {
      this.$eventBus.$emit('dragend', ev, type, item)
    },
    // 头部tab切换
    tagClick(tabId) {
      this.leftViewChange(false)
      this.biCustom.currentTab = tabId
    },
    rightIconClick(row) {
      row.bTitle = row.title
      this.$eventBus.$emit('openDesignDialog', row)
    },
    // // 展开节点
    // toggleExpandChangeEvent({ row, expanded }) {

    //   // 根节点
    //   if (row.hasChild == 'level1') {
    //     this.$nextTick(() => {
    //       this.biCustom.expandNode = JSON.parse(JSON.stringify(row))
    //     })
    //   }
    // },
    getThemeClassify() {
      const _this = this
      this.$api({
        url: '/ts-system/api/dict/item/list/PLAT_USER_SERVICE_TOPIC_CATEGORY',
        method: 'get',
        loading: false,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
        }
      })
        .then(function(response) {
          // 请求成功
          if (response.object) {
            for (let item of response.object) {
              _this.dataSourceTree.push({
                queryName: item.itemName,
                hasChild: 'level1',
                children: [{}]
              })
            }
            // _this.dataSourceTree = _this.changeDateTree(_this.dataSourceTree)
          }
        })
        .catch(function(error) {})
    },
    // 左侧树的选中回调
    onTreeSelectRow(o) {},
    // 数据源树搜索框
    searchDSTree(val) {
      this.keywords = val
      this.getDataSourceTree()
    },
    // 获取数据源数据
    getDataSourceTree(val) {
      let _this = this
      _this.dSEmptyText = '数据加载中...'
      let data = { condition: this.keywords, pageSize: 2000 }
      this.$api({
        url: '/ts-query/api/user/define/service/list',
        method: 'post',
        loading: false,
        data: JSON.stringify(data),
        timeout: 30000000, // 指定请求超时的毫秒数
        loading: false,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
        }
      })
        .then(function(response) {
          // 请求成功
          if (response.rows) {
            _this.dataSourceTree = []
            for (let row of response.rows) {
              row.hasChild = 'level1'
            }
            // 默认回显展开上次保存的节点
            // if (
            //   _this.biCustom.currentTab == 'tab1' &&
            //   Object.keys(_this.biCustom.expandNode).length > 0
            // ) {
            //   _this.$refs.dataSourceTree.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.dSEmptyText = '--暂无数据--'
          } else {
            _this.$utils.msg(_this, response.message, 'error')
          }
        })
        .catch(function(error) {
          // 请求失败
          _this.dSEmptyText = '--暂无数据--'
          _this.$utils.msg(_this, error.message, 'error')
        })
    },
    // 获取业务组件
    getBusinessCom() {
      let _this = this
      _this.bsEmptyText = '数据加载中...'
      let data = { appType: '3', pageSize: 2000 }
      this.$api({
        url: '/ts-bi/api/BiReportDesign/businessComTreeNode/list',
        method: 'get',
        loading: false,
        data: JSON.stringify(data),
        timeout: 300000, // 指定请求超时的毫秒数
        loading: false
      })
        .then(function(response) {
          _this.bsEmptyText = '--暂无数据--'
          // 请求成功
          if (response.object) {
            _this.businessComTree = [...response.object]
            _this.$nextTick(() => {
              _this.$refs.businessComTree
                ? _this.$refs.businessComTree.$refs.biTableTree.setAllTreeExpand(
                    true
                  )
                : ''
            })
          } else {
            _this.$utils.msg(_this, response.message, 'error')
          }
        })
        .catch(function(error) {
          // 请求失败
          _this.bsEmptyText = '--暂无数据--'
          _this.$utils.msg(_this, error.message, 'error')
        })
    },
    // 初始化
    initDimensionData() {
      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',
        loading: false,
        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)
        })
    },
    changeTargetTree(arr, typeList) {
      if (typeList && typeList.length > 0) {
        let allData = []
        typeList.forEach(res => {
          res.children = []
          res.name = res.itemName
          allData.push(res)
        })
        allData.forEach(res => {
          arr.forEach(e => {
            if (res.itemCode == e.busType.toLowerCase()) {
              res.children.push(e)
            }
          })
        })
        return allData
      } else {
        return arr
      }
    },
    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',
        loading: false,
        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
    },
    leftViewChange(type) {
      if(type==undefined){
        this.isSmallBiLeftTree = !this.isSmallBiLeftTree
        return
      }
      this.isSmallBiLeftTree = type
    }
  },
  watch: {
    isSmallBiLeftTree: {
      handler(type) {
        this.$emit('leftViewChange', type)
      }
    },
    // dataSourceTree: {
    //   handler() {
    //   },
    //   deep: true
    // },
    biCustom: {
      handler(val) {
        this.$eventBus.$emit('biCustomChange', { target: this.biCustom })
      },
      deep: true
    }
  },
  destroyed() {
    this.$eventBus.$off('refreshBusinessCom', this.getBusinessCom)
  }
}
</script>
<style lang="less" scoped>
/deep/ .vxe-table {
  font-size: 12px;
}
.iconleft{
  right: 0px;
  left: auto;
}
/deep/.m-tabs__header > li {
  margin: 0 10px;
}
.userDefined-left {
  position: relative;
  .tab-content {
    height: calc(100% - 30px);
  }
  .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>
