// mock/parking-mock-service.js - 停车场管理模拟数据服务

// 模拟数据存储
let mockSpaceData = [
    {
        id: 1,
        space_code: "A101",
        space_name: "A区101号",
        building_id: "B1",
        building_name: "A栋",
        floor_id: "B1",
        floor_name: "B1层",
        space_status: 0, // 空闲
        space_type: "normal",
        license_plate: null,
        entry_time: null,
        parking_fee: 0,
        is_online: 1,
        device_id: "DEV001",
        position_x: 120.123456,
        position_y: 30.123456,
        position_z: -3.0,
        remark: "靠近电梯口",
        create_time: "2024-01-01 10:00:00",
        update_time: "2024-01-15 14:30:00"
    },
    {
        id: 2,
        space_code: "A102",
        space_name: "A区102号",
        building_id: "B1",
        building_name: "A栋",
        floor_id: "B1",
        floor_name: "B1层",
        space_status: 1, // 占用
        space_type: "normal",
        license_plate: "粤A88888",
        entry_time: "2024-01-15 08:30:00",
        parking_fee: 45.50,
        is_online: 1,
        device_id: "DEV002",
        position_x: 120.123466,
        position_y: 30.123466,
        position_z: -3.0,
        remark: null,
        create_time: "2024-01-01 10:00:00",
        update_time: "2024-01-15 08:30:00"
    },
    {
        id: 3,
        space_code: "A103",
        space_name: "A区103号",
        building_id: "B1",
        building_name: "A栋",
        floor_id: "B1",
        floor_name: "B1层",
        space_status: 2, // 预约
        space_type: "vip",
        license_plate: null,
        entry_time: null,
        parking_fee: 0,
        is_online: 1,
        device_id: "DEV003",
        position_x: 120.123476,
        position_y: 30.123476,
        position_z: -3.0,
        remark: "VIP专属车位",
        create_time: "2024-01-01 10:00:00",
        update_time: "2024-01-15 10:00:00"
    },
    {
        id: 4,
        space_code: "B201",
        space_name: "B区201号",
        building_id: "B2",
        building_name: "B栋",
        floor_id: "B2",
        floor_name: "B2层",
        space_status: 1, // 占用
        space_type: "normal",
        license_plate: "粤B12345",
        entry_time: "2024-01-15 14:20:00",
        parking_fee: 12.00,
        is_online: 1,
        device_id: "DEV004",
        position_x: 120.124456,
        position_y: 30.124456,
        position_z: -6.0,
        remark: null,
        create_time: "2024-01-02 10:00:00",
        update_time: "2024-01-15 14:20:00"
    },
    {
        id: 5,
        space_code: "B202",
        space_name: "B区202号",
        building_id: "B2",
        building_name: "B栋",
        floor_id: "B2",
        floor_name: "B2层",
        space_status: 0, // 空闲
        space_type: "disabled",
        license_plate: null,
        entry_time: null,
        parking_fee: 0,
        is_online: 1,
        device_id: "DEV005",
        position_x: 120.124466,
        position_y: 30.124466,
        position_z: -6.0,
        remark: "残疾人专用车位，加宽设计",
        create_time: "2024-01-02 10:00:00",
        update_time: "2024-01-02 10:00:00"
    },
    {
        id: 6,
        space_code: "C301",
        space_name: "C区301号",
        building_id: "B3",
        building_name: "C栋",
        floor_id: "F1",
        floor_name: "1层",
        space_status: 3, // 故障
        space_type: "normal",
        license_plate: null,
        entry_time: null,
        parking_fee: 0,
        is_online: 0,
        device_id: "DEV006",
        position_x: 120.125456,
        position_y: 30.125456,
        position_z: 3.0,
        remark: "地锁故障，维修中",
        create_time: "2024-01-03 10:00:00",
        update_time: "2024-01-15 09:00:00"
    }
];

// 模拟API响应延迟
const delay = (ms = 300) => new Promise(resolve => setTimeout(resolve, ms));

