<template>
  <div>
    <Title title="病虫异常">
      <template v-slot:title-slot>
        <div class="slot-right">
          <div class="btn yse-events">异常复盘</div>
          <div class="btn yse-events">预警详情</div>
        </div>
      </template>
    </Title>
    <div class="content-box">
      <div class="box-header">
        {{content}}
      </div>
      <div ref="chartDom" class="box-echars"></div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, reactive, toRefs, ref ,onBeforeUnmount} from "vue";
import { useStore } from "vuex";
import * as echarts from "echarts";
import Title from "../../../components/title";

const getters = useStore().getters;
const curGardenId = ref(getters.userinfo.curGardenId);

// 在组件或全局监听器中监听自定义事件
function handleStorageUpdate(e) {  
    curGardenId.value = e.detail
    initData()
} 
// 在组件或全局监听器中监听自定义事件
window.addEventListener('storageChanged', handleStorageUpdate); 

// 组件销毁前移除监听
onBeforeUnmount(()=>{
  window.removeEventListener('storageChanged', handleStorageUpdate);
})

const active = ref(0);

const handleAct = (e) => {
  active.value = e;
  initList(active.value);
};

let chartDom = ref(null);
let myChart = null;

onMounted(() => {
  myChart = echarts.init(chartDom.value);
  myChart.setOption(options);
  initData();
});

const colors = [
  {
    offset: 0.25,
    color: "rgba(252, 186, 138, 0.4)",
  },
  {
    offset: 0.5,
    color: "rgba(43, 202, 207, 0.4)",
  },
  {
    offset: 0.75,
    color: "rgba(26, 134, 137, 0.4)",
  },
  {
    offset: 1,
    color: "rgba(26, 134, 137, 0.4)",
  },
];

const options = {
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow",
      shadowStyle: {
        color: {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "rgba(210, 73, 83, 0)" },
            { offset: 0.5, color: "rgba(210, 73, 83, 0.5)" },
            { offset: 1, color: "rgba(210, 73, 83, 0)" },
          ],
          global: false,
        },
      },
    },
  },
  legend: {
    orient: "vertical",
    data: ["预测态势"],
    //图例文字样式
    textStyle: {
      color: "#fff",
      fontSize: "11px",
    },
    align: "left",
    right: "2.4%",
    top: "-3%",
    icon:'rect',
    itemGap: 5,
    itemWidth: 20,
    itemHeight: 8,
  },
  grid: {
    top: "19%",
    left: "1%",
    right: "4%",
    bottom: "5%",
    containLabel: true,
  },
  xAxis: [
    {
      type: "category",
      data: [],
      axisLine: {
        show: false,
        lineStyle: {
          color: "#f4f4f4",
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: "#ffffff1f",
        },
      },
      axisTick: {
        show: false,
        alignWithLabel: true,
      },
      axisLabel: {
        interval: 0,
        textStyle: {
          color: "#fff",
        },
        // 默认x轴字体大小
        fontSize: 12,
        align: "center",
      },
      boundaryGap: false,
    },
  ],
  yAxis: [
    {
      name: "百分比/％",
      nameTextStyle: {
        color: "#fff",
        fontSize:'11'
      },
      type: "value",
      max: 100,
      axisTick: {
        show: false,
      },
      axisLabel: {
        textStyle: {
          color: "#fff",
        },
      },
      // 分割线
      splitLine: {
        show: true,
        lineStyle: {
          color: "#ffffff1f",
        },
      },
    },
    {
      type: "value",
      show: false,
      max: 40,
    },
  ],
  series: [
    {
      name: "预测态势",
      type: "line",
      data: [],
      symbol: "none",
      itemStyle: {
        color: "#2BCACF",
        borderWidth: 1,
      },
      yAxisIndex: 0,
      areaStyle: {
        normal: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, colors, false),
        },
      },
      lineStyle: {
        width: 0,
      },
    },
    // {
    //   name: "预测态势",
    //   type: "line",
    //   data: [],
    //   symbol: "emptyCircle",
    //   symbolSize: 3,
    //   showSymbol: false,
    //   itemStyle: {
    //     color: "red",
    //   },
    //   yAxisIndex: 1,
    //   lineStyle: {
    //     width: 1,
    //     color: "#FF5358", //改变折线颜色
    //     type: "dashed",
    //   },
    // },
  ],
};

