<!-- SidePanelItem.vue -->
<template>
  <div>
    <SidePanelItem title="生态流量达标情况" :click-action="{ show: true }">
      <!-- 使用插槽自定义点击提示的内容 -->
      <template #click-action-content>
        <div v-if="titleData.cnt" style="max-width: 300px; line-height: 1.6">
          <p>
            1、统计电站范围：接入过生态流量数据的电站
            <span
              style="color: #5989ad; cursor: pointer; "
              @click.stop="handleStationClick()"
            >
             ({{titleData.cnt}})
            </span>
          </p>
          <p>2、当来水不足时，生态流量不小于入库流量判定为达标</p>
          <p>3、“≥95%座数”表示统计电站范围内时段达标率大于等于95%的电站数量</p>
        </div>
      </template>

      <div class="body_topOne">
        <a-radio-group v-model:value="mode" @change="dataChage">
          <a-radio-button value="hour">逐时</a-radio-button>
          <a-radio-button value="day">日</a-radio-button>
        </a-radio-group>
        <div class="title_text">≥95%座数/总座数</div>
      </div>
      <a-spin :spinning="spinning">
        <div>
          <div v-for="el in datalist" @click="handleBarClick(el)">
            <div :key="el.key">
              <div class="boy_one">
                <div style="flex: 1; white-space: nowrap; margin-right: 5px">
                  {{ el.name }}
                </div>
                <img style="flex: 1" src="@/assets/components/fgx.svg" alt="" />
              </div>
              <div class="body_zhu">
                <div class="body_biao">
                  <div v-for="value in allArr">
                    <div :key="value" class="nei_body">
                      <div
                        v-if="
                          value <
                          (el?.key == null
                            ? 1
                            : el.qecTCnt == 0
                            ? 0
                            : el.qecCnt / el.qecTCnt) *
                            20
                        "
                        class="little_body"
                        :style="{ backgroundColor: el.color }"
                      ></div>
                    </div>
                  </div>
                </div>
                <div class="body_text">{{ el.qecCnt }}/{{ el.qecTCnt }}</div>
              </div>
            </div>
          </div>
        </div>
      </a-spin>
    </SidePanelItem>

    <!-- 自定义弹框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="'生态流量达标情况'"
      width="1536px"
      :footer="null"
    >
      <STLLXFFS
        v-if="modalVisible"
        :options="list"
        :typeKey="selectedItem.key"
        :time="mode"
        :basicId="baseid"
      />
    </a-modal>

    <!-- 环保自动监测工作开展情况弹框 -->
    <a-modal
      v-model:open="huanbaoModalVisible"
      :title="'环保自动监测工作开展情况'"
      width="1536px"
      :footer="null"
    >
     <ModalYkzhbzdjcgz v-if="huanbaoModalVisible" :baseId="baseid" :titleData = titleData />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import SidePanelItem from '@/components/SidePanelItem/index.vue';
import {
  qgcetQgcStaticData,
  evnmAutoMonitorGetKendoListCust
} from '@/api/stll';
import { useJidiSelectEventStore } from '@/store/modules/jidiSelectEvent';
import STLLXFFS from './TwoLayer/ShengTaiLiuLiangDaBQKTwoLayer.vue';
import ModalYkzhbzdjcgz from './TwoLayer/ModalYkzhbzdjcgz.vue';
import HuanbaoZDJCGZKZ from '@/modules/huanbaozdjcgzkzQK/index.vue';
// 定义组件名（便于调试和递归）
defineOptions({
  name: 'shengtaidabiaoMod'
});
const JidiSelectEventStore = useJidiSelectEventStore();
const baseid = ref('');
const obj = {
  show: true,
  value:
    '1、统计电站范围：接入过生态流量数据的电站,2、当来水不足时，生态流量不小于入库流量判定为达标,3、“≥95%座数”表示统计电站范围内时段达标率大于等于95%的电站数量'
};

const mode = ref('hour');
const dataArr: any = ref([
  {
    name: '生态环境部门要求',
    qecCnt: '41', // 座数
    qecTCnt: '55', //总座数
    type: 1,
    key: 'qecInterval'
  },
  {
    name: '水利部门要求',
    qecCnt: '41', // 座数
    qecTCnt: '55', //总座数
    type: 2,
    key: 'mwrInterval'
  }
]);
const list: any = ref([
  { name: '生态环境部门要求', type: 1, color: '#77C300', key: 'qecInterval' },
  { name: '水利部门要求', type: 2, color: '#56C3E3', key: 'mwrInterval' },
  { name: '多年平均流量 10%', type: 3, color: '#F76B01', key: 'avqInterval' },
  { name: '无生态流量要求', type: 4, color: '#B4B4B4', key: null }
]);
const datalist: any = ref([]);
const allArr: any = ref(Array.from({ length: 20 }, (_, i) => i));
const spinning = ref(false);
const modalVisible = ref(false);
const modalTitle = ref('');
const selectedItem = ref<any>(null);
const huanbaoModalVisible = ref(false);

// 处理电站数量点击事件
const handleStationClick = () => {
  huanbaoModalVisible.value = true;
};