// 模拟API服务
const mockService = {
    // 获取车位列表
    async listParkingSpace(query) {
        await delay();

        let filteredData = [...mockSpaceData];

        // 模拟搜索过滤
        if (query.spaceCode) {
            filteredData = filteredData.filter(item =>
                item.space_code.includes(query.spaceCode)
            );
        }
        if (query.spaceName) {
            filteredData = filteredData.filter(item =>
                item.space_name.includes(query.spaceName)
            );
        }
        if (query.buildingId) {
            filteredData = filteredData.filter(item =>
                item.building_id === query.buildingId
            );
        }
        if (query.floorId) {
            filteredData = filteredData.filter(item =>
                item.floor_id === query.floorId
            );
        }
        if (query.spaceStatus !== null && query.spaceStatus !== undefined) {
            filteredData = filteredData.filter(item =>
                item.space_status === query.spaceStatus
            );
        }
        if (query.spaceType) {
            filteredData = filteredData.filter(item =>
                item.space_type === query.spaceType
            );
        }

        // 模拟分页
        const pageNum = query.pageNum || 1;
        const pageSize = query.pageSize || 10;
        const start = (pageNum - 1) * pageSize;
        const end = start + pageSize;

        return {
            code: 200,
            msg: "查询成功",
            total: filteredData.length,
            rows: filteredData.slice(start, end)
        };
    },

    // 获取单个车位详情
    async getParkingSpace(id) {
        await delay();
        const space = mockSpaceData.find(item => item.id === parseInt(id));

        if (space) {
            return {
                code: 200,
                msg: "查询成功",
                data: { ...space }
            };
        } else {
            return {
                code: 404,
                msg: "车位不存在",
                data: null
            };
        }
    },

    // 新增车位
    async addParkingSpace(data) {
        await delay();
        const newSpace = {
            ...data,
            id: mockSpaceData.length + 1,
            space_status: 0,
            license_plate: null,
            entry_time: null,
            parking_fee: 0,
            is_online: 1,
            create_time: new Date().toLocaleString(),
            update_time: new Date().toLocaleString()
        };

        mockSpaceData.push(newSpace);

        return {
            code: 200,
            msg: "新增成功",
            data: newSpace
        };
    },

    // 更新车位
    async updateParkingSpace(data) {
        await delay();
        const index = mockSpaceData.findIndex(item => item.id === data.id);

        if (index !== -1) {
            mockSpaceData[index] = {
                ...mockSpaceData[index],
                ...data,
                update_time: new Date().toLocaleString()
            };

            return {
                code: 200,
                msg: "修改成功",
                data: mockSpaceData[index]
            };
        } else {
            return {
                code: 404,
                msg: "车位不存在",
                data: null
            };
        }
    },

    // 删除车位
    async delParkingSpace(ids) {
        await delay();
        const idArray = Array.isArray(ids) ? ids : [ids];

        idArray.forEach(id => {
            const index = mockSpaceData.findIndex(item => item.id === parseInt(id));
            if (index !== -1) {
                mockSpaceData.splice(index, 1);
            }
        });

        return {
            code: 200,
            msg: "删除成功",
            data: null
        };
    },

    // 导出车位
    async exportParkingSpace(query) {
        await delay();
        // 模拟返回文件下载链接
        return {
            code: 200,
            msg: "/download/parking_space_export_20240115.xlsx",
            data: null
        };
    },

    // 获取统计数据
    async getParkingStatistics() {
        await delay();

        const totalSpaces = mockSpaceData.length;
        const freeSpaces = mockSpaceData.filter(s => s.space_status === 0).length;
        const occupiedSpaces = mockSpaceData.filter(s => s.space_status === 1).length;
        const reservedSpaces = mockSpaceData.filter(s => s.space_status === 2).length;
        const faultSpaces = mockSpaceData.filter(s => s.space_status === 3).length;

        return {
            code: 200,
            msg: "success",
            data: {
                totalSpaces,
                freeSpaces,
                occupiedSpaces,
                reservedSpaces,
                faultSpaces,
                occupancyRate: ((occupiedSpaces / totalSpaces) * 100).toFixed(2),
                todayEntries: 126,
                todayExits: 98,
                todayRevenue: 3456.80
            }
        };
    },

    // 获取实时数据
    async getRealtimeData() {
        await delay();

        const recentEntries = [
            {
                id: 101,
                license_plate: "粤A66666",
                space_code: "A201",
                entry_time: "2024-01-15 16:45:23",
                space_type: "normal"
            },
            {
                id: 102,
                license_plate: "粤B99999",
                space_code: "B105",
                entry_time: "2024-01-15 16:42:15",
                space_type: "vip"
            },
            {
                id: 103,
                license_plate: "粤C88888",
                space_code: "C203",
                entry_time: "2024-01-15 16:38:45",
                space_type: "normal"
            },
            {
                id: 104,
                license_plate: "粤A12345",
                space_code: "A108",
                entry_time: "2024-01-15 16:35:20",
                space_type: "normal"
            }
        ];

        const recentExits = [
            {
                id: 201,
                license_plate: "粤D55555",
                space_code: "B203",
                entry_time: "2024-01-15 08:30:00",
                exit_time: "2024-01-15 16:40:00",
                duration: "8小时10分",
                fee: 96.00
            },
            {
                id: 202,
                license_plate: "粤E77777",
                space_code: "A105",
                entry_time: "2024-01-15 14:00:00",
                exit_time: "2024-01-15 16:35:00",
                duration: "2小时35分",
                fee: 25.00
            },
            {
                id: 203,
                license_plate: "粤F33333",
                space_code: "C101",
                entry_time: "2024-01-15 09:15:00",
                exit_time: "2024-01-15 16:30:00",
                duration: "7小时15分",
                fee: 72.00
            }
        ];

        // 模拟楼层车位数据
        const floorSpaces = [];
        const floors = ['B1', 'B2'];
        let spaceId = 1;

        floors.forEach(floor => {
            for (let i = 1; i <= 20; i++) {
                const randomStatus = Math.random();
                let status = 0; // 默认空闲
                let licensePlate = null;

                if (randomStatus < 0.5) {
                    status = 1; // 50%占用
                    licensePlate = `粤${String.fromCharCode(65 + Math.floor(Math.random() * 26))}${Math.floor(10000 + Math.random() * 90000)}`;
                } else if (randomStatus < 0.7) {
                    status = 0; // 20%空闲
                } else if (randomStatus < 0.9) {
                    status = 2; // 20%预约
                } else {
                    status = 3; // 10%故障
                }

                floorSpaces.push({
                    id: spaceId++,
                    space_code: `A${floor}${String(i).padStart(3, '0')}`,
                    floor_id: floor,
                    space_status: status,
                    license_plate: licensePlate
                });
            }
        });

        return {
            code: 200,
            msg: "success",
            data: {
                recentEntries,
                recentExits,
                floorSpaces
            }
        };
    },

    // 获取报表数据
    async getParkingReport(params) {
        await delay();

        const dates = [];
        const occupancyRates = [];
        const revenues = [];
        const details = [];

        // 生成7天的数据
        for (let i = 6; i >= 0; i--) {
            const date = new Date();
            date.setDate(date.getDate() - i);
            const dateStr = date.toISOString().split('T')[0];

            const occupancyRate = 40 + Math.random() * 30; // 40-70%
            const revenue = 3000 + Math.random() * 4000; // 3000-7000

            dates.push(dateStr);
            occupancyRates.push(parseFloat(occupancyRate.toFixed(1)));
            revenues.push(parseFloat(revenue.toFixed(2)));

            details.push({
                date: dateStr,
                totalSpaces: 500,
                usedSpaces: Math.floor(500 * occupancyRate / 100),
                occupancyRate: occupancyRate.toFixed(1),
                entryCount: 150 + Math.floor(Math.random() * 200),
                exitCount: 140 + Math.floor(Math.random() * 190),
                revenue: revenue.toFixed(2)
            });
        }

        return {
            code: 200,
            msg: "success",
            data: {
                dates,
                occupancyRates,
                revenues,
                details,
                summary: {
                    avgOccupancyRate: (occupancyRates.reduce((a, b) => a + b) / 7).toFixed(1),
                    totalRevenue: revenues.reduce((a, b) => a + b).toFixed(2),
                    totalEntries: 2156,
                    totalExits: 2098,
                    peakOccupancyRate: Math.max(...occupancyRates).toFixed(1),
                    peakDate: dates[occupancyRates.indexOf(Math.max(...occupancyRates))]
                }
            }
        };
    }
};

// 导出模拟服务
export default mockService;