const title = ref("");
const content = ref("")
const dataInfo = ref([]);

const initData = async () => {
  const { code, data } = await VE_API.znxy.pestAbnormal({ gardenId: curGardenId.value });
  if (data.length < 1) {
    myChart.clear();
    content.value = '';
  } else {
    dataInfo.value = data;
    initList(active.value);
    myChart.clear();
    options && myChart.setOption(options);
  }
};

function initList(index) {
  title.value = dataInfo.value[index].title;
  content.value = dataInfo.value[index].content;
  options.xAxis[0].data = dataInfo.value[index].data.map((item) =>
    formatDate(item.date)
  );
  options.series[0].data = dataInfo.value[index].data.map((item) =>
    item.forecast
  );
  // options.series[1].data = dataInfo.value[index].data.map((item) =>
  //   item.forecast.slice(0, 2)
  // );
}

function formatDate(dateString) {
  // 确保输入字符串是有效的
  const regex = /^\d{4}-\d{2}-\d{2}$/;
  if (!regex.test(dateString)) {
    return "Invalid date format";
  }

  const parts = dateString.split("-");
  const year = parseInt(parts[0], 10);
  const month = parseInt(parts[1], 10) - 1; // 注意月份是从0开始的
  const day = parseInt(parts[2], 10);

  // 创建Date对象
  const date = new Date(year, month, day);

  // 提取月份和日期并格式化输出
  const monthFormatted = String(date.getMonth() + 1); // 使用padStart来确保总是两位数
  const dayFormatted = String(date.getDate()).padStart(2, "0");

  return `${monthFormatted}/${dayFormatted}`;
}
</script>

<style lang="scss" scoped>
.content-box {
  width: 100%;
  height: calc(100% - 48px);
  padding: 8px 11px;
  box-sizing: border-box;
  .box-header {
    width: 100%;
    height: 45px;
    padding: 5px;
    box-sizing: border-box;
    font-weight: bold;
    color: #FFFDFD;
    font-size: 12px;
    background: url("@/assets/img/znxy/qxyj_bg.png") no-repeat center center /
      100% 100%;
    .box-title {
      background-image: url("@/assets/img/znxy/yc_title_bg.png");
      background-repeat: no-repeat;
      background-size: 100% 100%;
      width: 156px;
      height: 100%;
      line-height: 32px;
      text-align: center;
      .name {
        color: #edcb42;
      }
    }
    .text {
      text-align: center;
      line-height: 30px;
      font-weight: 400;
      color: #b4fffb;
    }
    .btn {
      cursor: pointer;
      background-image: url("@/assets/img/tabs_btn3.png");
      background-repeat: no-repeat;
      background-size: 100% 100%;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(180, 255, 251, 0.6);
      width: 124px;
      height: 30px;
    }
  }

  .box-echars {
    width: 100%;
    height: calc(100% - 45px);
  }
}

.slot-time {
  color: #fff;
  font-size: 15px;
  color: #fe4444;
  width: 50%;
}

.slot-right {
  width: 70%;
  cursor: pointer;
  display: flex;
  flex-direction: row;
  justify-content: right;
  align-items: center;
  padding-right: 12px;
  .btn {
    cursor: pointer;
    background: url("@/assets/img/tabs_btn3.png") no-repeat center center /
      100% 100%;
    margin-right: 5px;
    color: rgba(180,255,251,.8);
    font-weight: bold;
    font-size: 15px;
    width: 92px;
    height: 32px;
    text-align: center;
    line-height: 32px;
  }
}
</style>
