<template>
    <div class="detailPage">
        <div class="detail-head">
            <div
                class="head-title"
                :class="{ 'head-title-hover': item.showBg }"
                v-for="(item, idx) in titleList"
                :key="idx"
                @click="handleType(item.funcid)"
            >
                <span>{{ item.name }}</span>
            </div>
        </div>
        <div class="container">
            <div
                style="height:100%;width:100%;position:relative"
                v-if="resChartData.length>0"
            >
                <ff-canvas
                    v-for="(item, idx) in titleList"
                    class="f2-chart"
                    id="wxf2"
                    onInit="{{onInitChart}}"
                    v-if="item.showBg"
                ></ff-canvas>
                <div
                    class="temp_unit"
                    v-show="currentItem2.funcid=='Tdb,RH'"
                >℃</div>
                <div
                    class="wet_unit"
                    v-show="currentItem2.funcid=='Tdb,RH'"
                >%</div>
                <div
                    class="nodata"
                    v-show="noData"
                >暂无数据</div>
            </div>
            <div
                class="nodata2"
                v-else
            >该空间数据未配置</div>
        </div>
        <div class="container-text">
            <span>{{currentItem2.funcid=='Tdb,RH'?'温湿度逐时分布':'浓度逐时分布'}}</span>
        </div>
        <!-- 文案 -->
        <div class="detail-text">
            <span class="text-level">{{ currentItem2.level }}</span>
            <div v-if="currentItem2.img" class="text-img">
                <image :src="currentItem2.img" />
            </div>
            <div class="text-item">
                <div class="text-name">{{ currentItem2.name }}·小贴士</div>
                <div class="text-inner">
                    <p
                        class="text-line"
                        v-for="(tx,idx) in currentItem2.text"
                        :key="idx"
                    >
                        <div class="text-icon">
                            <image src="{{ h5StaticPath }}text_icon.svg" />
                        </div>
                        <div class="text-content">{{tx}}</div>
                    </p>
                </div>
            </div>

        </div>
    </div>

</template>
<script>
import wepy from '@wepy/core'
import { getChartListHTTP } from '@/packagesEnv/api/officehome.js'
import config from '@/config'
const titleList = [
  {
    id: 0,
    name: 'CO₂',
    funcid: 'CO2',
    text: [
      'CO₂，一种无色无味气体；CO₂的标准为1000ppm',
      'CO₂过高，影响人体呼吸系统，大脑容易疲劳，工作效率降低',
      '室内人员增多，新风量不足时，室内CO₂的浓度就会上升',
      '宜开窗通风或增加送风量，来降低CO₂浓度'

    ],
    level: '不同浓度下的人体感觉',
    img: `${config.h5StaticPath + '/page-officehome/'}CO2.png`,
    showBg: false

  },
  {
    id: 1,
    name: 'PM2.5',
    funcid: 'PM2d5',
    text: [
      'PM2.5的平均值在0-35ug/m3',
      'PM2.5浓度过高，影响人体呼吸系统和心血管系统健康',
      '应开启除尘净化设备'
    ],
    level: '不同PM2.5浓度对应等级',
    img: `${config.h5StaticPath + '/page-officehome/'}pm25.png`,
    showBg: false
  },
  {
    id: 2,
    name: '甲醛',
    funcid: 'HCHO',
    text: [
      '甲醛（HCHO）是无色有刺激性有机气体。甲醛的主要危害表现为对皮肤和黏膜的刺激作用，室内甲醛浓度长期偏高会引发呼吸系统，消化系统或免疫系统疾病。',
      '甲醛多来自于室内装饰材料，如家具，墙纸，油漆以及胶水、芳香剂等物质。',
      '由于家具，胶水中的甲醛挥发是一个长期缓慢的过程，因此甲醛超标常表现为室内甲醛浓度长期处于较高的数值。',
      '最为有效避免甲醛超标的方法是持续高效的通风，通过引入室外新鲜空气将室内甲醛浓度长期控制在低于有害标准的范围内。',
      '由于甲醛传感器为电化学传感器，存在交叉干扰的特性，当室内出现无害的挥发性气体时也会导致测得的甲醛浓度短暂升高，如吸烟，使用香水，空气清新剂，喷洒酒精，甚至剥橘子皮溅出的汁液均可能在短时间内影响甲醛传感器的读数，在去除干扰源后，此种影响会在短时间内消除，可不必因此产生担忧。'
    ],
    level: '不同阈值浓度对应标准',
    img: `${config.h5StaticPath + '/page-officehome/'}methanal.png`,
    showBg: false
  },
  {
    id: 3,
    name: '温湿度',
    funcid: 'Tdb,RH',
    text: [
      '温度表示空气的冷热程度夏季高温高湿会使人烦躁、疲倦',
      '冬季湿度过高时，人体感觉越冷冬季湿度低易引起呼吸道不适',
      '室外温度较高时，宜遮阳关窗'
    ],
    level: '',
    img: '',
    showBg: false
  }
]
let spaceId = null
let currentTab = titleList[0]
let chart = null
let resultData = {}

