<template>
  <div class="detail-content">
    <div class="title">环境参数</div>
    <van-tabs class="my-tab" @change="changeTab" v-model:active="active">
      <van-tab
        :title="item.name"
        :name="item.funcid"
        :key="item.id + '' + index"
        v-for="(item, index) in titleList"
      >
        <div class="container-text" v-if="item.options">
          <span>{{
            item.funcid == "Tdb,RH" ? "温湿度逐时分布" : "浓度逐时分布"
          }}</span>
        </div>
        <div class="chart-box">
          <com-chart
            :options="item.options"
            v-if="item.options"
            :id="item.funcid"
            height="100%"
            width="100%"
          />
          <div v-else class="no-data" height="100%" width="100%">
            <template v-if="item.showNowData === 1">
              <img :src="parseImgUrl('page-officehome', 'empty.png')" alt="" />
              <span>暂无数据</span>
            </template>
            <template v-if="item.showNowData === 2">
              <img :src="parseImgUrl('page-officehome', 'empty.png')" alt="" />
              <span>该空间数据未配置</span>
            </template>
          </div>
        </div>
        <div class="detail-desc clearfix">
          <!-- <div class="detail-title">
            {{ item.name }}
          </div> -->
          <div class="detail-text">
            <p v-for="(textItem, idx) in item.text" :key="idx">
              <!-- <van-icon class="icon" name="success" v-if="idx % 2 == 0" /> -->
              <span class="circle"></span>
              <span class="tem-span">
                {{ textItem }}
              </span>
            </p>
          </div>
        </div>
        <div class="detail-bottom">
          <p>{{ item.level }}</p>
          <div class="text-img">
            <img :src="item.img" alt="" />
          </div>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, watch } from "vue";
import ComChart from "@/components/charts/ComChart.vue";
import { useRoute } from "vue-router";
import * as echarts from "echarts";
import { EChartsOption } from "echarts";
import { getChartListHTTP } from "@/apis/envmonitor";
import { setQueryConfig } from "@/utils";
import { parseImgUrl } from "@/utils";
import { Toast } from "vant";

