<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">
        <div
          class="item_operate"
          v-if="!config.hideInfo&&!isEditable&&$parent.formId&&item.targetId&&!$parent.isFromList"
        >
          <el-popover
            placement="bottom-start"
            :title="target.targetName||'指标名称'"
            width="300"
            trigger="hover"
          >
            <bi-targetInfo :target="target" v-if="target&&target.targetId"></bi-targetInfo>
            <span
              @mouseenter="getInfo(item,'info')"
              slot="reference"
              class="item_ball iconfont icon-tishi2"
            ></span>
          </el-popover>
          <span
            @click="onTargetInfo(item,'infoTable')"
            title="详情"
            class="item_ball iconfont icon-Group-24"
          ></span>
        </div>
      </div>
      <tsLoading :loading="loading" />
      <div class="situation-contanier_center" v-if="!loading">
        <div class="flexbox" style="align-items: center;width:calc(100% - 130px)">
          <span
            class="title ellipsis hidden"
            :style="{width:'100%',fontSize:(config.textSize||'25')+'px',color:config.textColor||'var(--base-acv)',lineHeight:(config.textSize||'25')+'px'}"
            :title="item.thisVal||'-'"
          >
            {{item.thisVal||'-'}}
            <span class="font13 co999 mrgl5">{{item.targetUnit}}</span>
          </span>
          <!-- <div v-if="(item.thisVal||'-').indexOf('万')>-1" class="font13 co999 mrgl5">万</div> -->
        </div>
        <div class="font12" style="margin-left: auto;">
          <div class="center">
            <span class="co999">同比</span>
            <span v-if="item.sameRate&&item.sameRate.indexOf('-')==0" class="green">▼</span>
            <span
              v-else-if="item.sameRate&&item.sameRate.indexOf('-')!=0&&item.sameRate!='0'&&item.sameRate!='0.00'"
              class="red2"
            >▲</span>
            <div v-else style="width:20px"></div>
            <span class="value">{{item.sameRate||'-'}}%</span>
          </div>
          <div class="center">
            <span class="co999">环比</span>
            <span v-if="item.chainRate&&item.chainRate.indexOf('-')==0" class="green">▼</span>
            <span
              v-else-if="item.chainRate&&item.chainRate.indexOf('-')!=0&&item.chainRate!='0'&&item.chainRate!='0.00'"
              class="red2"
            >▲</span>
            <div v-else style="width:20px"></div>
            <span class="value">{{item.chainRate||'-'}}%</span>
          </div>
        </div>
      </div>
      <div class="situation-contanier_bottom" v-if="!loading&&!config.hideChartData">
        <template v-if="config.viewType=='chart'">
          <ts-g2-plot
            v-if="config.cate == 'plot'"
            :chartType="config.chartId"
            :point="config.point"
            :data="item.chartData"
            :themeCode="config.themeCode"
            :isShowValue="config.isShowValue"
            :legendPos="config.legendPos"
            :smooth="config.smooth"
            :position="config.position"
            :isSlider="config.isSlider"
            width="100%"
          ></ts-g2-plot>
          <ts-g2-chart
            v-else
            :chartType="config.chartId"
            :data="item.chartData"
            :point="config.point"
            height="100%"
            :timeout="300"
            :maxNumber="8000"
            ref="tsChart"
            :smooth="config.smooth"
            :isSlider="config.isSlider"
          ></ts-g2-chart>
        </template>
        <ts-table
          v-if="config.viewType == 'table'"
          :source="tableSource"
          width="100%"
          height="100%"
          ref="tsTable"
          :isHideFunc="true"
        ></ts-table>
      </div>
    </ts-title-panel>
    <!-- <p v-if="dataList&&dataList.length==0" class="no_data">--暂无数据--</p> -->
  </div>
</template>