function onInitChart(F2, config) {
  var data
  data = resultData.chartData
  console.log('data', data)
  console.log('config', config)
  chart = new F2.Chart({ ...config })

  if (currentTab.funcid === 'Tdb,RH') {
    chart.source(data, {
      sales: {
        tickCount: 4,
        alias: '温度'
      },
      rhsales: {
        tickCount: 4,
        alias: '湿度'
      },
      time: {
        tickCount: 6,
        mask: 'HH:mm'
      }
    })
    chart.axis('rhsales', {
      grid: null
    })

        // 图例
    chart.legend({
      custom: true,
      position: 'top',
      align: 'center',
      items: [
                { name: '温度', marker: 'circle', fill: '#246FE5' },
                { name: '湿度', marker: 'circle', fill: '#3DCBCC' }
      ]
    })
  } else {
    chart.source(data, {
      sales: {
        tickCount: 4,
        type: 'linear',
        max: resultData.max,
        alias: currentTab.funcid === 'HCHO' ? '甲醛' : currentTab.funcid === 'CO2' ? 'CO₂' : 'PM2.5'
      },
      time: {
        tickCount: 6,
        mask: 'HH:mm'
      }
    })
  }
    // 辅助线
  chart.axis('sales', {
    label: (text, index, total) => {
      const cfg = {
      }
      if (currentTab.funcid == 'HCHO') {
        cfg.text = Number(text).toFixed(2)
      } else if (currentTab.funcid == 'CO2') {
        cfg.text = Number(text)
      } else {
        cfg.text = Number(text).toFixed(1)
      }
      return cfg
    }
  })

  chart.tooltip({
    offsetY: 20,
    showTitle: true
  })

  var max = resultData.max
  if (data.length > 1) {
    chart.guide().line({
      start() {
        return [0, max]
      }, // 辅助线起始位置，
      end: [data.length - 1, max], // 辅助线结束位置
      style: {
        stroke: 'red', // 线的颜色
        lineWidth: 1 // 线的宽度
      }
    })
    if (currentTab.funcid === 'Tdb,RH') { // 加湿度的面积图
      chart.line().position('time*rhsales').color('#3DCBCC').shape('smooth')
      chart.line().position('time*sales').color('#246FE5').shape('smooth')
    } else {
      chart.area().position('time*sales').color('#3DCBCC').shape('smooth')
    }
  }

    // 注意：需要把chart return 出来
  if (currentTab.funcid === 'Tdb,RH') { // 加湿度的线
    chart.line().position('time*rhsales').color('#3DCBCC').shape('smooth')
    chart.line().position('time*sales').color('#246FE5').shape('smooth')
  } else {
    chart.line().position('time*sales').color('#3DCBCC').shape('smooth') // smooth stack
  }
  chart.render()
  return chart
};

