import { Request, Response } from 'express';

// 初始数据
const genInventoryList = (current: number, pageSize: number) => {
    const tableListDataSource: any[] = [];
    const warehouses = ['上海一号仓', '北京东区仓', '深圳前海仓'];
    const units = ['个', '箱', '台'];
    const statusList = ['normal', 'low_stock', 'out_of_stock'];

    for (let i = 0; i < pageSize; i += 1) {
        const quantity = Math.floor(Math.random() * 200);
        let status = 'normal';
        if (quantity === 0) status = 'out_of_stock';
        else if (quantity < 10) status = 'low_stock';

        tableListDataSource.push({
            key: i,
            id: `inv-${i}`,
            sku: `SKU-2024-${String(i).padStart(3, '0')}`,
            name: `高性能组件-${i}`,
            quantity,
            unit: units[i % 3],
            warehouse: warehouses[i % 3],
            status,
            minStock: 10,
            maxStock: 500,
            lastUpdated: new Date().toISOString(),
            category: '电子元器件',
            description: '关键零部件，需定期盘点',
        });
    }
    return tableListDataSource;
};

let tableListDataSource = genInventoryList(1, 40);
const logs: Record<string, any[]> = {}; // Map<InventoryId, LogItem[]>

export default {
    'GET /api/inventory': (req: Request, res: Response) => {
        const { current = 1, pageSize = 20, name, sku, status, warehouse } = req.query as any;

        let dataSource = [...tableListDataSource];

        if (name) {
            dataSource = dataSource.filter(item => item.name.includes(name));
        }
        if (sku) {
            dataSource = dataSource.filter(item => item.sku.includes(sku));
        }
        if (status) {
            dataSource = dataSource.filter(item => item.status === status);
        }
        if (warehouse) {
            dataSource = dataSource.filter(item => item.warehouse === warehouse);
        }

        const total = dataSource.length;
        const startIndex = ((current as number) - 1) * (pageSize as number);
        const endIndex = (current as number) * (pageSize as number);
        const list = dataSource.slice(startIndex, endIndex);

        res.json({
            data: list,
            total,
            success: true,
            pageSize,
            current: parseInt(`${current}`, 10) || 1,
        });
    },

    'POST /api/inventory': (req: Request, res: Response) => {
        const newData = {
            ...req.body,
            id: `inv-${Date.now()}`,
            lastUpdated: new Date().toISOString(),
            createdAt: new Date().toISOString(),
            status: req.body.quantity > 0 ? 'normal' : 'out_of_stock',
        };
        tableListDataSource.unshift(newData);
        res.json(newData);
    },

    'PUT /api/inventory/:id': (req: Request, res: Response) => {
        const { id } = req.params;
        const index = tableListDataSource.findIndex(item => item.id === id);
        if (index !== -1) {
            tableListDataSource[index] = { ...tableListDataSource[index], ...req.body, lastUpdated: new Date().toISOString() };
            res.json(tableListDataSource[index]);
        } else {
            res.status(404).json({ success: false });
        }
    },

    'POST /api/inventory/:id/adjust': (req: Request, res: Response) => {
        const { id } = req.params;
        const { type, quantity, remark } = req.body; // type: 'in' | 'out' | 'adjust'
        const index = tableListDataSource.findIndex(item => item.id === id);

        if (index !== -1) {
            const item = tableListDataSource[index];
            let newQuantity = item.quantity;
            let changeAmount = 0;

            if (type === 'in') {
                newQuantity += parseInt(quantity, 10);
                changeAmount = parseInt(quantity, 10);
            } else if (type === 'out') {
                newQuantity -= parseInt(quantity, 10);
                changeAmount = -parseInt(quantity, 10);
            } else if (type === 'adjust') {
                changeAmount = parseInt(quantity, 10) - item.quantity; // 盘点调整：直接设为新值
                newQuantity = parseInt(quantity, 10);
            }

            if (newQuantity < 0) {
                res.status(400).json({ success: false, message: '库存不足，无法扣减' });
                return;
            }

            // Update Status
            let status = 'normal';
            if (newQuantity === 0) status = 'out_of_stock';
            else if (newQuantity < (item.minStock || 10)) status = 'low_stock';

            tableListDataSource[index] = { ...item, quantity: newQuantity, status, lastUpdated: new Date().toISOString() };

            // Log
            const logId = String(id);
            if (!logs[logId]) logs[logId] = [];
            logs[logId].unshift({
                id: `log-${Date.now()}`,
                inventoryId: logId,
                type,
                quantity: changeAmount,
                beforeQuantity: item.quantity,
                afterQuantity: newQuantity,
                operator: 'Admin', // MOCKED
                remark,
                createdAt: new Date().toISOString(),
            });

            res.json({ success: true, data: tableListDataSource[index] });
        } else {
            res.status(404).json({ success: false, message: 'Item not found' });
        }
    },

    'GET /api/inventory/:id/logs': (req: Request, res: Response) => {
        const { id } = req.params;
        const logId = String(id);
        const list = logs[logId] || [];
        res.json({
            data: list,
            total: list.length,
            success: true,
        });
    },

    'DELETE /api/inventory/:id': (req: Request, res: Response) => {
        const { id } = req.params;
        tableListDataSource = tableListDataSource.filter(item => item.id !== id);
        delete logs[String(id)];
        res.json({ success: true });
    }

};
