<template>
  <div class="height100 situation-contanier" style="width:100%">
    <ts-title-panel
      :title="config.targetName||item.targetName||'-'"
      class="situation-contanier_div"
      :data="config"
      :titleStructure="config.titleStructure"
      :backgroundColor="config.panelBackgroundColor||'transparent'"
      :titleBackgroundColor="item.titleBackgroundColor||'transparent'"
      :groundColor="item.groundColor||'transparent'"
      :isBorder="false"
    >
      <div slot="titleSlot" class="title-right" v-if="!loading">
        <biTagsTreeItem
          :item="item"
           :formId="formId"
           :params="params"
          :config="config"
          :isMainItem="true"
          itemBackground
          :isEditable="isEditable"
        ></biTagsTreeItem>
      </div>
      <tsLoading :loading="loading" />
      <div class="situation-contanier_bottom" v-if="!loading">
        <biTagsTreeItem
          :item="treeItem"
          :config="config"
          :params="params"
          :formId="formId"
          v-for="(treeItem,index) of treeDatas"
          :key="index"
          :showName="true"
          :isEditable="isEditable"
          :itemBackground="config.itemBackground1"
        >
 
        </biTagsTreeItem>
      </div>
    </ts-title-panel>
    <!-- <p v-if="dataList&&dataList.length==0" class="no_data">--暂无数据--</p> -->
  </div>
</template>