export default defineComponent({
  props: {
    query: {
      // 空调基本信息
      type: Object,
      default: () => {},
    },
  },
  components: {
    ComChart,
  },
  setup(props) {
    const titleList: any = [
      {
        id: 0,
        name: "CO₂",
        funcid: "CO2",
        text: [
          "CO₂，一种无色无味气体",
          "CO₂的标准为1000ppm",
          "CO₂过高，影响人体呼吸系统",
          "大脑易疲劳，工作效率降低",
          "室内人员增多，新风量不足时",
          "室内CO₂的浓度就会上升",
          "宜开窗通风或增加送风量",
          "来降低CO₂浓度",
        ],
        level: "不同浓度下的人体感觉",
        img: parseImgUrl("page-officehome", "CO2.png"),
        showNowData: 0, // 0:loading 1:暂无数据 2：暂无服务定制时间
        options: null,
      },
      {
        id: 1,
        name: "PM2.5",
        funcid: "PM2d5",
        options: null,
        text: [
          "PM2.5，直径≤2.5微米的颗粒",
          "PM2.5的平均值在0-35μg/m3",
          "PM2.5浓度过高，影响人体",
          "呼吸系统和心血管系统健康",
          "应开启除尘净化设备",
        ],
        level: "不同PM2.5浓度对应等级",
        img: parseImgUrl("page-officehome", "pm25.png"),
        showNowData: 0, // 0:loading 1:暂无数据 2：暂无服务定制时间
      },
      {
        id: 2,
        name: "甲醛",
        options: null,
        funcid: "HCHO",
        text: [
          "甲醛（HCHO）是无色有刺激性有机气体。甲醛的主要危害表现为对皮肤和黏膜的刺激作用，室内甲醛浓度长期偏高会引发呼吸系统，消化系统或免疫系统疾病。",
          "甲醛多来自于室内装饰材料，如家具，墙纸，油漆以及胶水、芳香剂等物质。",
          "由于家具，胶水中的甲醛挥发是一个长期缓慢的过程，因此甲醛超标常表现为室内甲醛浓度长期处于较高的数值。",
          "最为有效避免甲醛超标的方法是持续高效的通风，通过引入室外新鲜空气将室内甲醛浓度长期控制在低于有害标准的范围内。",
          "由于甲醛传感器为电化学传感器，存在交叉干扰的特性，当室内出现无害的挥发性气体时也会导致测得的甲醛浓度短暂升高，如吸烟，使用香水，空气清新剂，喷洒酒精，甚至剥橘子皮溅出的汁液均可能在短时间内影响甲醛传感器的读数，在去除干扰源后，此种影响会在短时间内消除，可不必因此产生担忧。",
        ],
        level: "不同阈值浓度对应标准",
        img: parseImgUrl("page-officehome", "methanal.png"),
        showNowData: 0, // 0:loading 1:暂无数据 2：暂无服务定制时间
      },
      {
        id: 3,
        name: "温湿度",
        funcid: "Tdb,RH",
        options: null,
        text: [
          "温度表示空气的冷热程度",
          "夏季高温高湿会使人烦躁、疲倦",
          "冬季湿度过高时，人体感觉越冷",
          "冬季湿度低易引起呼吸道不适",
          "室外温度较高时，宜遮阳关窗",
        ],
        level: "",
        img: "",
        showNowData: 0, // 0:loading 1:暂无数据 2：暂无服务定制时间
      },
    ];
    const query: {
      funcid: string;
      spaceId: string;
    } = {
      funcid: "",
      spaceId: "",
    };
    const activeItem: any = [];
    const proxyData = reactive({
      active: "",
      activeItem: activeItem,
      titleList: titleList,
      query: props.query ? props.query : query,
      parseImgUrl: parseImgUrl,
      /**
       * 加载loading
       */
      loadingStart() {
        Toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true,
          message: "加载中...",
        });
      },
      /**
       * 结束
       */
      loadinngEnd() {
        Toast.clear();
      },
      /**
       * 设置当前选中的tab
       */
      setActiveItem() {
        for (let i = 0; i < proxyData.titleList.length; i++) {
          if (proxyData.titleList[i].funcid == proxyData.query.funcid) {
            proxyData.active = proxyData.titleList[i].funcid;
            proxyData.activeItem = proxyData.titleList[i];
            break;
          }
        }
      },
      /**
       * 详情页面tab切换
       */
      changeTab() {
        if (proxyData.query.spaceId) {
          proxyData.query.funcid = proxyData.active;
          proxyData.setActiveItem();
          proxyData.queryAllData();
        }
      },
      // 查询echarts图表
      queryAllData() {
        if (proxyData.activeItem.funcid) {
          let funcid = proxyData.activeItem.funcid;
          proxyData.loadingStart();
          if (funcid === "Tdb,RH") {
            // 两条线的 时候
            proxyData.formatTowOptions(funcid);
          } else {
            proxyData.formatOptios(funcid);
          }
        }
      },
      /**
       *获取图表统计数据
       * @param funcid
       */
      getData(funcid: string = "") {
        // debugger
        let paramObj = {
          spaceId: proxyData.query.spaceId,
          funcid: funcid,
        };
        const paramStr: string = setQueryConfig(paramObj);
        return getChartListHTTP(paramStr)
          .then((res) => {
            const resData: any = res;
            let { propertyData, dayTarget } = resData;
            let chartData = proxyData.formatChartData(
              propertyData,
              dayTarget,
              funcid
            );
            // 设置警线的值
            let chartMax = proxyData.setMax(funcid, dayTarget);
            if (funcid === "Tdb" || funcid === "RH") {
              return chartData;
            } else {
              return {
                chartData,
                chartMax,
              };
            }
          })
          .catch((error: any) => {
            proxyData.loadinngEnd();
          });
      },
      /**
       * co pm 甲醛统计数据格式化成图表可使用的数据
       * @param propertyData
       * @param dayTarget
       * @param funcid
       */
      formatChartData(propertyData: any, dayTarget: any, funcid: any) {
        // 只是一个处理数据的函数
        if (!Array.isArray(propertyData) || !Array.isArray(dayTarget)) {
          return [];
        }
        let baseArr: any = (propertyData && propertyData.slice(1)) || [];
        let tragetChart: any = [];

        let handleNumber = (val: any) => {
          return Number(val);
        };

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

        // 类型
        if (baseArr && baseArr.length > 0) {
          for (let i = 0; i < baseArr.length; i++) {
            let item = baseArr[i];
            item[1] = item[1] == "-9999" ? null : initNum[funcid](item[1]);
          }
        }

        if (
          baseArr.length &&
          dayTarget.length &&
          baseArr.length === dayTarget.length
        ) {
          for (let i = 0; i < dayTarget.length; i++) {
            let item = dayTarget[i];
            let time = "";
            item.time &&
              (time = item.time.slice(0, 2) + ":" + item.time.slice(2, 4));
            let initObj = {
              time: time,
              sales: baseArr[i][1],
            };
            tragetChart.push(initObj);
          }
        }
        return tragetChart;
      },
      checkIsData(data: any) {
        let tempArr: any = data.filter((item: any) => {
          return item === null;
        });
        if (data.length === tempArr.length) {
          return false;
        } else {
          return true;
        }
      },
      async formatOptios(funcid: any) {
        proxyData.activeItem.options = null;
        let { chartData, chartMax } = await proxyData.getData(funcid);
        proxyData.loadinngEnd();
        let seriesData: any = chartData.map((item: any) => {
          return item.sales;
        });
        let xData: any = chartData.map((item: any) => {
          return item.time;
        });
        let max: any = Math.max(...seriesData);
        if (xData && xData.length) {
          if (proxyData.checkIsData(seriesData)) {
            let options = {
              tooltip: {
                trigger: "axis",
              },
              grid: {
                top: 20,
                left: 5,
                right: 20,
                bottom: 20,
                containLabel: true,
              },
              xAxis: [
                {
                  type: "category",
                  boundaryGap: false,
                  axisLine: {
                    lineStyle: {
                      color: "#ECEFF4",
                    },
                  },
                  axisLabel: {
                    fontSize: 12,
                    interval: 8,
                    showMaxLabel: true,
                    color: "#C4C4C4",
                  },
                  data: xData,
                },
              ],
              yAxis: [
                {
                  type: "value",
                  // max: chartMax,
                  axisTick: {
                    show: false,
                  },
                  axisLine: {
                    lineStyle: {
                      color: "#ECEFF4",
                    },
                  },
                  axisLabel: {
                    fontSize: 12,
                    color: "#C4C4C4",
                  },
                  splitLine: {
                    lineStyle: {
                      type: "dashed",
                      color: "#ECEFF4",
                    },
                  },
                },
              ],
              series: [
                {
                  markLine:
                  max && chartMax && max >= chartMax
                      ? {
                          symbol: "none",
                          data: [
                            {
                              name: "均线",
                              type: "max",
                              yAxis: chartMax,
                              lineStyle: {
                                normal: {
                                  color: "red",
                                  width: 2,
                                  type: "solid",
                                },
                              },
                            },
                          ],
                          label: {
                            normal: {
                              show: true,
                              position: "middle",
                              textStyle: {
                                fontSize: 12,
                                fontWeight: 600,
                              },
                            },
                          },
                        }
                      : {},
                  name: "CO₂",
                  type: "line",
                  smooth: true,
                  symbol: "circle",
                  symbolSize: 5,
                  showSymbol: false,
                  areaStyle: {
                    color: new (echarts as any).graphic.LinearGradient(
                      0,
                      1,
                      0,
                      0,
                      [
                        {
                          offset: 0,
                          color: "rgba(79, 128, 255, 0.1)",
                        },
                        {
                          offset: 1,
                          color: "rgba(79, 128, 255, 0.6)",
                        },
                      ],
                      false
                    ),
                    shadowColor: "rgba(79, 128, 255, 0.1)",
                    shadowBlur: 10,
                  },
                  itemStyle: {
                    color: "rgba(79, 128, 255, 1)",
                    borderColor: "rgba(79, 128, 255, 1)",
                    borderWidth: 12,
                  },
                  data: seriesData,
                },
              ],
            } as EChartsOption;
            proxyData.activeItem.options = options;
            proxyData.activeItem.showNowData = 0;
          } else {
            proxyData.activeItem.options = null;
            proxyData.activeItem.showNowData = 1;
          }
        } else {
          proxyData.activeItem.options = null;
          proxyData.activeItem.showNowData = 2;
        }
      },
      async formatTowOptions(funcid: any) {
        // debugger
        proxyData.activeItem.options = null;
        let funcidArr = funcid.split(",");
        // debugger
        let chartData1: any = await proxyData.getData(funcidArr[0]);
        let chartData2: any = await proxyData.getData(funcidArr[1]);
        proxyData.loadinngEnd();
        let xData: any = chartData1.map((item: any) => {
          return item.time;
        });
        let seriesData1: any = chartData1.map((item: any) => {
          return item.sales;
        });
        let seriesData2: any = chartData2.map((item: any) => {
          return item.sales;
        });
        let options = {
          tooltip: {
            trigger: "axis",
          },
          legend: {
            icon: "circle",
            itemWidth: 14,
            itemHeight: 5,
            itemGap: 20,
            data: ["温度", "湿度"],
            textStyle: {
              fontSize: 12,
              color: "#C4C4C4",
            },
          },
          grid: {
            top: 30,
            left: 5,
            right: 15,
            bottom: 20,
            containLabel: true,
          },
          xAxis: [
            {
              type: "category",
              boundaryGap: false,
              axisLine: {
                lineStyle: {
                  color: "#ECEFF4",
                },
              },
              axisLabel: {
                fontSize: 12,
                interval: 8,
                showMaxLabel: true,
                color: "#C4C4C4",
              },
              data: xData,
            },
          ],
          yAxis: [
            {
              name: "℃",
              type: "value",
              nameGap: 12, // y轴name与横纵坐标轴线的间距
              // nameLocation: "left", // y轴name处于y轴的什么位置
              nameTextStyle: {
                color: "#9FA9BC",
                padding : [0, 25, 0, 0],
                // margin : [5, 0, 0, -20],
              },
              axisTick: {
                show: false,
              },
              axisLine: {
                lineStyle: {
                  color: "#ECEFF4",
                },
              },
              axisLabel: {
                fontSize: 12,
                color: "#C4C4C4",
              },
              splitLine: {
                lineStyle: {
                  type: "dashed",
                  color: "#ECEFF4",
                },
              },
            },
            {
              name: "％  ",
              nameGap: 12, // y轴name与横纵坐标轴线的间距
              nameTextStyle: {
                color: "#9FA9BC",
                padding : [0, 0, 0, 40],
              },
              type: "value",
              axisTick: {
                show: false,
              },
              axisLine: {
                show: false,
                lineStyle: {
                  color: "#ECEFF4",
                },
              },
              axisLabel: {
                fontSize: 12,
                color: "#C4C4C4",
              },
              splitLine: {
                show: false,
              },
            },
          ],
          series: [
            {
              name: "温度",
              type: "line",
              smooth: true,
              symbol: "circle",
              symbolSize: 5,
              yAxisIndex: 0,
              showSymbol: false,
              lineStyle: {
                width: 1,
              },
              areaStyle: {
                color: new (echarts as any).graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: "rgba(79, 128, 255, 0.165)",
                    },
                    {
                      offset: 0.8,
                      color: "rgba(79, 128, 255, 0)",
                    },
                  ],
                  false
                ),
                shadowColor: "rgba(79, 128, 255,0.1)",
                shadowBlur: 10,
              },
              itemStyle: {
                color: "rgba(79, 128, 255, 1)",
                borderColor: "rgba(79, 128, 255, 1)",
                borderWidth: 12,
              },
              data: seriesData1,
            },
            {
              name: "湿度",
              type: "line",
              smooth: true,
              symbol: "circle",
              symbolSize: 5,
              showSymbol: false,
              yAxisIndex: 1,
              lineStyle: {
                width: 1,
              },
              areaStyle: {
                color: new (echarts as any).graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: "rgba(137,189,27, 0.3)",
                    },
                    {
                      offset: 0.8,
                      color: "rgba(137,189,27, 0.165)",
                    },
                  ],
                  false
                ),
                shadowColor: "rgba(79, 128, 255,0.1)",
                shadowBlur: 10,
              },
              itemStyle: {
                color: "rgb(137,189,27)",
                borderColor: "rgba(137,189,2,1)",
                borderWidth: 12,
              },
              data: seriesData2,
            },
          ],
        } as EChartsOption;
        if (xData && xData.length) {
          if (
            proxyData.checkIsData(seriesData1) ||
            proxyData.checkIsData(seriesData2)
          ) {
            proxyData.activeItem.options = options;
            proxyData.activeItem.showNowData = 0;
          } else {
            proxyData.activeItem.options = null;
            // 暂位配置服务时间
            proxyData.activeItem.showNowData = 1;
          }
        } else {
          proxyData.activeItem.options = null;
          // 暂位配置服务时间
          proxyData.activeItem.showNowData = 2;
        }
      },
      setMax(funcid: any = "", dayTarget: any) {
        let max = 0;
        switch (funcid) {
          case "CO2":
            for (let i = 0; i < dayTarget.length; i++) {
              if (dayTarget[i].co2Max) {
                max = dayTarget[i].co2Max;
              }
            }
            break;
          case "PM2d5":
            for (let i = 0; i < dayTarget.length; i++) {
              if (dayTarget[i].pm25Max) {
                max = dayTarget[i].pm25Max;
              }
            }
            break;
          case "HCHO":
            // max = dayTarget && dayTarget[0] && dayTarget[0].hchoMax;
            for (let i = 0; i < dayTarget.length; i++) {
              if (dayTarget[i].hchoMax) {
                max = dayTarget[i].hchoMax;
              }
            }
            break;
          case "RH":
            max = 0;
            break;
          case "Tdb":
            // max = dayTarget[0].temperatureMax;
            max = 0;
            break;
          default:
            break;
        }
        return max;
      },
    });
    watch(
      props,
      (newProps: any) => {
        proxyData.query = JSON.parse(JSON.stringify(newProps.query));
        proxyData.setActiveItem();
        proxyData.queryAllData();
        // 设置当前选中的tab
      },
      {
        deep: true,
        immediate: true,
      }
    );
    onMounted(() => {
      // proxyData.setActiveItem();
      // proxyData.queryAllData();
      // const route: any = useRoute();
      // if (route.query) {
      //   proxyData.query = route.query;
      //   // 设置当前选中的tab
      //   proxyData.setActiveItem();
      //   proxyData.queryAllData();
      // }
    });
    return {
      ...toRefs(proxyData),
    };
  },
});
</script>

