package com.zg.project.wisdom.service.impl;

import com.zg.project.wisdom.domain.vo.SceneUsageVO;
import com.zg.project.wisdom.domain.vo.WarehouseSceneStatsResp;
import com.zg.project.wisdom.domain.vo.WarehouseStatVO;
import com.zg.project.wisdom.mapper.WarehouseStatMapper;
import com.zg.project.wisdom.service.WarehouseStatService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

@Service
public class WarehouseStatServiceImpl implements WarehouseStatService {

    @Resource
    private WarehouseStatMapper warehouseStatMapper;

    @Override
    public WarehouseSceneStatsResp getWarehouseSceneStats() {
        // 1) 启用仓库列表 & 总数
        List<WarehouseStatVO> warehouses = warehouseStatMapper.selectEnabledWarehouses();
        int totalWarehouses = warehouses == null ? 0 : warehouses.size();

        // 2) 逐仓库查询场景统计并计算仓库级汇总与百分比
        if (warehouses != null) {
            for (WarehouseStatVO wh : warehouses) {
                String code = wh.getWarehouseCode();

                // 场景列表（每个场景含总库位、已使用）
                List<SceneUsageVO> scenes = warehouseStatMapper.selectSceneUsageByWarehouse(code);
                if (scenes == null) scenes = new ArrayList<>();

                // 补充每个场景的空闲与百分比
                int whTotal = 0, whUsed = 0, whFree = 0;
                for (SceneUsageVO s : scenes) {
                    int t = nvl(s.getTotalPositions());
                    int u = nvl(s.getUsedPositions());
                    int f = Math.max(t - u, 0);

                    s.setFreePositions(f);
                    s.setUsageRatePercent(pct(u, t));
                    s.setFreeRatePercent(pct(f, t));

                    whTotal += t;
                    whUsed  += u;
                    whFree  += f;
                }

                // 仓库级汇总
                wh.setScenes(scenes);
                wh.setSceneCount(scenes.size());
                wh.setTotalPositions(whTotal);
                wh.setUsedPositions(whUsed);
                wh.setFreePositions(whFree);
                wh.setUsageRatePercent(pct(whUsed, whTotal));
                wh.setFreeRatePercent(pct(whFree, whTotal));
            }
        }

        // 3) 组装响应
        WarehouseSceneStatsResp resp = new WarehouseSceneStatsResp();
        resp.setTotalWarehouses(totalWarehouses);
        resp.setItems(warehouses == null ? new ArrayList<>() : warehouses);
        return resp;
    }

    private static int nvl(Integer v) { return v == null ? 0 : v; }

    private static String pct(int part, int total) {
        if (total <= 0 || part <= 0) return "0.00";
        return new BigDecimal(part)
                .multiply(new BigDecimal("100"))
                .divide(new BigDecimal(total), 2, RoundingMode.HALF_UP)
                .toPlainString();
    }
}