<script>
import biTagsTreeItem from './biTagsTreeItem.vue'
import biTargetInfo from '../../components/uiElement/biTargetInfo.vue'
import biUtils from '../../utils/biUtils'
import previewRealDate from '../../utils/dateUtils'
export default {
  name: 'biTagsTree',
  components: {
    biTargetInfo,
    biTagsTreeItem
  },
  props: {
    dataList: {
      type: Array,
      default: () => {
        return []
      }
    },
    isEditable: {
      // 是否编辑
      type: Boolean,
      default: false
    },
    chartType: {
      type: Number,
      default: 2
    },
    point: {
      type: Boolean,
      default: true
    },
    config: {
      // 属性内容
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      formId: '',
      clickFirst: true,
      url: '/ts-bi/api/v3/busi/list/statistic',
      eventSource: null,
      params: {}, // 参数
      item: this.isEditable
        ? {
            targetId: '000000',
            targetName: '指标名称',
            thisVal: '2419.83',
            sameRate: '-52',
            sameVal: '6672.69',
            chainRate: '21',
            chainVal: '0'
          }
        : this.dataList && this.dataList.length > 0
        ? this.dataList[0]
        : {},
      notRealDatas: [
        {
          targetId: '000000',
          targetName: '指标名称1',
          thisVal: '2419.83',
          sameRate: '-52',
          sameVal: '6672.69',
          chainRate: '21',
          chainVal: '0',
          children: [
            {
              targetId: '000000',
              targetName: '指标名称1.1',
              thisVal: '2419.83',
              sameRate: '-52',
              sameVal: '6672.69',
              chainRate: '21',
              chainVal: '0'
            },
            {
              targetId: '000000',
              targetName: '指标名称1.2',
              thisVal: '2419.83',
              sameRate: '-52',
              sameVal: '6672.69',
              chainRate: '21',
              chainVal: '0'
            }
          ]
        },
        {
          targetId: '000000',
          targetName: '指标名称2',
          thisVal: '2419.83',
          sameRate: '-52',
          sameVal: '6672.69',
          chainRate: '21',
          chainVal: '0',
          children: [
            {
              targetId: '000000',
              targetName: '指标名称2.1',
              thisVal: '2419.83',
              sameRate: '-52',
              sameVal: '6672.69',
              chainRate: '21',
              chainVal: '0',
              children: [
                {
                  targetId: '000000',
                  targetName: '指标名称2.1.1',
                  thisVal: '2419.83',
                  sameRate: '-52',
                  sameVal: '6672.69',
                  chainRate: '21',
                  chainVal: '0'
                }
              ]
            }
          ]
        }
      ], //模拟数据
      treeDatas: [],
      chartData: [{ column: '门急诊人次', category: '科室', value: 4232 }],
      target: {},
      tableSource: this.sourceFn(),
      loading: false
    }
  },
  created() {
    if (this.config.targetTreeDatas && this.config.targetTreeDatas.length > 0) {
      this.treeDatas = [...this.config.targetTreeDatas]
    } else {
      this.treeDatas = this.isEditable ? [...this.notRealDatas] : []
    }
  },
  mounted() {
   this.formId = this.$parent.formId
    if (!this.isEditable) {
      this.$eventBus.$on(
        'refreshBiTarget' +
          (this.config ? this.config.id : '') +
          this.$parent.formId +
          this.isEditable,
        this.getDatas
      ) // 为方便进行筛选器联动
    } else {
      if (
        this.config.targetTreeDatas &&
        this.config.targetTreeDatas.length > 0
      ) {
        this.getTargetTreeRealData(this.treeDatas)
      }
    }
    if (!this.config.filterId && !this.config.filterData) {
      this.getDatas({}) // 为防止重复调用，有筛选器的，只能通过eventBus才能调用到数据
    }
  },
  methods: {
    // 获取模拟数据
    getTargetTreeRealData(list, tree) {
      for (let item of list) {
        if (item.children && item.children.length > 1) {
          this.getTargetTreeRealData(item.children, tree)
        }
        if (tree) {
          if (tree.targetId == item.code) {
            item = { ...Object.assign(item, { ...tree }) }
            break
          }
        } else {
          item = Object.assign(item, {
            targetId: item.code,
            targetName: item.name
              ? item.name.replace('(' + item.code + ')', '')
              : ''
          })
        }
      }
    },
    getInfo(item) {
      this.target = item
    },
    // 打开指标详情
    onTargetInfo(row, key) {
      row.params = {...this.params}
      row.params.busiCode = this.config.targetCode
      this.$eventBus.$emit(
        'openTargetItemDialog' + this.$parent.formId,
        row,
        key
      )
    },
    // 获取数据项
    getDatas(params) {
      const _this = this
      if (this.isEditable || (!params.targetCode && !this.config.targetCode)) {
        // 未选中指标
        return
      }
      _this.item = {}
      this.params = Object.assign(this.params, params)
      this.params.busiCode = this.config.treeTargetCode
        ? [this.params.targetCode || this.config.targetCode]
            .concat(this.config.treeTargetCode.split(','))
            .join(',')
        : this.params.targetCode || this.config.targetCode
      // 模拟日期
      this.params.beginDate =
        this.params.beginDate || previewRealDate.getRealDate('y').startDate
      this.params.endDate = this.params.endDate || this.$utils.getTodayDate()
      this.params.hideChartData =
        this.params.hideChartData || this.config.hideChartData || false
      if (this.config.isRealTime) {
        this.openRealTimeUrl()
      } else {
        this.loading = true
        this.$api({
          method: 'post',
          url: this.url,
          data: this.params,
          headers: {
            'Content-Type': 'application/json; charset=utf-8'
          }
        })
          .then(function(resp) {
            if (resp.success) {
              _this.doResponse(resp)
            } else {
              _this.$utils.msg(_this, resp.message, 'error')
            }
            _this.loading = false
          })
          .catch(function(error) {
            _this.loading = false
            _this.$utils.msg(_this, error.message || '系统异常', 'error')
          })
      }
    },
    // 打开实时功能
    openRealTimeUrl() {
      const _this = this
      if (typeof EventSource !== 'undefined') {
        this.eventSource = new EventSource(
          biUtils.objArgs(this.params, this.url, null)
        )
        this.eventSource.onmessage = function(event) {
          if (event.data) {
            try {
              _this.doResponse(JSON.parse(event.data))
            } catch (error) {
              console.warn(error)
              _this.$utils.msg(
                _this,
                error.message || '返回格式存在问题，请联系管理员',
                'error'
              )
            }
          }
        }
      } else {
        _this.$utils.msg(_this, '该浏览器不支持SSE,请升级浏览器版本', 'warning')
      }
    },
    // 处理响应内容
    doResponse(resp) {
      const _this = this
      let respList = resp.object || []
      if (resp.success && respList.length > 0) {
        _this.item = { ...respList[0] }
        _this.item.targetId_ = _this.config.targetId
        _this.item.targetName = _this.config.targetName
        _this.item.thisVal = biUtils.splitNum(
          _this.item.thisVal,
          _this.item.dataOf
        )
        if (
          this.config.treeTargetCode &&
          this.config.treeTargetCode.length > 0
        ) {
          respList.splice(0, 1)
          for (let tree of respList) {
            this.getTargetTreeRealData(this.treeDatas, tree)
          }
        }
      } else {
        _this.$utils.msg(_this, resp.message, 'error')
      }
    },
    // 列表配置
    sourceFn() {
      let self = this
      return {
        showOverflow: true,
        offPage: false,
        rownumbers: false,
        dataType: 'local',
        colModel: this.colFn(),
        offPage: true
      }
    },
    colFn() {
      let self = this
      return [
        {
          title: '月份',
          field: 'category',
          align: 'center',
          width: 60,
          formatter: function({ cellValue, row, column }) {
            return cellValue
          }
        },
        {
          title: '本期',
          field: 'thisVal',
          align: 'right',
          helpDetail: '当前月份',
          formatter: function({ cellValue, row, column }) {
            return biUtils.splitNum(cellValue, self.item.dataOf)
          }
        },
        {
          title: '同期',
          field: 'sameVal',
          align: 'right',
          helpDetail: '去年同月份',
          formatter: function({ cellValue, row, column }) {
            return biUtils.splitNum(cellValue, self.item.dataOf)
          }
        }
      ]
    }
  },
  watch: {
    'config.viewType': {
      handler(n) {
        this.$nextTick(() => {
          this.getDatas({})
        })
      }
    },
    config: {
      handler(n) {
        this.config = n
      },
      deep: true
    },
    'config.targetTreeDatas': {
      handler(n) {
        if (this.isEditable) {
          if (
            this.config.targetTreeDatas &&
            this.config.targetTreeDatas.length > 0
          ) {
            this.treeDatas = [...this.config.targetTreeDatas]
            this.getTargetTreeRealData(this.treeDatas)
          } else {
            this.treeDatas = [...this.notRealDatas]
          }
        }
      },
      deep: true
    }
  },
  beforeDestroy: function() {
    this.eventSource ? this.eventSource.close() : ''
    this.$eventBus.$off(
      'refreshBiTarget' +
        (this.config ? this.config.id : '') +
        this.$parent.formId +
        this.isEditable,
      this.getDatas
    ) // 为方便进行筛选器联动
  }
}
</script>
<style lang="scss" scoped>
/deep/.green {
    color: #2BCB95 !important;
    background: none !important;
    font-size: 14px;
}
.red {
    color: #FB3A77;
}
/deep/.red2 {
   font-size: 14px;
    color: #FF6B3B !important;
}

