<template>
  <div>
    <Title title="气象预警">
      <template v-slot:title-slot>
              <div class="slot-right">
                <!-- <div class="btn yse-events" @click="toPage">气象详情</div> -->
                <div class="btn yse-events" @click="gybg">果园报告</div>
              </div>
      </template>
    </Title>
    <div class="content-box">
      <div class="info">
        <div class="weather">
          <div class="temperature">
            <i :class="['qi-'+nowWeather.iconDay]"></i>
            <span>{{nowWeather.maxTemp}}℃</span>
          </div>
          <div class="txt">
            <span>{{nowWeather.textDay}}</span><br />
            <span>湿度:{{nowWeather.humidity}}％</span>
          </div>
        </div>
        <div class="desc">
          <div
              class="desc-item"
              v-for="(item, index) in warningItems"
              :key="index"
              v-html="index + 1 + '、'+ item.desc"
          >
          </div>
        </div>
      </div>
      <div ref="chartDom" class="charts yse-events"></div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref, onBeforeUnmount } from "vue";
import { useStore } from "vuex";
import * as echarts from "echarts";
import Title from "../../../components/title";
import {useRouter} from "vue-router";
import {dateFormat} from "../../../../utils/date_util"
import {base_img_url} from "../../../../api/config"
const router = useRouter();

let emit =defineEmits(["gybg"])

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

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

const getters = useStore().getters;
const curGardenId = ref(getters.userinfo.curGardenId);
let chartDom = ref(null);
let myChart = null;

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

const toPage = () =>{
  router.push('/weatherDetails')
}
const gybg = ()=>{
  emit("gybg",gybgFilename.value)
}

const options = {
  tooltip: {
    trigger: "axis",
    triggerOn: "click",
    backgroundColor: "#CB5D23",
    borderColor: "#CB5D23",
    textStyle: {
      color: "#FFF",
    },
    formatter: "{c1}℃-{c0}℃",
    padding: [2, 5],
    axisPointer: {
      type: "none", // 设置为'none'以去除指示线
    },
  },
  grid: {
    top: "6%",
    left: "1%",
    right: "3%",
    bottom: "5%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    boundaryGap: false,
    data: [],
    axisLabel: {
      margin: 12,
      color: "#fff",
    },
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
      length: 25,
      lineStyle: {
        color: "#ffffff1f",
      },
    },
    splitLine: {
      show: true,
      lineStyle: {
        color: "#ffffff1f",
      },
    },
  },
  yAxis: [
    {
      type: "value",
      max: 40,
      axisLabel: {
        margin: 12,
        color: "#fff",
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: "#ffffff1f",
        },
      },
      axisLine: {
        lineStyle: {
          color: "#fff",
          width: 2,
        },
      },
    },
  ],
  series: [
    {
      name: "注册总量",
      type: "line",
      smooth: true, //是否平滑曲线显示
      showAllSymbol: true,
      symbol: "circle",
      symbolSize: 0,
      lineStyle: {
        normal: {
          color: "rgba(0,0,0,0)", // 线条颜色
        },
      },
      itemStyle: {
        borderWidth: 6,
        borderColor: "#F46719",
      },
      areaStyle: {
        normal: {
          color: new echarts.graphic.LinearGradient(
              0,
              0.2,
              0,
              1,
              [
                {
                  offset: 0,
                  color: "#ea0521",
                },
                {
                  offset: 0.4,
                  color: "rgba(242, 208, 130, 0.5)",
                },
                {
                  offset: 0.6,
                  color: "rgba(242, 208, 130, 0.2)",
                },
                {
                  offset: 0.8,
                  color: "rgba(242, 208, 130, 0.1)",
                },
                {
                  offset: 1,
                  color: "rgba(242, 208, 130, 0.1)",
                },
              ],
              false
          ),
        },
      },
      data: [],
    },
    {
      name: "注册总量",
      type: "line",
      smooth: true, //是否平滑曲线显示
      showAllSymbol: true,
      symbol: "circle",
      symbolSize: 0,
      lineStyle: {
        normal: {
          color: "rgba(0,0,0,0)", // 线条颜色
        },
      },
      itemStyle: {
        borderWidth: 6,
        borderColor: "#F46719",
      },
      areaStyle: {
        normal: {
          color: new echarts.graphic.LinearGradient(
              0,
              0.2,
              0,
              1,
              [
                {
                  offset: 0,
                  color: "#F46719",
                },
                {
                  offset: 0.4,
                  color: "rgba(242, 208, 130, 0.5)",
                },
                {
                  offset: 0.6,
                  color: "rgba(242, 208, 130, 0.2)",
                },
                {
                  offset: 0.8,
                  color: "rgba(242, 208, 130, 0.1)",
                },
                {
                  offset: 1,
                  color: "rgba(242, 208, 130, 0.1)",
                },
              ],
              false
          ),
        },
      },
      data: [],
    },
  ],
};

const warningItems = ref([]);
const nowWeather = ref({});
const gybgFilename = ref({})

const initData = async () => {
  const { code, data } = await VE_API.znxy.weatherWarning({
    gardenId: curGardenId.value,
  });
  for(let i=0;i < data.warningItems.length;i++){
    data.warningItems[i].desc = data.warningItems[i].desc.replace("存在的","")
  }
  warningItems.value = data.warningItems;
  getNowWeather(data.data)
  initTempGybgPdf()
  options.xAxis.data = data.data.map((item) => formatDate(item.date));
  options.series[0].data = data.data.map((item) => item.maxTemp);
  options.series[1].data = data.data.map((item) => item.minTemp);
  myChart.clear();
  options && myChart.setOption(options);
};

const initTempGybgPdf = ()=>{
  VE_API.temp_garden_report_pdf.get({id:curGardenId.value}).then(({data,code})=>{
    if(code == 0){
      gybgFilename.value = data.filename
    }
  })
}

function getNowWeather(data){
  let now = new Date()
  let str = dateFormat(now,"YY-mm-dd")
  nowWeather.value = data.find((item)=> item.date == str)
  console.log(nowWeather.value)
}

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>
.slot-right {
  width: 70%;
  box-sizing: border-box;
  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, 0.8);
    font-weight: bold;
    font-size: 15px;
    width: 92px;
    height: 32px;
    text-align: center;
    line-height: 32px;
  }
}
.content-box {
  width: 100%;
  height: calc(100% - 48px);
  padding: 8px 11px;
  box-sizing: border-box;
  color: #FFFDFD;
  .info {
    display: flex;
    justify-content: space-between;
    .weather{
      display: flex;
      align-items: center;
      width: 50%;
      .temperature{
        display: flex;
        align-items: center;
        margin-right: 10px;
        i{
          width: 38px;
          height: 38px;
          font-size: 30px;
        }
        span{
          font-weight: bold;
          font-size: 38px;
        }
      }
    }
  }
  .desc {
    width: 50%;
    font-size: 12px;
    height: 45px;
    font-weight: bold;
    overflow: hidden;
    // text-overflow: ellipsis;
    // display: -webkit-box;
    // -webkit-box-orient: vertical;
    // -webkit-line-clamp: 5; /* 设置显示的行数 */
    background: url("@/assets/img/znxy/qxyj_bg.png") no-repeat center center /
      100% 100%;
    box-sizing: border-box;
    padding: 5px;
  }
  .charts {
    width: 100%;
    height: calc(100% - 44px);
  }
}
</style>
