<!-- SidePanelItem.vue -->
<template>
  <SidePanelItem
    title="水生生态调查情况"
    :select="select"
    :datetimePicker="datetimePicker"
    @update-values="handlePanelChange"
  >
    <a-spin :spinning="dataLoading" tip="加载中...">
      <div class="facility-grid">
        <div
          v-for="facility in facilities"
          :key="facility.name"
          class="facility-card"
          @click="handleCardClick"
        >
          <div
            style="
              width: 60px;
              height: 62px;
              display: flex;
              align-items: center;
              justify-content: center;
            "
          >
            <div class="facility-icon">
              <i
                style="color: #fff"
                :class="facility.icon"
                type="icon-shengtailiuliang2"
              ></i>
            </div>
          </div>

          <div class="facility-info">
            <div class="facility-name">{{ facility.name }}</div>
            <div style="font-size: 16px">
              <span class="facility-count">{{ facility.count }}</span>
              <span>{{ facility.unit }}</span>
            </div>
          </div>
        </div>
      </div>
    </a-spin>
  </SidePanelItem>

  <!-- 水生生态调查概况弹框 -->
  <a-modal
    v-model:open="modalVisible"
    title="水生生态调查概况"
    width="1536px"
    :footer="null"
    @cancel="handleModalClose"
  >
    <SsstdcgkTk
      v-if="modalVisible"
      :selectDateTime="datetimePicker.value"
      :all="true"
    />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { useJidiSelectEventStore } from '@/store/modules/jidiSelectEvent';
import SidePanelItem from '@/components/SidePanelItem/index.vue';
import SsstdcgkTk from './SsstdcgkTk.vue';
import { wbsbGetKendoList, getDftYear, getWeFisht } from '@/api/stdc';
import moment from 'moment';
import { Label } from 'cesium';

// 定义组件名
defineOptions({
  name: 'shuishengshengtaijiance'
});

const JidiSelectEventStore = useJidiSelectEventStore();
const baseid = ref('');
const dataLoading = ref(false);

// ==================== 弹框状态 ====================
const modalVisible = ref(false);

// ==================== 响应式变量定义 ====================
// 选择器配置
const select = ref({
  show: true,
  value: undefined,
  options: [],
  picker: undefined,
  format: undefined,
  width: '120px'
});

// 日期选择器配置
const datetimePicker = ref({
  show: true,
  value: '',
  format: 'YYYY',
  picker: 'year' as const,
  options: []
});

const facilities = ref([
  {
    name: '水生态调查断面',
    count: 0,
    unit: '个',
    icon: 'icon iconfont icon-liuliangjiancezhan'
  },
  {
    name: '调查鱼类统计',
    count: 0,
    unit: '种',
    icon: 'icon iconfont icon-yuleizengzhizhan'
  }
]);

// ==================== 事件处理 ====================
const handlePanelChange = (data: any) => {
  console.log('当前所有控件状态:', data);
  if (data.select) {
    select.value.value = data.select;
  }
  if (data.datetime) {
    datetimePicker.value.value = data.datetime;
  }
  // 选择器或日期变化时，重新获取统计数据
  getCardData();
};

const handleCardClick = () => {
  console.log('卡片被点击，准备打开弹框');
  console.log('modalVisible:', datetimePicker.value.value);
  modalVisible.value = true;
  console.log('modalVisible:', modalVisible.value);
};

const handleModalClose = () => {
  modalVisible.value = false;
};

// ==================== 获取默认年份 ====================
const getDefaultYear = async () => {
  if (!baseid.value) return;

  try {
    // const params = {
    //   filter: { baseId: baseid.value },
    //   group: [{ dir: 'des', field: 'yr' }]
    // };
    let params = {
      filter: {
        logic: 'and',
        filters: [
          baseid.value != 'all'
            ? {
                field: 'baseId',
                operator: 'eq',
                dataType: 'string',
                value: baseid.value
              }
            : null
        ].filter(Boolean)
      },
      group: [
        {
          dir: 'des',
          field: 'yr'
        }
      ]
    };
    const res = await getDftYear(params);
    const data = res?.data?.data?.[0] || {};
    const allYears = Object.values(data);

    if (allYears?.length) {
      const last = (allYears as any[]).flat().sort().pop();
      datetimePicker.value.value = last;
    } else {
      datetimePicker.value.value = moment().format('YYYY');
    }

    // 获取统计数据
    getCardData();
  } catch (error) {
    console.error('获取默认年份失败:', error);
    datetimePicker.value.value = moment().format('YYYY');
    getCardData();
  }
};

