<template>
  <view class="InternetExtruder">
    <view class="mainBox-image">
      <view class="image-title">实时温度</view>
      <view class="image-list">
        <l-echart ref="chart"></l-echart>
        <!-- <qiun-data-charts type="gauge" :chartData="chartData" background="none" :opts="opts" /> -->
      </view>
    </view>
    <view>
      <uni-table border stripe emptyText="暂无更多数据">
        <!-- 表头行 -->
        <uni-tr>
          <uni-th align="center" width="200rpx"></uni-th>
          <uni-th align="center">油温（℃）</uni-th>
          <uni-th align="center">速度（mm/s）</uni-th>
          <uni-th align="center">压力 （Kg/cm²）</uni-th>
        </uni-tr>
        <!-- 表格数据行 -->
        <template v-if="tableData.length">
          <uni-tr>
            <uni-td>当日峰值</uni-td>
            <uni-td>{{ tableData[0].maxValue }}</uni-td>
            <uni-td>{{ tableData[1].maxValue }}</uni-td>
            <uni-td>{{ tableData[2].maxValue }}</uni-td>
          </uni-tr>
          <uni-tr>
            <uni-td>当日谷值</uni-td>
            <uni-td>{{ tableData[0].minValue }}</uni-td>
            <uni-td>{{ tableData[1].minValue }}</uni-td>
            <uni-td>{{ tableData[2].minValue }}</uni-td>
          </uni-tr>
          <uni-tr>
            <uni-td>当日均值</uni-td>
            <uni-td>{{ tableData[0].avgValue }}</uni-td>
            <uni-td>{{ tableData[1].avgValue }}</uni-td>
            <uni-td>{{ tableData[2].avgValue }}</uni-td>
          </uni-tr>
        </template>
      </uni-table>
    </view>
  </view>
</template>

