<template>
  <div class="table-box">
    <div class="card table-search" style="overflow: hidden;">
      <el-form ref="formRef" :model="pageable" :inline="true" label-width="auto">
        <el-form-item label="所属基地：" prop="base">
          <el-select v-model="pageable.base" placeholder="请选择" style="width: 200px" @change="changeBase">
            <el-option v-for="item in baseList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button plain @click="resetQuery">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="main_list ">
      <el-row :gutter="15">
        <el-col :xs="24" :sm="12" :md="8" :lg="8">
          <div class="chart_item zhuti">
            <div style="font-weight: bold;" class="item_title">
              <span>设备工况(单位:台)</span>
            </div>
            <div class="mt5">
              <div ref="device" class="ve-ring" style="height: 200px" v-if="stateList"></div>
              <div v-else
                style="height: 200px; display: flex; justify-content: center; align-items: center; font-size: 20px;">
                暂无数据</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="8">
          <div class="chart_item zhuti">
            <div style="font-weight: bold;" class="item_title">
              <span>检定周期(单位:台)</span>
            </div>
            <div class="mt5">
              <div ref="period" class="ve-ring" style="height: 200px"></div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="8">
          <div class="chart_item zhuti">
            <div style="font-weight: bold;" class="item_title">
              <span>FTP链路</span>
            </div>
            <div class="mt5">
              <div class="FTP_box" style="height: 200px">
                <div class="FTP_item">
                  <img src="@/assets/images/centerStation.png" alt="">
                  <div>正常FTP({{ FTPList && FTPList.true ? FTPList?.true.length : 0 }})</div>
                </div>
                <div class="FTP_item" @click="gotoFTP">
                  <img src="@/assets/images/areaStation.png" alt="">
                  <div>异常FTP({{ FTPList && FTPList.false ? FTPList?.false.length : 0 }})</div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="24">
          <div class="chart_item zhuti">
            <div style="font-weight: bold;" class="item_title">
              <span>危险天气</span>
            </div>
            <el-row :gutter="15">
              <el-col :span="8">
                <div class="mt5">
                  <div ref="weather" class="ve-ring" style="height: 300px"></div>
                </div>
              </el-col>
              <el-col :span="16" style="margin-bottom: 0;">
                <div>
                  <div ref="element" class="ve-ring" style="height: 300px"></div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="24">
          <div class="chart_item zhuti">
            <div style="font-weight: bold;" class="item_title">
              <span>到报监控</span>
            </div>
            <div class="mt5">
              <div ref="control" class="ve-ring" style="height: 300px"></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts" name="allDevice">
import * as echarts from 'echarts';
import { getStamp, groupByType, getNextDayMidnight } from "@/utils/dateTime";
import { ElMessage } from "element-plus";
import { useGlobalStore } from "@/stores/modules/global";
import { ref, computed, onMounted, reactive, watch, onDeactivated, onActivated, nextTick } from "vue";
import { getTacRecordList, getFTPList, getCertificateList, getStaitemList, getArriveList } from "@/api/modules/allData";
import { Platform } from "@/api/interface";
import { parseTime } from '@/utils/index';
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
const router = useRouter();
const gotoFTP = () => {
  router.push({
    path: '/system/disposition',
    query: {
      status: 'distributionAutomatic',
    }
  })
}
// 查询自动站列表
const queryas = ref<Platform>({
  pageSize: 5000,
  pageNum: 1,
  currentpage: 1
})
const pageable = ref({
  data_type: true,
  time_order: 1,
  time_space: 1,
  base: undefined,
  as_code_list: [],
  data_items: [
    {
      data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
      data_id: 101,
      data_type: "温湿度",
      data_item: "QI_WEN",
      data_name: "气温",
      data_unit: "℃",
      data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
      data_value: "",
      data_order: 1,
      data_condition: 0
    }
  ],
});

const userStore = useUserStore();
const platformList = ref<any>(computed(() => userStore.stations))
const baseList = ref<any>([])
const selectPlatform = ref()

const getPlatforms = async () => {
  baseList.value = groupByType(platformList.value)

  pageable.value.base = baseList.value[0].value
  pageable.value.as_code_list = baseList.value[0].children
  selectPlatform.value = baseList.value[0]
  // getDeviceStatus()
  // getArrive()
  // getHistoryList()

};
const resetQuery = () => {

  pageable.value.base = baseList.value[0].value
  pageable.value.as_code_list = baseList.value[0].children
  handleSearch()

};