// 处理进度条点击事件
const handleBarClick = (item: any) => {
  selectedItem.value = item;
  //   modalTitle.value = `${item.name} - 详细信息`;
  modalVisible.value = true;
};

// 根据 type 将 list 中的数据合并到 dataArr 中
const setStyle = () => {
  if (dataArr.value.length == 0) {
    return false;
  }
  dataArr.value.forEach((item: any) => {
    // 在 list 中找到 type 匹配的数据
    const matched = list.value.find(
      (listItem: any) => listItem.type === item.type
    );
    if (matched) {
      // 合并数据，dataArr 的属性优先
      datalist.value.push({
        ...matched,
        ...item
      });
    }
  });
  console.log(datalist.value);
};
const dataChage = () => {
  getData();
};
const getData = async () => {
  // 计算时间范围：当前时间前一个月的00:00:00 到 当前时间的23:59:59
  const now = new Date();
  const oneMonthAgo = new Date(now);
  oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);

  // 格式化日期为 YYYY-MM-DD
  const formatDate = (date: Date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  const startDate = `${formatDate(oneMonthAgo)} 00:00:00`;
  const endDate = `${formatDate(now)} 23:59:59`;

  let params = {
    filter: {
      logic: 'and',
      filters: [
        baseid.value != 'all'
          ? {
              field: 'baseId',
              operator: 'eq',
              dataType: 'string',
              value: baseid.value
            }
          : null,
        {
          field: 'dtin',
          operator: 'eq',
          dataType: 'string',
          value: '1'
        },
        {
          field: 'type',
          operator: 'eq',
          dataType: 'string',
          value: mode.value
        },
        {
          field: 'tm',
          operator: 'gte',
          dataType: 'date',
          value: startDate
        },
        {
          field: 'tm',
          operator: 'lte',
          dataType: 'date',
          value: endDate
        }
      ].filter(Boolean)
    }
  };

  spinning.value = true;
  try {
    let res = await qgcetQgcStaticData(params);
    // 根据API响应结构规范处理数据
    if (res.data && res.data.list) {
      const apiList = res.data.list;
      //   debugger
      // 只使用前两条数据（type: 1 和 type: 2）
      if (apiList && apiList.length > 0) {
        dataArr.value = apiList.slice(0, 2).map((item: any) => ({
          //   name: item.typeName || item.desc,
          qecCnt: item.qecCnt,
          qecTCnt: item.qecTCnt,
          type: item.type
        }));

        // 清空旧数据并重新合并样式
        datalist.value = [];
        setStyle();
      } else {
        // 无数据场景处理
        dataArr.value = [];
        datalist.value = [];
      }
    }
  } catch (error) {
    console.error('获取生态流量达标数据失败:', error);
  } finally {
    spinning.value = false;
  }
};
watch(
  () => JidiSelectEventStore.selectedItem,
  newVal => {
    if (newVal && newVal.wbsCode) {
      baseid.value = newVal.wbsCode;
      getData();
    }
  },
  { deep: true, immediate: true }
);
//统计电站范围：接入过生态流量数据的电站
const titleData:any = ref({ cnt: 0 })
const getcont = async () => {
  let params = {
    "filter": {
        "logic": "and",
        "filters": [
            {
                "field": "showIds",
                "operator": "in",
                "value": [
                    "7"
                ]
            }
        ]
    }
}
  let res = await evnmAutoMonitorGetKendoListCust(params);
//   [
//     {
//         "cnt": 452,
//         "orderInx": 7,
//         "orderInxName": "生态流量",
//         "sttpFullPath": "ENG",
//         "sttpCode": "ENG",
//         "sttpName": "生态流量"
//     }
// ]
  let list = res?.data?.data[0];
  if (list) {
    titleData.value = list
  }
  // debugger
};
// 页面加载时执行的逻辑
onMounted(() => {
  setStyle();
  getcont()
});
</script>

<style lang="scss" scoped>
.body_topOne {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  .title_text {
    font-size: 16px;
  }
}

.boy_one {
  display: flex;
  align-items: center;
  margin: 5px 0px;
}

.body_zhu {
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  transition: all 0.3s ease;

  .body_biao {
    width: 100%;
    height: 52px;
    border: 1px solid #ccdae7;
    border-radius: 2px;
    display: flex;
    padding: 5px 1px;
    overflow: hidden;

    .nei_body {
      width: 12px;
      height: 100%;
      border: 1px solid #ccdae7;
      padding: 2px;
      margin-left: 4px;

      .little_body {
        width: 100%;
        height: 100%;
      }
    }
  }

  .body_text {
    display: flex;
    flex-direction: column;
    width: 90px;
    height: 100%;
    justify-content: space-around;
    margin-left: 6px;
    align-items: center;
    font-size: 18px;
    font-weight: 500;
  }
}

.ant-radio-group {
  // border: 3px solid #2f6b98 !important;
  // border-radius: 10px !important;

  .ant-radio-button-wrapper-checked {
    border: 1px solid #2f6b98 !important;
    background-color: #2f6b98 !important;
    color: #fff !important;
  }

  .ant-radio-button-wrapper {
    border: 2px solid #2f6b98 !important;
  }

  .ant-radio-button-wrapper-checked :before {
    background-color: #2f6b98 !important;
  }
}
</style>