<script>
// import uCharts from '@/plugins/stan-ucharts/u-charts/u-charts-2.js'
// import * as echarts from 'echarts'
import { get, postJ } from '@/utils/api.js'
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
import { debounce } from 'lodash'
import mqtt from './mqtt'
export default {
  mixins: [mqtt],
  data () {
    return {
      opts: {},
      chartData: {},
      tableData: [],
      propertyList: [
        {
          name: '油温',
          property: 'oil_temp'
        },
        {
          name: '速度',
          property: 'speed'
        },
        {
          name: '压力',
          property: 'measure_pressure'
        }
      ],
      // mqtt 订阅类别
      topIc_type: 'EXTRUDER_TOPIC'
    }
  },
  props: ['realData', 'info'],
  computed: {
    // mqtt topic
    TOPIC () {
      if (this.info.iotId) {
        return {
          topic: `/${this.topIc_type}/${this.info.iotId}`,
          qos: 0
        }
      } else {
        return null
      }
    }
  },
  created () {
    this.getTableData()
    if (this.TOPIC) {
      this.mqttInit()
    }
  },
  mounted () {
    this.initGauge()
  },

  methods: {
    async initGauge () {
      console.log(this.info)
      let option = {
        tooltip: {
          show: false
        },
        series: [
          {
            zlevel: 1,
            ...this.getGaugeSeries(),
            center: ['25%', '30%'],

            splitNumber: 4,
            min: 0,
            max: this.getMax(this.info.measure_pressure || 0, 12),
            name: 'Pressure',
            backgroundColor: '#000',
            data: [
              {
                value: this.realData.measure_pressure
                  ? this.realData.measure_pressure.value
                  : 0,
                name: '压力表'
              }
            ],
            detail: {
              width: '60%',
              lineHeight: 40,
              height: 40,
              fontSize: 18,
              borderRadius: 8,
              offsetCenter: [0, '30%'],
              valueAnimation: true,
              formatter: function (value) {
                return `${value}kg/cm²`
              }
            }
          },
          //   {
          //     ...this.getGaugeSeriesBg(),
          //     center: ['25%', '28%']
          //   },

          {
            ...this.getGaugeSeries(),
            zlevel: 1,
            splitNumber: 4,
            min: 0,
            max: this.getMax(this.info.speed || 0, 80),
            center: ['75%', '30%'],
            name: 'Pressure1',
            data: [
              {
                value: this.realData.speed ? this.realData.speed.value : 0,
                name: '速度表'
              }
            ],
            detail: {
              width: '60%',
              lineHeight: 40,
              height: 40,
              fontSize: 18,
              borderRadius: 8,
              offsetCenter: [0, '30%'],
              valueAnimation: true,
              formatter: function (value) {
                return `${value}m/s`
              }
            }
          },
          //   {
          //     ...this.getGaugeSeriesBg(),
          //     center: ['75%', '28%']
          //   },
          {
            ...this.getGaugeSeries(),
            zlevel: 1,
            splitNumber: 4,
            min: 0,
            max: this.getMax(this.info.oil_temp || 0, 4000),
            center: ['25%', '80%'],
            name: 'Pressure2',
            data: [
              {
                value: this.realData.oil_temp
                  ? this.realData.oil_temp.value
                  : 0,
                name: '油温表'
              }
            ],
            detail: {
              width: '60%',
              lineHeight: 40,
              height: 40,
              fontSize: 18,
              borderRadius: 8,
              offsetCenter: [0, '30%'],
              valueAnimation: true,
              formatter: function (value) {
                return `${value}度`
              }
            }
          }
          //   {
          //     ...this.getGaugeSeriesBg(),
          //     center: ['25%', '75%']
          //   }
        ]
      }
      this.$refs.chart.init(echarts, chart => {
        chart.setOption(option)
      })
    },

    async getTableData () {
      function fnNum (num) {
        return num < 10 ? '0' + num : num
      }
      let startTime
      let endTime

      let ndate = new Date()
      let year = ndate.getFullYear()
      let month = ndate.getMonth() + 1
      let day = ndate.getDate()

      let _date = `${year}-${fnNum(month)}-${fnNum(day)}`
      startTime = _date + ' 00:00:00'
      endTime = _date + ' 23:59:59'

      const resList = await Promise.all(
        this.propertyList.map(i =>
          postJ(
            this.apiUrl +
              `/asset/getEquHistory?equId=${this.info.id}&startTime=${startTime}&endTime=${endTime}&timeType=3&property=${i.property}`
          )
        )
      )
      this.tableData = resList.map(i => {
        if (i?.success) {
          return i.data || {}
        }
        return {}
      })
    },

    //  mqtt处理数据
    initMqttData (items) {
      console.log('mqtt处理数据', items)
      for (const [key, obj] of Object.entries(items)) {
        const realData = this.realData
        realData[key].value = obj.value
        realData[key].time = obj.time

        this.$emit('update:realData', realData)
      }
      let initGauge = debounce(this.initGauge, 1000)
      initGauge()
    },

    getGaugeSeriesBg () {
      return {
        data: [],
        startAngle: 360,
        endAngle: 0,
        radius: '41%',
        type: 'gauge',
        detail: {
          show: false
        },
        title: {
          show: false
        },
        axisLabel: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            width: 100,
            color: [[1, '#fff']]
          }
        },
        progress: {
          show: false
        },
        anchor: {
          show: false
        },
        pointer: {
          show: false
        }
      }
    },
    getGaugeSeries () {
      return {
        startAngle: 200,
        endAngle: -20,
        radius: '40%',
        type: 'gauge',
        detail: {
          valueAnimation: true,
          formatter: '{value}'
        },
        title: {
          show: true,
          offsetCenter: [0, '65%'],
          color: '#9e9e9e',
          fontSize: 14
        },
        axisLabel: {
          rotate: 360,
          distance: -38,
          color: '#666666',
          fontSize: 18
        },
        splitLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLine: {
          roundCap: true,
          lineStyle: {
            width: 12,
            // color:'#dddefd',
            color: [[1, '#B9BEFF']]
          }
        },
        progress: {
          show: true,
          roundCap: true,
          width: 12,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              {
                offset: 0,
                color: '#15b4ff'
              },
              {
                offset: 1,
                color: '#716dff'
              }
            ]),
            shadowColor: 'rgba(0,138,255,0.45)',
            shadowBlur: 10,
            shadowOffsetX: 2,
            shadowOffsetY: 2
          }
        },
        itemStyle: {
          color: '#7a71ff',
          shadowColor: 'rgba(0,138,255,0.45)',
          shadowBlur: 10,
          shadowOffsetX: 2,
          shadowOffsetY: 2,
          borderCap: 'round'
        },
        anchor: {
          show: true,
          showAbove: true
        },
        pointer: {
          icon: 'path://M2090.36389,615.30999 L2090.36389,615.30999 C2091.48372,615.30999 2092.40383,616.194028 2092.44859,617.312956 L2096.90698,728.755929 C2097.05155,732.369577 2094.2393,735.416212 2090.62566,735.56078 C2090.53845,735.564269 2090.45117,735.566014 2090.36389,735.566014 L2090.36389,735.566014 C2086.74736,735.566014 2083.81557,732.63423 2083.81557,729.017692 C2083.81557,728.930412 2083.81732,728.84314 2083.82081,728.755929 L2088.2792,617.312956 C2088.32396,616.194028 2089.24407,615.30999 2090.36389,615.30999 Z',
          length: '75%',
          width: 12,
          offsetCenter: [0, 8]
          // itemStyle: {
          // 	color: '#7a71ff',
          // }
        }
      }
    },

    getMax (data, def = 100) {
      let half = def / 2

      if (data <= def) {
        return def
      }

      const n = data % half
      const m = Math.floor(data / half)

      return n === 0 ? m * half : (m + 1) * half
    }
  }
}
</script>

<style lang="scss" scoped>
.InternetExtruder /deep/.uni-table {
  min-width: 100vw !important;

  .uni-table-td,
  .uni-table-th {
    padding: 20rpx 10rpx !important;
    text-align: center !important;
  }
}
.mainBox-image {
  width: 100%;
  .image-title {
    width: 98%;
    margin: 16rpx auto 0;
    font-size: 28rpx;
    font-weight: bold;
    color: #000;
  }
  .image-list {
    width: 100vw;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .charts-box {
      width: 100vw;
      height: 800rpx;
    }
  }
}
</style>