const changeBase = (e) => {
  const item = baseList.value.find(item => item.value === e);
  pageable.value.as_code_list = item.children

  // getCertificate()
  // getFTP()
  // getDeviceStatus()
  // getArrive()
  // getHistoryList()
}
watch(() => pageable.value.as_code_list, (newValue, oldValue) => {
  if (newValue) {
    weatherInfo();
    getCertificate();
    getFTP();
    getDeviceStatus();
    getArrive();
    // getHistoryList();
  }
});

const formRef = ref()
const device = ref()
const period = ref()
const weather = ref()
const element = ref()
const control = ref()

// 获取到报监控
const arriveList = ref<any>({ aa: [], bb: [], cc: [] })
const arriveTime = ref<any>()
const getArrive = async () => {
  const { data } = await getArriveList({ ...pageable.value, time_space: 60, data_type: false, end_time: getStamp(parseTime(new Date(), '{y}-{m}-{d} {h}') + ':01'), begin_time: getStamp(parseTime(new Date(), '{y}-{m}-{d}') + ' 01:00') })
  // 提取键并排序
  const sortedKeys = Object.keys(data).sort((a, b) => {
    const [timeA] = a.split(':').map(Number);
    const [timeB] = b.split(':').map(Number);
    return timeA - timeB;
  });

  // 根据排序后的键构建新对象
  const sortedObj = {};
  sortedKeys.forEach(key => {
    sortedObj[key] = data[key];
  });

  arriveTime.value = Object.keys(sortedObj)

  const arr = <any>{ aa: [], bb: [], cc: [] }
  arriveTime.value?.forEach((item, index) => {
    arr.aa.push(pageable.value.as_code_list.length)
    arr.bb.push(data[item].length)
    arr.cc.push(pageable.value.as_code_list.length - data[item].length)
  });
  arriveList.value = arr

  nextTick(() => {
    showControl()
  })
};



const wertherColumns = ref<any>({
  tact_state_on: true,
  tact_data_on: false,
  tact_state: 0,
  // tact_state: 0,
  // tact_data: 0,
  pageNum: 1,
  pageSize: 999,

});


const weatherInfoArr = ref()
const dangetWeatherNum = ref(0)
const weatherNormal = ref()
const weatherWarning = ref()
const weatherInfo = async () => {
  const { data } = await getTacRecordList({ ...wertherColumns.value, as_code_list: pageable.value.as_code_list });
  dangetWeatherNum.value = [...new Set(data.list?.map(obj => obj.as_code))].length
  weatherInfoArr.value = data.list

  let arr2 = new Array(8).fill(0);
  let arr1 = new Array(8).fill(pageable.value.as_code_list.length);

  data.list?.forEach((item, index) => {
    arr1[item.data_type]--
    arr2[item.data_type]++
  })
  weatherNormal.value = arr1
  weatherWarning.value = arr2

  nextTick(() => {
    showWeather()
    showElement()
  })
};

// 获取自动站定检证书
// 返回两个数组中相同的个数
function findCommonCount(arr1, arr2) {
  const common = arr1.filter(item => arr2.includes(item));
  return common.length;
}
const certificateList = ref<any>({})
const getCertificate = async () => {

  const { data } = await getCertificateList()
  // certificateList.value.a = data[0]?.length || 0
  certificateList.value.a = findCommonCount(pageable.value.as_code_list, data[0]?.length ? data[0] : [])
  certificateList.value.b = findCommonCount(pageable.value.as_code_list, data[1]?.length ? data[1] : [])
  certificateList.value.c = findCommonCount(pageable.value.as_code_list, data[2]?.length ? data[2] : [])

  nextTick(() => {
    showPeriod()
  })
  // certificateList.value=data.list
};

// 获取FTP链路
const FTPList = ref<any>({})
const getFTP = async () => {
  const { data } = await getFTPList()
  FTPList.value = data
};

// 获取设备工况 stateList（用于存储设备状态）、getDeviceStatus（存储设备状态）
const stateList = ref<any>()
const getDeviceStatus = async () => {
  const { data } = await getStaitemList(pageable.value);
  const state = { normal: [], warning: [], error: [] }

  data?.list?.forEach(item => {
    const staList = item.sta_list;
    staList.forEach(sta => {
      if (sta.state === 0) {
        if (!state.normal.includes(item.as_code)) {
          state.normal.push(item.as_code);
        }
        // state.normal++;
      } else if (sta.state === 2) { // 注意：你的要求中提到了state为2的个数，但原始数据中并没有state为2的例子，这里我假设你需要统计它  
        if (!state.warning.includes(item.as_code)) {
          state.warning.push(item.as_code);
        }
        // state.warning++;
      } else if (sta.state === 3) {
        if (!state.error.includes(item.as_code)) {
          state.error.push(item.as_code);
        }
        // state.error++;
      }
    });
  });
  state.normal=state.normal?.filter(item => !state.error?.includes(item)); //过滤正常状态设备，删除掉异常状态的设备代码

  stateList.value = state
  nextTick(() => {
    showDevice()
  })
};