<style lang="scss" scoped>
.detail-content {
  width: 100%;
  height: 100%;
  .title {
    padding-bottom: 14px;
    font-family: "PingFang SC";
    font-style: normal;
    font-weight: 500;
    font-size: 22px;
    line-height: 31px;
    color: #000000;
  }
}

.container-text {
  font-family: PingFang SC;
  padding-top: 17px;
  background: #fff;
  font-weight: 500;
  font-size: 16px;
  line-height: 22px;
  text-align: center;
  color: #000000;
  text-align: center;
}
.chart-box {
  width: 100%;
  height: 280px;
  padding-top: 10px;
  background: #fff;
}

.detail-desc {
  // padding: 0 15px;
  margin-top: 20px;
  padding-left: 15px;
  display: flex;

  .detail-title {
    display: inline-block;
    margin-right: 22px;
    vertical-align: middle;
    width: 64px;
    height: 85px;
    line-height: 85px;
    text-align: center;
    background: #fff;
    border-radius: 5px;
    font-size: 18px;
    align-items: center;
    text-align: center;
    color: #140050;
  }

  .detail-text {
    flex: 86px 1;
    display: inline-block;
    font-family: PingFang SC;
    color: #4d5262;
    vertical-align: middle;

    p {
      position: relative;
      margin-bottom: 10px;
      // padding-bottom: 10px;
    }

    .icon {
      position: absolute;
      top: 7px;
      left: 0;
      display: inline-block;
      vertical-align: middle;
      font-size: 12px;
    }

    .circle {
      display: inline-block;
      vertical-align: middle;
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background: $elCircle;
    }
    .tem-span {
      display: inline-block;
      vertical-align: middle;
      padding-bottom: 5px;
      font-style: normal;
      font-weight: 400;
      font-size: 13px;
      line-height: 20px;
      color: #646c73;
      padding-left: 15px;
    }
  }
}

