<!-- SidePanelItem.vue -->
<template>
    <SidePanelItem title="AI识别大坝环境" :datetimePicker="datetimePicker" @update-values="handlePanelChange">
        <a-spin :spinning="dataLoading" tip="加载中...">
            <div class="facility-grid">
                <div
                    v-for="(facility, idx) in facilities"
                    :key="facility.name"
                    class="facility-card"
                    @click="handleCardClick(String(idx + 1))"
                >
                    <div style="width: 70px;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: 14px;"> <span class="facility-count">{{ facility.count }}</span>
                            <span>次</span>
                        </div>
                    </div>
                </div>
            </div>
        </a-spin>
    </SidePanelItem>

    <!-- AI识别大坝环境详情弹框 -->
    <a-modal
        v-model:open="modalVisible"
        title="AI识别大坝环境"
        width="1536px"
        :footer="null"
        @cancel="handleModalClose"
    >
        <AISBTK
            v-if="modalVisible"
            :month="datetimePicker.value"
            :tab-idx="currentTabIdx"
            :baseid="baseid"
        />
    </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 AISBTK from './AISBTK.vue';
import { getAisbdbyxList } from '@/api/zngj';
import dayjs from 'dayjs';

// 定义组件名（便于调试和递归）
defineOptions({
    name: 'aisbdbyx'
});

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

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

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

// ==================== 设施数据 ====================
const facilities = ref([
    {
        name: '漂浮物识别',
        count: 0,
        icon: 'icon iconfont icon-piaofuwu'
    },
    {
        name: '叠梁门运行识别',
        count: 0,
        icon: 'icon iconfont icon-dieliangmen1'
    },
]);

// ==================== 事件处理 ====================
const handlePanelChange = (data: any) => {
    console.log('当前所有控件状态:', data);
    if (data.datetime) {
        datetimePicker.value.value = data.datetime;
    }
    getCardData();
};

const handleCardClick = (tabIdx: string) => {
    currentTabIdx.value = tabIdx;
    modalVisible.value = true;
};

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

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

    dataLoading.value = true;

    try {
        const params = {
            filter: {
                logic: 'and',
                filters: [
                    baseid.value !== 'all' ? {
                        field: 'baseId',
                        operator: 'eq',
                        dataType: 'string',
                        value: baseid.value
                    } : null,
                    {
                        field: 'startTime',
                        operator: 'gte',
                        dataType: 'date',
                        value: dayjs(datetimePicker.value.value).startOf('month').format('YYYY-MM-DD 00:00:00')
                    },
                    {
                        field: 'endTime',
                        operator: 'lte',
                        dataType: 'date',
                        value: dayjs(datetimePicker.value.value).endOf('month').format('YYYY-MM-DD 23:59:59')
                    }
                ].filter(Boolean)
            }
        };

        const res = await getAisbdbyxList(params);
        const data = res?.data ?? {};

        facilities.value = [
            {
                name: '漂浮物识别',
                count: data?.pfwCnt ?? 0,
                icon: 'icon iconfont icon-piaofuwu'
            },
            {
                name: '叠梁门运行识别',
                count: data?.dlmCnt ?? 0,
                icon: 'icon iconfont icon-dieliangmen1'
            }
        ];
    } catch (error) {
        console.error('获取统计数据失败:', error);
        facilities.value = [
            {
                name: '漂浮物识别',
                count: 0,
                icon: 'icon iconfont icon-piaofuwu'
            },
            {
                name: '叠梁门运行识别',
                count: 0,
                icon: 'icon iconfont icon-dieliangmen1'
            }
        ];
    } finally {
        dataLoading.value = false;
    }
};

// ==================== 监听基地变化 ====================
watch(
    () => JidiSelectEventStore.selectedItem,
    async newVal => {
        if (newVal && newVal.wbsCode) {
            baseid.value = newVal.wbsCode;
            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: 70px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 4px 0px;
    background: #fff;
    border: 1px solid #e8e8e8;
    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: rgb(47, 107, 152);
    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>