<script>
import biTargetInfo from '../../components/uiElement/biTargetInfo.vue'
import biUtils from '../../utils/biUtils'
import previewRealDate from '../../utils/dateUtils'
export default {
  name: 'biTarget',
  components: { biTargetInfo },
  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 {
      clickFirst: true,
      url: '/ts-bi/api/v3/busi/statistic',
      eventSource: null,
      params: {}, // 参数
      item: this.isEditable
        ? {
            targetId: '000000',
            targetName: '指标名称',
            thisVal: '2419.83',
            sameRate: '-52',
            sameVal: '6672.69',
            chainRate: '21',
            chainVal: '0',
            chartData: [
              { category: '01月', column: '2021', value: '249.83' },
              { category: '02月', column: '2021', value: '1569.12' },
              { category: '03月', column: '2021', value: '4439.81' },
              { category: '04月', column: '2021', value: '6231.12' },
              { category: '05月', column: '2021', value: '6769.12' },
              { category: '06月', column: '2021', value: '939.12' },
              { category: '07月', column: '2021', value: '249.83' },
              { category: '08月', column: '2021', value: '1569.12' },
              { category: '09月', column: '2021', value: '4769.81' },
              { category: '10月', column: '2021', value: '4631.12' },
              { category: '11月', column: '2021', value: '6769.12' },
              { category: '12月', column: '2021', value: '6769.12' },
              { category: '01月', column: '2020', value: '769.12' },
              { category: '02月', column: '2020', value: '8900.51' },
              { category: '03月', column: '2020', value: '4898.45' },
              { category: '04月', column: '2020', value: '5168.92' },
              { category: '05月', column: '2020', value: '6475.68' },
              { category: '06月', column: '2020', value: '6672.69' },
              { category: '07月', column: '2020', value: '769.12' },
              { category: '08月', column: '2020', value: '1900.51' },
              { category: '09月', column: '2020', value: '8898.45' },
              { category: '10月', column: '2020', value: '3168.92' },
              { category: '11月', column: '2020', value: '5475.68' },
              { category: '12月', column: '2020', value: '4672.69' }
            ]
          }
        : this.dataList && this.dataList.length > 0
        ? this.dataList[0]
        : {},
      chartData: [{ column: '门急诊人次', category: '科室', value: 4232 }],
      target: {},
      tableSource: this.sourceFn(),
      loading: false
    }
  },
  created() {},
  mounted() {
    if (!this.isEditable) {
      this.$eventBus.$on(
        'refreshBiTarget' +
          (this.config ? this.config.id : '') +
          this.$parent.formId +
          this.isEditable,
        this.getDatas
      ) // 为方便进行筛选器联动
    }
    if (!this.config.filterId && !this.config.filterData) {
      this.getDatas({}) // 为防止重复调用，有筛选器的，只能通过eventBus才能调用到数据
    }
  },
  methods: {
    getInfo(item) {
      this.target = item
    },
    // 打开指标详情
    onTargetInfo(row, key) {
      row.params = this.params
      this.$eventBus.$emit(
        'openTargetItemDialog' + this.$parent.formId,
        row,
        key
      )
    },
    // 获取数据项
    getDatas(params) {
      const _this = this
      if (this.isEditable || (!params.targetCode && !this.config.targetCode)) {
        // 未选中指标
        return
      }
      if (this.isEditable && _this.config.viewType == 'table') {
        // 为表格
        _this.$refs.tsTable.data = biUtils.changeChart2TableData(
          _this.item.chartData
        )
        return
      }
      _this.item = {}
      this.params = Object.assign(this.params, params)
      this.params.busiCode = 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 (params.pivotType || this.config.pivotType) {
      //   params.pivotType = params.pivotType || this.config.pivotType
      // }
      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'
              )
            }
          }
        }
        // source.onerror = function(e) {
        //     _this.$utils.msg(_this, '请求参数过长，请检查参数', 'warning')
        //     source.close();
        //     source = null
        // };
      } else {
        _this.$utils.msg(_this, '该浏览器不支持SSE,请升级浏览器版本', 'warning')
      }
    },
    // 处理响应内容
    doResponse(resp) {
      const _this = this
      if (resp.success) {
        _this.item = { ...resp.object }
        _this.item.targetId_ = _this.config.targetId
        _this.item.thisVal = biUtils.splitNum(
          _this.item.thisVal,
          _this.item.dataOf
        )
        if (_this.config.viewType == 'table') {
          // 为表格
          _this.$refs.tsTable.data = biUtils.changeChart2TableData(
            _this.item.chartData
          )
        }
      } 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
    }
  },
  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="less" scoped>
.situation-contanier:hover {
  /deep/.item_operate {
    display: block;
  }
}

.situation-contanier_div {
  width: 100%;
  flex-wrap: wrap;
  /deep/.form-title {
    display: flex;
  }
  /deep/.panel-content {
    overflow-y: hidden !important;
  }
  .no_data {
    width: 100%;
  }
  /deep/.table-loading {
    height: calc(100% - 40px);
    margin-top: 40px;
  }

  .item_operate {
    position: absolute;
    top: 8px;
    right: 3px;
    display: none;
    z-index: 4;
    .item_ball {
      padding: 3px;
      margin-right: 3px;
      border-radius: 25px;
      background: #c7defe;
      color: #ffffff;
      // border: 1px solid var(--base-black);
      cursor: pointer;
      font-weight: bold;
      &:hover {
        background: var(--button_color);
      }
    }
  }
  .situation-contanier_center {
    align-items: center;
    display: flex;
    width: calc(100% - 30px);
    margin: 0 15px;
    height: 54px;
    line-height: 20px;
    .title {
      font-size: 25px;
      color: #e6a23c;
    }

    .target-info {
      cursor: pointer;
      &:hover {
        text-decoration: underline;
      }
    }
    .value {
      color: black;
      width: 50px;
      justify-content: flex-end;
      display: flex;
    }
  }
  .situation-contanier_bottom {
    height: calc(100% - 64px);
    width: 100%;
  }
  .center {
    display: flex;
    align-items: center;
    // justify-content: center;
    span {
      padding: 0 5px;
    }
  }
}
</style>