wepy.page({
  data: {
    h5StaticPath: config.h5StaticPath + '/page-officehome/',
    titleFlag: false,
    titleList,
    currentItem2: titleList[0],
    noData: true,
    resChartData: [],
    onInitChart
  },
  computed: {},

  onLoad(options) {
    spaceId = options.spaceId  // 空间id
    var funcid = options.funcid  // 指标的名字
    this.handleType(funcid)
  },
  methods: {
    initChartdate(propertyData, dayTarget, funcid) { // 只是一个处理数据的函数
      if (!Array.isArray(propertyData) || !Array.isArray(dayTarget)) {
        return []
      }
      let baseArr = propertyData && propertyData.slice(1) || []
      let tragetChart = []

      let handleNumber = (val) => {
        return Number(val)
      }

      let initNum = {
        PM2d5: handleNumber,
        TVOC: function (value) {
          return Number(value)
        },
        CO2: handleNumber,
        HCHO: function (value) {
          return Number(Number(value).toFixed(2))
        },
        RH: handleNumber,
        Tdb: handleNumber
      }

            // 类型
      if (baseArr.length > 0) {
        baseArr.forEach(item => {
          item[1] = item[1] == '-9999' ? null : initNum[funcid](item[1])
          if (item[1] !== null) { this.noData = false }
        })
      }

      if (baseArr.length === dayTarget.length) {
        dayTarget.forEach((item, index) => {
          let time = ''
          item.time && (time = item.time.slice(0, 2) + ':' + item.time.slice(2, 4))
          let initObj = {
            time: time,
            sales: baseArr[index][1]

          }
          tragetChart.push(initObj)
        })
      }
      return tragetChart
    },
        // 获取数据
    getData(funcid) {
      let paramObj = {
        spaceId: spaceId,
        funcid: funcid
      }
      return getChartListHTTP(paramObj).then((res) => {
        let { propertyData, dayTarget } = res
        var chartData = this.initChartdate(propertyData, dayTarget, funcid)// 先处理一下数据 返回的是处理后的chart数据
                // 辅助线 - 上限
        let max = null

        switch (funcid) {
          case 'CO2':
            max = dayTarget && dayTarget[0] && dayTarget[0].co2Max
                        // max = 2;
            break
          case 'PM2d5':
            max = dayTarget && dayTarget[0] && dayTarget[0].pm25Max
                        //  max = 4.6;
            break
          case 'HCHO':
            max = dayTarget && dayTarget[0] && dayTarget[0].hchoMax
                        //  max = 0.05;
            break
                    //   case 'TVOC':
                    //     max = dayTarget[0].tvocMax;
                    //     break;
          case 'RH':
                        // max = dayTarget[0].humidityMax;
            max = null
            break
          case 'Tdb':
                        // max = dayTarget[0].temperatureMax;
            max = null
            break
          default:
            break
        }
        return {
          chartData, max
        }
      })
    },
    queryAllData(ele) {
      var funcidArr = ele.funcid.split(',')
      var promiseArr = []
      funcidArr.forEach((item) => { // 处理请求
        var promiseMethod = this.getData(item)
        promiseArr.push(promiseMethod)
      })
      wx.showLoading({
        title: '加载中'
      })
      var _this = this
      Promise.all(promiseArr).then(function (res) { // 这个res 就是返回的chart数据
        console.log('promise.all', res)

        if (ele.funcid === 'Tdb,RH') {
          var tdata = res[0].chartData
          var rhdata = res[1].chartData
          tdata.map(function (ele, index) {
            ele.rhsales = rhdata[index].sales
            return ele
          })
        }
        _this.resChartData = res[0].chartData || []

        resultData = {
          chartData: res[0].chartData,
          max: res[0].max
        }
        console.log('resultData', resultData)
        ele.showBg = true
        wx.hideLoading()
      })
    },
    handleType(funcid) {
      let self = this
      this.titleList.forEach((ele) => {
        if (ele.funcid === funcid) {
          self.currentItem2 = ele
          currentTab = ele
          this.queryAllData(ele)
        } else {
          ele.showBg = false
        }
      })
    }
  }

})
</script>
<style lang="less">
page {
    // height: 100%;
}
.detailPage {
}
.detail-head {
    display: flex;
    justify-content: space-around;
    align-items: center;
    text-align: center;
    width: 100%;
    padding: 24rpx 0;
    background: #fff;
    .head-title {
        font-family: PingFang SC;
        font-size: 28rpx;
        font-weight: 400;
        line-height: 44rpx;
        // width: 58rpx;
        height: 44rpx;
        color: #8B949E;

    }
    .head-title-hover {
        font-weight: 600;
        color: #1B2129;
        position: relative;
    }
    .head-title-hover::after {
        position: absolute;
        top: 60rpx;
        left: 0rpx;
        content: '';
        width: 100%;
        height: 6rpx;
        border-radius: 6px;
        background: #3DCBCC;
    }
}

.container {
    width: 100%;
    height: 500rpx;
    background: #fff;
    // overflow: hidden;
    .f2-chart {
        width: 100%;
        height: 500rpx;
    }
    .temp_unit {
        position: absolute;
        top: 32rpx;
        left: 36rpx;
        color: #656872;
        font-size: 26rpx;
    }
    .wet_unit {
        position: absolute;
        top: 32rpx;
        right: 36rpx;
        color: #656872;
        font-size: 26rpx;
    }
    .nodata {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-26px, -20px);
        color: #c4c4c4;
    }
    .nodata2 {
        height: 100%;
        color: #c4c4c4;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
.container-text {
    display: flex;
    justify-content: center;
    padding-bottom: 21px;
    font-family: PingFang SC;
    font-size: 24rpx;
    font-style: normal;
    font-weight: 400;
    line-height: 24rpx;
    letter-spacing: 0em;
    text-align: left;
    color: #c4c4c4;
    background: #fff;
}
.detail-text {
    padding: 70rpx 40rpx;
    .text-item {
        padding-bottom: 80rpx;
    }
    .text-name {
        padding-bottom: 40rpx;
        font-family: PingFang SC;
        font-size: 28rpx;
        font-weight: 600;
        line-height: 44rpx;
    }
    .text-icon {
        margin-right: 16rpx;
        height: 40rpx;
        width: 20rpx;
        image {
            height: 100%;
            width: 100%;
        }
    }
    .text-content{
        flex:1;
    }
    .text-inner {
        font-family: PingFang SC;
        font-size: 13px;
        font-weight: 400;
        line-height: 20px;
        color: #626c78;
        .text-line {
            display: flex;
            padding-bottom: 24rpx;
        }
    }
    .text-level {
        padding-top: 80rpx;
        font-family: PingFang SC;
        font-size: 28rpx;
        font-style: normal;
        font-weight: 600;
        line-height: 44rpx;
    }
    .text-img {
        padding-top: 40rpx;
        padding-bottom: 80rpx;

        height: 122rpx;
        image {
            width: 100%;
            height: 100%;
        }
    }
}
</style>
<config>
    {
        backgroundColor: '#ffffff',
       "usingComponents": {
            "ff-canvas": "../../vendor/antv/wx-f2"
        } 
    }
</config>