.situation-contanier:hover {
  /deep/.item_operate {
    display: block;
  }
}
.title-right {
  margin-left: auto;
  width: 70%;
  display: flex;
  .bi-target-item-con {
    position: relative;
    display: flex;
    margin-left: auto;
  }
}
.situation-contanier_div {
  width: 100%;
  flex-wrap: wrap;
  /deep/.form-title {
    display: flex;
    font-size: 16px;
    line-height: 16px;
  }
  /deep/.panel-content {
    height: calc(100% - 36px) !important;
    overflow-y: hidden !important;
  }
  .no_data {
    width: 100%;
  }
  /deep/.table-loading {
    height: calc(100% - 40px);
    margin-top: 40px;
  }

  /deep/.bi-target-item-con {
    position: relative;
    .situation-contanier_center {
      align-items: center;
      display: flex;

      width: auto;
      margin: 0 5px;
      height: 34px;
      .title {
        font-size: 16px;
        color: #e6a23c;
        margin-left: auto;
      }
      .rate-div {
        background: #ffffff;
        padding: 3px;
        min-width: 130px;
      }
      .target-info {
        cursor: pointer;
        &:hover {
          text-decoration: underline;
        }
      }
      .value {
        color: black;
        width: 40px;
        text-align: end;
        // justify-content: flex-end;
        // display: flex;
      }
      .center {
        display: flex;
        align-items: center;
        line-height: 14px;
        // justify-content: center;
        span {
          padding: 0 5px;
        }
      }
    }
    .not-main-item {
      margin: 5px 8px;
      .target-name,
      .title {
        font-size: 14px !important;
        // color: #ffffff !important;
        line-height: 1 !important;
        border-radius: 2px;
        padding: 8px;
      }
    }
  }

  .situation-contanier_bottom {
    height: calc(100% - 70px);
    width: 100%;
  }
}
</style>