// ==================== 获取卡片统计数据 ====================
const getCardData = async () => {
  if (!datetimePicker.value.value) return;

  dataLoading.value = true;

  try {
    const filters: any[] = [
      {
        field: 'yr',
        operator: 'eq',
        dataType: 'string',
        value: moment(datetimePicker.value.value).format('YYYY')
      }
    ];

    if (baseid.value && baseid.value !== 'all') {
      filters.push({
        field: 'baseId',
        operator: 'eq',
        dataType: 'string',
        value: baseid.value
      });
    }

    if (select.value.value) {
      filters.push({
        field: 'hbrvcd',
        operator: 'eq',
        dataType: 'string',
        value: select.value.value
      });
    }

    const params = {
      filter: {
        logic: 'and',
        filters
      },
      group: [],
      groupResultFlat: true
    };

    const res = await getWeFisht(params);
    const data = res?.data?.data?.[0];

    facilities.value = [
      {
        name: '水生态调查断面',
        count: data?.stcdCount ?? 0,
        unit: '个',
        icon: 'icon iconfont icon-liuliangjiancezhan'
      },
      {
        name: '调查鱼类统计',
        count: data?.ftpCount ?? 0,
        unit: '种',
        icon: 'icon iconfont icon-yuleizengzhizhan'
      }
    ];
  } catch (error) {
    console.error('获取统计数据失败:', error);
    facilities.value = [
      {
        name: '水生态调查断面',
        count: 0,
        unit: '个',
        icon: 'icon iconfont icon-liuliangjiancezhan'
      },
      {
        name: '调查鱼类统计',
        count: 0,
        unit: '种',
        icon: 'icon iconfont icon-yuleizengzhizhan'
      }
    ];
  } finally {
    dataLoading.value = false;
  }
};

// ==================== 获取选择器数据 ====================
const getSelectData = async () => {
  let params = {
    filter: {
      logic: 'and',
      filters: [
        {
          field: 'wbsType',
          operator: 'eq',
          value: 'PSB_RVCD'
        },
        baseid.value != 'all'
          ? {
              field: 'objId',
              operator: 'eq',
              value: '水生生态调查情况'
            }
          : null
      ].filter(Boolean)
    },
    group: [
      {
        dir: 'asc',
        field: 'orderIndex'
      },
      {
        dir: 'asc',
        field: 'wbsCode'
      },
      {
        dir: 'asc',
        field: 'wbsName'
      },
      {
        dir: 'asc',
        field: 'objid'
      }
    ],
    groupResultFlat: true
  };
  const res = await wbsbGetKendoList(params);
  let data = res?.data?.data;
  select.value.options = data.map((item: any) => {
    return {
      value: item.wbsCode,
      label: item.wbsName
    };
  });
};

// ==================== 监听基地变化 ====================
watch(
  () => JidiSelectEventStore.selectedItem,
  async newVal => {
    if (newVal && newVal.wbsCode) {
      baseid.value = newVal.wbsCode;
      getSelectData();
      getDefaultYear();
    }
  },
  { deep: true, immediate: true }
);
</script>

<style lang="scss" scoped>
.facility-grid {
  width: 406px;
  flex-flow: wrap;
  display: flex;
  justify-content: space-between;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
    Helvetica Neue, Arial, Noto Sans, sans-serif, Apple Color Emoji,
    Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
}

.facility-card {
  width: 200px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 4px 0px;
  background: #fff;
  border: 1px solid rgb(229, 236, 245);
  border-radius: 2px;
  transition: all 0.3s;
  cursor: pointer;
  box-sizing: border-box;
}

.facility-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  // margin-right: 8px;
  background: #2f6b98;
  border-radius: 50%;

  .anticon {
    font-size: 24px;
    color: #fff;
  }
}

.facility-info {
  flex: 1;
}

.facility-name {
  font-size: 16px;
  color: #333;
  // margin-bottom: 4px;
  // font-weight: 500;
}

.facility-count {
  font-size: 18px;
  color: #2f6b98;
  // font-weight: 600;
}

:deep(.ant-spin-nested-loading) {
  min-height: 72px;
}
</style>