.detail-bottom {
  padding: 0 15px;
  padding-bottom: 30px;
  padding-top: 40px;
  width: 100%;
  font-weight: 500;
  font-size: 14px;
  line-height: 12px;
  color: #140050;

  .text-img {
    width: 100%;
    padding-top: 20px;

    img {
      width: 100%;
      margin: 0 auto;
    }
  }
}
</style>
<style lang="scss">
.detail-content {
  .van-tabs__content {
    width: 100%;
    //height: 280px;
    //padding-left: 22px;
    //padding-right: 22px;
    //padding-top: 10px;
  }

  .van-tab__panel {
    width: 100%;
    height: 100%;
  }

  .van-tabs__line {
    display: none;
  }

  .van-tab__text {
    display: inline-block;
    padding: 3px;
    // font-size: 16px;
    color: #c4c4c4;
    width: 100%;
    height: 100%;
    line-height: 44px;
    text-align: center;
    font-style: normal;
    font-weight: 700;
    font-size: 14px;
  }

  .van-tab--active {
    .van-tab__text {
      color: #fff;
      background: #ffffff;
      border-radius: 4px;
      color: $elActiveColor;
      // background: $elActiveColor;
    }
  }

  .van-tabs__wrap {
    // position: fixed;
    padding: 2px;
    width: 100%;
    height: 50px;
    border-radius: 4px;
    //top: 48px;
    top: 0;
    background: #f2f3f5;
    left: 0;
    z-index: 333;
  }

  .van-tabs__nav--line {
    background: #f2f3f5;
    border-radius: 4px;
  }

  .van-tabs__content {
    //padding-top: 42px;
    //padding-top: 10px;
  }
}
</style>
