<template>
  <div class="statstics-wrapper">
    <div
      ref="headerWrapper"
      class="statstics-header"
    >
      <StatisticsHeader
        title="扫描节点与位置分析"
        :items="formItems"
        :data="formData"
        button-text="开始分析"
        @getFormData="getFormData"
      />
    </div>
    <div class="statstics-content">
      <div
        id="chart"
        class="node-statistics-chart"
        :style="{ height: chartHeight }"
      />
      <div
        v-if="tooltips.length"
        class="node-tooltip"
      >
        <div class="node-tooltip-title">节点扫描率</div>
        <div
          v-for="tooltip in tooltips"
          :key="tooltip.label"
          class="node-tooltip-content"
        ><span>{{ tooltip.label }}：</span><span>{{ tooltip.ratio }}</span></div>
      </div>
    </div>
  </div>
</template>

<script>
import StatisticsHeader from '../components/statisticsHeader.vue'
import { Query } from '@/api/dataIntegration'
import { mapGetters } from 'vuex'
export default {
  name: 'FlightStatisticsCharts',
  components: { StatisticsHeader },
  data() {
    const that = this
    return {
      formData: {
        range: '',
        airline: '',
        airport: '',
        inOrOut: '',
        dateTime: ''
      },
      formItems: [
        {
          prop: 'range',
          inputType: 'select',
          placeholder: '请选择统计范围',
          options: [],
          queryId: DATACONTENT_ID.nodeRangeId,
          setKey: 'a1',
          changeHandler(value) {
            this.formData.airline = ''
            this.formData.airport = ''
            this.formData.inOrOut = ''
            that.setInOrOutOptions(value)
            this.formItems[1].disabled = true
            this.formItems[2].disabled = true
            switch (value) {
              case '航线':
                this.formItems[1].disabled = false
                break
              case '航站':
                this.formItems[2].disabled = false
                break
              default:
                break
            }
          }
        },
        {
          prop: 'airline',
          inputType: 'select',
          placeholder: '航线选择',
          filterable: true,
          clearable: true,
          disabled: true,
          queryId: DATACONTENT_ID.nodeAirlineId,
          setKey: 'a2',
          options: []
        },
        {
          prop: 'airport',
          inputType: 'select',
          placeholder: '航站选择',
          filterable: true,
          clearable: true,
          // multiple: true,
          disabled: true,
          queryId: DATACONTENT_ID.nodeAirportId,
          setKey: 'a2',
          options: []
        },
        {
          prop: 'inOrOut',
          inputType: 'select',
          placeholder: '请选择进离港',
          clearable: true,
          options: []
        },
        {
          prop: 'dateTime',
          inputType: 'datePicker',
          clearable: true,
          width: '240px',
          options: []
        }
      ],
      myChart: null,
      debounceTime: 300,
      chartHeight: '70vh',
      options: {
        // legend: {
        //   top: 32,
        //   right: 32,
        //   height: 14,
        //   itemWidth: 14,
        //   itemHeight: 14,
        //   icon: 'rect',
        //   textStyle: {
        //     fontSize: 14
        //   },
        //   data: ['离港', '进港']
        // },
        tooltip: {
          trigger: 'item'
        },
        label: {
          show: true,
          formatter: function (params) {
            return params.value
          }
        },
        radar: {
          indicator: [
            {
              name: '行李总件数',
              max: 10000
            },
            {
              name: '值机件数',
              max: 10000
            },
            {
              name: '安检件数',
              max: 10000
            },
            {
              name: '分拣件数',
              max: 10000
            },
            {
              name: '装车件数',
              max: 10000
            },
            {
              name: '装机件数',
              max: 10000
            },
            {
              name: '卸机件数',
              max: 10000
            },
            {
              name: '到达件数',
              max: 10000
            }
          ],
          axisName: {
            padding: 10,
            color: '#303133',
            fontFamily: 'Helvetica, "Microsoft YaHei"'
          }
        },
        series: [
          {
            name: 'nodeRadar',
            type: 'radar',
            areaStyle: {
              color: '#6897D8'
            },
            itemStyle: {
              color: '#ffffff',
              borderWidth: 2,
              borderColor: '#4475B8'
            },
            lineStyle: {
              color: '#4475B8',
              width: 2
            },
            data: []
          }
        ]
      },
      tooltips: [
        {
          label: '值机',
          ratio: '0%'
        },
        {
          label: '安检',
          ratio: '0%'
        },
        {
          label: '分拣',
          ratio: '0%'
        },
        {
          label: '装车',
          ratio: '0%'
        },
        {
          label: '装机',
          ratio: '0%'
        },
        {
          label: '卸机',
          ratio: '0%'
        },
        {
          label: '到达',
          ratio: '0%'
        }
      ]
    }
  },
  computed: {
    ...mapGetters(['sidebar'])
  },
  watch: {
    // 监听数据变化 重绘图形
    options: {
      handler(obj) {
        this.myChart.setOption(obj)
        this.resizeHandler()
      },
      deep: true
    },
    'sidebar.expand'() {
      this.resizeHandler()
    }
  },
  mounted() {
    this.setChartHeight()
    this.myChart = this.$echarts.init(document.getElementById('chart'))
    this.myChart.setOption(this.options)
    // 监听页面缩放
    window.addEventListener('resize', this.setChartHeight)
    window.addEventListener('resize', this._.debounce(this.resizeHandler, this.debounceTime))
    this.$nextTick(() => {
      this.resizeHandler()
    })
  },
  beforeDestroy() {
    // 销毁实例和移除监听
    window.removeEventListener('resize', this.setChartHeight)
    if (this.myChart) {
      this.myChart.dispose()
      window.removeEventListener('resize', this.resizeHandler)
      this.myChart = null
    }
  },
  methods: {
    getFormData(data) {
      this.getData(data)
    },
    setInOrOutOptions(range) {
      const theInOrOutItem = this.formItems.find(item => item.prop === 'inOrOut')
      switch (range) {
        case '全部':
        case '航线':
          theInOrOutItem.options = [
            {
              label: '全部',
              value: '全部'
            }
          ]
          this.formData.inOrOut = '全部'
          this.formItems[3].disabled = true
          break
        case '航站':
          theInOrOutItem.options = [
            {
              value: '进港',
              label: '进港'
            },
            {
              value: '离港',
              label: '离港'
            }
          ]
          this.formItems[3].disabled = false
          break
        default:
          theInOrOutItem.options = []
          this.formItems[3].disabled = false
          break
      }
    },
    async getData(data) {
      const params = []
      let queryId
      if (data.range === '') {
        this.$message.warning('请先选择统计范围')
        return
      }
      if (data.range === '航线' && data.airline === '') {
        this.$message.warning('请先选择航线')
        return
      }
      if (data.range === '航站' && data.airport === '') {
        this.$message.warning('请先选择航站')
        return
      }
      switch (data.inOrOut) {
        case '全部':
          queryId = DATACONTENT_ID.nodeAllId
          break
        case '进港':
          queryId = DATACONTENT_ID.nodeInId
          break
        case '离港':
          queryId = DATACONTENT_ID.nodeOutId
          break
        default:
          this.$message.warning('请先选择统计时间范围')
          return
      }
      if (data.dateTime === '') {
        this.$message.warning('请先选择统计时间范围')
        return
      }
      params.push(data.range, data.inOrOut, data.dateTime[0], data.dateTime[1])
      if (data.range === '航线') {
        params.splice(1, 0, data.airline)
      } else if (data.range === '航站') {
        params.splice(1, 0, data.airport)
      } else {
        params.splice(1, 0, '全部')
      }
      try {
        const res = await Query({
          id: queryId,
          dataContent: params
        })
        if (Number(res.code) === 0) {
          if (!res.returnData.listValues.length) {
            this.options.series[0].data = []
            this.tooltips.forEach(tooltip => (tooltip.ratio = '0%'))
            return
          }
          const labels = Object.keys(res.returnData.listValues[0])
          const datas = Object.values(res.returnData.listValues[0])
          const max = Math.max(...datas)
          this.options.radar.indicator = labels.map(label => {
            return {
              name: label,
              max
            }
          })
          this.options.series[0].data = [
            {
              value: datas,
              name: data.inOrOut
            }
          ]
          this.tooltips = labels.reduce((pre, curr, index) => {
            if (!curr.includes('总')) {
              return [
                ...pre,
                {
                  label: curr.slice(0, 2),
                  ratio: (datas[index] / max * 100).toFixed(2) + '%'
                }
              ]
            } else {
              return pre
            }
          }, [])
          // .map((label, index) => ({
          //   label: label.replace('件数', ''),
          //   ratio: (datas[index] / max).toFixed(2) * 100 + '%'
          // }))
          // .filter(element => !element.label.includes('总'))
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('出错了', error)
      }
    },
    setChartHeight() {
      const topBarHeight = 80
      const headerBlankHeight = 24
      const tabsWrapperHeight = 62
      const headerHeight = this.$refs['headerWrapper'].offsetHeight
      const footerBlankHeight = 24
      this.chartHeight = `calc(100vh - ${
        topBarHeight + headerBlankHeight + tabsWrapperHeight + headerHeight + footerBlankHeight
      }px)`
    },
    resizeHandler() {
      if (this.myChart) {
        this.myChart.resize()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.statstics-wrapper {
  .statstics-content {
    background-color: #fff;
    position: relative;
    .node-tooltip {
      width: 90px;
      position: absolute;
      bottom: 48px;
      left: 64px;
      z-index: 100;
      font-size: 14px;
      font-family: Helvetica, 'Microsoft YaHei';
      color: #303133;
      .node-tooltip-title {
        line-height: 14px;
        margin-bottom: 30px;
        font-weight: bold;
      }
      .node-tooltip-content {
        line-height: 14px;
        display: flex;
        justify-content: space-between;
        &:not(:last-child) {
          margin-bottom: 21px;
        }
      }
    }
    .node-statistics-chart {
      width: 100%;
    }
  }
}
</style>