const handleSearch = () => {
  getArrive()
  weatherInfo()
  getCertificate()
  getFTP()
  getDeviceStatus()
}



const globalStore = useGlobalStore();
const isDark = computed(() => globalStore.isDark);

const showDevice = () => {


  let mychart = echarts.init(device.value);
  let option = {
    tooltip: {
      trigger: 'item',
      formatter:function(params) {
        return `<div>${params.name}：${params.value}台</div>`;
      }
    },
    legend: {
      bottom: '0%',
      left: 'center',
      textStyle: {//图例文字的样式
        color: isDark.value ? '#fff' : "#000",
      }
    },
    series: [
      {
        name: '设备工况',
        type: 'pie',
        radius: ['50%', '68%'],
        center: ['50%', '45%'],
        hoverAnimation: false,
        itemStyle: {
          borderRadius: 3,
          borderColor: '#fff',
          borderWidth: 1
        },
        label: {
          normal: {
            show: true,
            position: 'outer',
            formatter: '{b}：{c}',
            overflow: 'none',
            fontSize: 15,
          },
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        //设置提示线
        labelLine: {
          normal: {
            show: true,//开启提示线展示
            length: 10,//设置第一条提示线长度
            length2: 30,//设置第二条提示线长度

          }
        },

        data: [
          {
            value: stateList.value ? stateList.value.normal.length : 0,
            name: '正常',
            list: stateList.value ? stateList.value.normal : [],
            itemStyle: { color: '#00C4B3' },
            label: { color: '#00C4B3' }
          },
          {
            value: stateList.value ? stateList.value.warning.length : 0,
            name: '告警',
            list: stateList.value ? stateList.value.warning : [],
            itemStyle: { color: '#EF6666' },
            label: { color: '#EF6666' }
          },
          {
            value: stateList.value ? stateList.value.error.length : 0,
            name: '故障',
            list: stateList.value ? stateList.value.error : [],
            itemStyle: { color: '#FAC858' },
            label: { color: '#FAC858' }
          }
        ]
      }
    ]
  };
  mychart.setOption(option)
  window.addEventListener("resize", function () {
    mychart.resize();
  });
}
const showPeriod = () => {
  let mychart = echarts.init(period.value);
  let option = {
    tooltip: {
      trigger: 'item',
      formatter: "{a} <br/>{b}: {c}台"

    },
    legend: {
      bottom: 0,
      left: 'center',
      textStyle: {//图例文字的样式
        color: isDark.value ? '#fff' : "#000",
      }
    },
    series: [
      {
        name: '检定周期',
        type: 'pie',
        radius: '65%',
        center: ['50%', '45%'],
        label: {
          normal: {
            show: true,
            position: 'outer',
            formatter: '{b}：{c}',
            fontSize: 14,
          },
        },

        data: [
          { value: certificateList.value.c ? certificateList.value.c : 0, name: '剩余31-60天', itemStyle: { color: '#5470C6' } },
          { value: certificateList.value.b ? certificateList.value.b : 0, name: '剩余1-30天', itemStyle: { color: '#FAC858' } },
          { value: certificateList.value.a ? certificateList.value.a : 0, name: '已过检', itemStyle: { color: '#EF6666' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  mychart.setOption(option)
  window.addEventListener("resize", function () {
    mychart.resize();
  });
}

const allSataion = ref(5)
const showWeather = () => {
  let mychart = echarts.init(weather.value);
  let option = {
    title: {
      text: `${pageable.value.as_code_list.length} \n 总站数 `,
      left: "center",
      top: "38%",
      textStyle: {
        fontSize: 20,
        color: '#000',
      },
    },
    tooltip: {
      trigger: 'item',
      formatter: "{a} <br/>{b}: {c}"
    },
    legend: {
      bottom: '1%',
      left: 'center',
      textStyle: {//图例文字的样式
        color: isDark.value ? '#fff' : "#000",
      }
    },
    series: [
      {
        name: '天气状况',
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['50%', '45%'],
        hoverAnimation: false,
        itemStyle: {
          borderRadius: 3,
          borderColor: '#fff',
          borderWidth: 1
        },
        label: {
          normal: {
            show: true,
            position: 'outer',
            formatter: '{b}：{c}',
            overflow: 'none',
            fontSize: 15,
          },
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        //设置提示线
        labelLine: {
          normal: {
            show: true,//开启提示线展示
            length: 15,//设置第一条提示线长度
            length2: 30,//设置第二条提示线长度

          }
        },

        data: [
          {
            value: pageable.value.as_code_list.length - dangetWeatherNum.value,
            name: '正常',
            itemStyle: { color: '#5470C6' },
            label: { color: '#5470C6' }
          },
          {
            value: dangetWeatherNum.value,
            name: '告警',
            itemStyle: { color: '#EF6666' },
            label: { color: '#EF6666' }
          }
        ]
      }
    ]
  };
  mychart.setOption(option)
  window.addEventListener("resize", function () {
    mychart.resize();
  });
}

const showElement = () => {
  let mychart = echarts.init(element.value);
  let option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      top: '3%',
      left: '3%',
      right: '4%',
      bottom: '0%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: [
          '能见度',
          '风速',
          '大气电场',
          '云量',
          '云高',
          '温度',
          '湿度',
          '小时雨量'
        ]
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '正常',
        barWidth: '50%',
        type: 'bar',
        stack: 'Ad',
        emphasis: {
          focus: 'series'
        },
        itemStyle: {
          color: '#5470C6'
        },
        data: weatherNormal.value
      },
      {
        name: '告警',
        barWidth: '50%',
        type: 'bar',
        stack: 'Ad',
        emphasis: {
          focus: 'series'
        },
        itemStyle: {
          color: '#EF6666'
        },
        data: weatherWarning.value
      }
    ]
  };

  mychart.setOption(option)
  window.addEventListener("resize", function () {
    mychart.resize();
  });
}

const showControl = () => {
  let mychart = echarts.init(control.value);
  let option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      textStyle: {//图例文字的样式
        color: isDark.value ? '#fff' : "#000",
      }
    },
    grid: {
      left: '15',
      right: '15',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: arriveTime.value
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [

      {
        name: '应报情况',
        type: 'bar',
        stack: 'Ad',
        emphasis: {
          focus: 'series'
        },
        itemStyle: {
          color: '#3BA272' // 蓝色
        },
        data: arriveList.value.aa.length ? arriveList.value.aa : [],
      },
      {
        name: '实报情况',
        type: 'bar',
        stack: 'Ad',
        emphasis: {
          focus: 'series'
        },
        itemStyle: {
          color: '#5470C6' // 绿色
        },
        data: arriveList.value.bb.length ? arriveList.value.bb : [],
      },
      {
        name: '未报情况',
        type: 'bar',
        stack: 'Ad',
        emphasis: {
          focus: 'series'
        },
        itemStyle: {
          color: '#EF6666' // 红色
        },
        data: arriveList.value.cc.length ? arriveList.value.cc : [],
      },

    ]
  };

  mychart.setOption(option)
  window.addEventListener("resize", function () {
    mychart.resize();
  });
}
watch(isDark, () => { showDevice(), showPeriod(), showWeather(), showElement(), showControl() });

onMounted(() => {
  // getFTP()
  // getCertificate()
  getPlatforms()
  // showDevice()
  // showPeriod()
  // showWeather()
  // showElement()
  // showControl()
})
let intervalId;

onActivated(() => {
  intervalId = setInterval(() => {
    // getList();
    weatherInfo()
    getCertificate();
    getFTP();
    getDeviceStatus();
    getArrive();
  }, 60 * 1000);
});

onDeactivated(() => {
  clearInterval(intervalId);
});
</script>
<style scoped lang="scss">
.el-row .el-col {
  margin-bottom: 15px;
}

.main_list {
  background: transparent !important;
  box-shadow: none !important;
  padding: 0 !important;
  height: calc(100vh - 150px);
  margin-bottom: 10px;
  overflow-y: scroll;
  overflow-x: hidden;


  .chart_item {
    border-radius: 10px;
    padding: 10px;
    background-color: #fff;
    // height: 100%;
    // margin-bottom: 15px;


    .item_title {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .FTP_box {
      padding: 0 50px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .FTP_item {
        flex: 1;
        flex-shrink: 0;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        img {
          width: 56px;
          margin-bottom: 20px;
        }
      }

    }
  }

  .info_box {
    .info_title {
      color: #999999;
      font-size: 16px;
    }

    .info_content {
      height: 40px;
      font-weight: bold;
      color: #000;
      font-size: 26px;
    }
  }

}
</style>
