<!-- 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(facility)"
        >
          <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="currentOrderIndex === '16' ? '红外相机信息' : '重点陆生动物'"
    width="1536px"
    :footer="null"
    @cancel="handleModalClose"
  >
    <LsstjkTk
      v-if="modalVisible"
      :selectDateTime="datetimePicker.value"
      :orderIndex="currentOrderIndex"
      :hbrvcd="select.value"
    />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, nextTick,watch } from 'vue';
import { ref, watch } from 'vue';
import { useJidiSelectEventStore } from '@/store/modules/jidiSelectEvent';
import SidePanelItem from '@/components/SidePanelItem/index.vue';
import LsstjkTk from './LsstjkTk.vue';
import { wbsbGetKendoList, getEvnmAutoMonitor } from '@/api/stdc';
import moment from 'moment';
import { useDraggable } from '@/utils/drag';

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

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

// ==================== 弹框状态 ====================
const modalVisible = ref(false);
const currentOrderIndex = ref('16');
useDraggable(modalVisible, { boundary: true, resetOnOpen: true });
// ==================== 响应式变量定义 ====================
// 选择器配置
const select = ref({
  show: true,
  value: undefined,
  options: [],
  picker: undefined,
  format: undefined,
  width: '120px'
});

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

const facilities:any = ref([
  {
    name: '野生动物监测',
    count: 0,
    unit: '个',
    icon: 'icon iconfont icon-dongwujiuzhuzhan',
    orderInx: '16'
  },
  {
    name: '重点陆生动物',
    count: 0,
    unit: '种',
    icon: 'icon iconfont icon-shipinjiankongshebei',
    orderInx: '20'
  }
]);

// ==================== 事件处理 ====================
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 = (facility: any) => {
  console.log('卡片被点击，准备打开弹框');
  // debugger
  currentOrderIndex.value = facility.orderInx;
  modalVisible.value = true;
};

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

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

  dataLoading.value = true;

  try {
    const year = moment(datetimePicker.value.value).format('YYYY');
    const startTime = `${year}-01-01 00:00:00`;
    const endTime = `${year}-12-31 23:59:59`;

    const filters: any[] = [
      {
        field: 'showIds',
        operator: 'in',
        value: ['16', '20']
      },
      {
        field: 'startTime',
        operator: 'gte',
        dataType: 'date',
        value: startTime
      },
      {
        field: 'endTime',
        operator: 'lte',
        dataType: 'date',
        value: endTime
      }
    ];

    if (baseid.value && baseid.value !== 'all') {
      filters.unshift({
        field: 'hbrvcd',
        operator: 'in',
        value: [baseid.value]
      });
    }

    const params = {
      filter: {
        logic: 'and',
        filters
      }
    };

    const res = await getEvnmAutoMonitor(params);
    const data = res?.data?.data;

    if (data && Array.isArray(data)) {
      const wildAnimalItem = data.find((item: any) => item.orderInx === 16);
      const keyAnimalItem = data.find((item: any) => item.orderInx === 20);

      facilities.value = [
        {
          name: '野生动物监测',
          count: wildAnimalItem?.cnt ?? 0,
          unit: '个',
          icon: 'icon iconfont icon-dongwujiuzhuzhan',
          orderInx: '16'
        },
        {
          name: '重点陆生动物',
          count: keyAnimalItem?.cnt ?? 0,
          unit: '种',
          icon: 'icon iconfont icon-shipinjiankongshebei',
          orderInx: '20'
        }
      ];
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
    facilities.value = [
      {
        name: '野生动物监测',
        count: 0,
        unit: '个',
        icon: 'icon iconfont icon-dongwujiuzhuzhan',
         orderInx: '16'
      },
      {
        name: '重点陆生动物',
        count: 0,
        unit: '种',
        icon: 'icon iconfont icon-shipinjiankongshebei',
        orderInx: '20'
      }
    ];
  } 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: baseid.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();
      getCardData();
    }
  },
  { 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;
  background: #2f6b98;
  border-radius: 50%;

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

.facility-info {
  flex: 1;
}

.facility-name {
  font-size: 16px;
  color: #333;
}

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

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