<template>
  <view class="InternetDryingBox">
    <view class="mainBox-image">
      <view class="image-title">实时温度</view>
      <view class="image-list">
        <view class="list-swiper">
          <l-echart ref="chart"></l-echart>
        </view>
        <view class="list-swiper">
          <l-echart ref="chart1"></l-echart>
        </view>
        <view class="list-swiper">
          <l-echart ref="chart2"></l-echart>
        </view>
        <view class="list-swiper">
          <l-echart ref="chart3"></l-echart>
        </view>
      </view>
    </view>
    <view>
      <uni-table border stripe emptyText="暂无更多数据">
        <!-- 表头行 -->
        <uni-tr>
          <uni-th align="center" width="180rpx"></uni-th>
          <uni-th align="center">温度1</uni-th>
          <uni-th align="center">温度2</uni-th>
          <uni-th align="center">温度3</uni-th>
          <uni-th align="center">温度4</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-td>{{ tableData[3].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-td>{{ tableData[3].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-td>{{ tableData[3].avgValue }}</uni-td>
          </uni-tr>
        </template>
      </uni-table>
    </view>
  </view>
</template>

<script>
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
import { get, postJ } from '@/utils/api.js'
import { debounce } from 'lodash'
import mqtt from './mqtt'
export default {
  mixins: [mqtt],
  data () {
    return {
      opts: {},
      chartData: {},
      tableData: [],
      propertyList: [
        {
          name: '温度1',
          property: 'temp1'
        },
        {
          name: '温度2',
          property: 'temp2'
        },
        {
          name: '温度3',
          property: 'temp3'
        },
        {
          name: '温度4',
          property: 'temp4'
        }
      ],
      // mqtt 订阅类别
      topIc_type: 'DRYING_OVEN_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: {
    initGauge () {
      let option = this.getGaugeOption(
        this.realData.temp1 ? this.realData.temp1.value : 0,
        '温度1'
      )
      this.$refs.chart.init(echarts, chart => {
        chart.setOption(option)
      })
      let option1 = this.getGaugeOption(
        this.realData.temp2 ? this.realData.temp2.value : 0,
        '温度2'
      )

      this.$refs.chart1.init(echarts, chart => {
        chart.setOption(option1)
      })
      let option2 = this.getGaugeOption(
        this.realData.temp3 ? this.realData.temp3.value : 0,
        '温度3'
      )
      this.$refs.chart2.init(echarts, chart => {
        chart.setOption(option2)
      })
      let option3 = this.getGaugeOption(
        this.realData.temp4 ? this.realData.temp4.value : 0,
        '温度4'
      )
      this.$refs.chart3.init(echarts, chart => {
        chart.setOption(option3)
      })
    },

    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()
    },

    //指针和起点覆盖
    getGaugeSeriesCover () {
      return {
        detail: {
          show: false
        },
        startAngle: 180,
        endAngle: -0,
        splitNumber: 2,
        radius: '84%',
        type: 'gauge',
        title: {
          show: false
        },
        axisLabel: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLine: {
          show: false
        },
        progress: {
          show: false
        },
        itemStyle: {
          color: '#7a71ff',
          shadowColor: 'rgba(0,138,255,0.45)',
          shadowBlur: 10,
          shadowOffsetX: 2,
          shadowOffsetY: 2,
          borderCap: 'round'
        },
        anchor: {
          show: true,
          showAbove: false,
          offsetCenter: ['-98.5%', -1],
          size: 10,
          icon: 'circle',
          itemStyle: {
            color: '#98a4f2',
            borderColor: '#fff',
            backgroundColor: '#98a4f2',
            borderWidth: 5
          }
        },
        pointer: {
          show: true,
          icon: 'image://data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDI0LjAuMSwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IuWbvuWxgl8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCIKCSB2aWV3Qm94PSIwIDAgMjAwIDIwMCIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMjAwIDIwMDsiIHhtbDpzcGFjZT0icHJlc2VydmUiPgo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPgoJLnN0MHtmaWxsOiNGRkZGRkY7fQoJLnN0MXtmaWxsOiM0MDYzRDE7fQo8L3N0eWxlPgo8cmVjdCB4PSI2Ny43IiB5PSI3NC43IiBjbGFzcz0ic3QwIiB3aWR0aD0iNjYuOSIgaGVpZ2h0PSI2OC43Ii8+CjxwYXRoIGNsYXNzPSJzdDEiIGQ9Ik0xNzUsMTA4LjNjMCw0MS40LTMzLjYsNzUtNzUsNzVzLTc1LTMzLjYtNzUtNzVzNjQuNi05MS43LDc1LTkxLjdTMTc1LDY2LjksMTc1LDEwOC4zeiBNNzcuMSwxMDguMwoJYzAsMTIuNywxMC4zLDIyLjksMjIuOSwyMi45czIyLjktMTAuMywyMi45LTIyLjlTMTEyLjcsODUuNCwxMDAsODUuNFM3Ny4xLDk1LjcsNzcuMSwxMDguM3oiLz4KPC9zdmc+Cg==',
          length: '18%',
          width: '16%',
          keepAspect: true,
          offsetCenter: [0, '-90%']
        }
      }
    },
    getGaugeOption (data, chartName) {
      const max = this.getMax(data || 0, 100)

      const min = 0
      return {
        tooltip: {
          show: false
        },
        series: [
          {
            zlevel: 1,
            min,
            max,
            startAngle: 180,
            endAngle: -0,
            splitNumber: 2,
            radius: '55%',
            type: 'gauge',
            detail: {
              width: '60%',
              lineHeight: 40,
              height: 40,
              fontSize: 20,
              borderRadius: 8,
              offsetCenter: [0, '-20%'],
              valueAnimation: true,
              formatter: function (value) {
                return `${value}℃`
              }
            },
            title: {
              show: true,
              offsetCenter: [0, '14%'],
              color: '#9e9e9e',
              fontSize: 14
            },
            axisLabel: {
              rotate: 360,
              distance: -10,
              color: '#666',
              fontSize: 16
            },
            splitLine: {
              show: true,
              length: 8,
              distance: -20,
              lineStyle: {
                width: 1,
                color: '#666'
              }
            },
            axisTick: {
              show: true,
              splitNumber: 10,
              distance: -15,
              length: 4,
              lineStyle: {
                height: 2,
                color: '#666'
              }
            },
            axisLine: {
              show: false
            },
            progress: {
              show: true,
              roundCap: true,
              width: 2,
              showAbove: false,
              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: false,
              offsetCenter: ['-98%', '-1.2%'],
              size: 8,
              icon: 'circle',
              itemStyle: {
                color: '#98a4f2',
                borderColor: '#fff',
                backgroundColor: '#98a4f2',
                borderWidth: 5
              }
            },

            pointer: {
              show: true,
              icon: 'pin',
              // icon: 'image://data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDI0LjAuMSwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IuWbvuWxgl8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCIKCSB2aWV3Qm94PSIwIDAgMjAwIDIwMCIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMjAwIDIwMDsiIHhtbDpzcGFjZT0icHJlc2VydmUiPgo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPgoJLnN0MHtmaWxsOiNGRkZGRkY7fQoJLnN0MXtmaWxsOiM0MDYzRDE7fQo8L3N0eWxlPgo8cmVjdCB4PSI2Ny43IiB5PSI3NC43IiBjbGFzcz0ic3QwIiB3aWR0aD0iNjYuOSIgaGVpZ2h0PSI2OC43Ii8+CjxwYXRoIGNsYXNzPSJzdDEiIGQ9Ik0xNzUsMTA4LjNjMCw0MS40LTMzLjYsNzUtNzUsNzVzLTc1LTMzLjYtNzUtNzVzNjQuNi05MS43LDc1LTkxLjdTMTc1LDY2LjksMTc1LDEwOC4zeiBNNzcuMSwxMDguMwoJYzAsMTIuNywxMC4zLDIyLjksMjIuOSwyMi45czIyLjktMTAuMywyMi45LTIyLjlTMTEyLjcsODUuNCwxMDAsODUuNFM3Ny4xLDk1LjcsNzcuMSwxMDguM3oiLz4KPC9zdmc+Cg==',
              length: '26%',
              width: '23%',
              keepAspect: true,
              offsetCenter: [0, '-95%']
            },
            center: ['48%', '54%'],
            name: 'Temperature',
            backgroundColor: '#000',
            data: [
              {
                value: data,
                name: chartName
              }
            ]
          }
          //   {
          //     min,
          //     max,
          //     zlevel: 2,
          //     ...this.getGaugeSeriesCover(),
          //     // center: ['48%', '77%'],
          //     center: ['49%', '62%'],
          //     name: 'Temperature',
          //     backgroundColor: '#000',
          //     data: [
          //       {
          //         value: data,
          //         name: chartName
          //       }
          //     ]
          //   }
        ]
      }
    },
    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>
.InternetDryingBox /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;
    flex-wrap: wrap;
    .list-swiper {
      width: 50%;
      height: 400rpx;

      background: url('~@/static/charts/dryingBox-bg.jpg') no-repeat 50% 50%;
      // background-image: url('~@/assets/img/charts/dryingBox-bg.jpg');
      background-size: 77% auto;
    }
  }
}
</style>
