package com.ema.admin.modules.assets.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ema.admin.modules.assets.entity.AssetsInfo;
import com.ema.admin.modules.assets.vo.AssetsInfoQueryVo;
import com.ema.admin.modules.assets.vo.AssetsStatisticsVo;
import com.ema.admin.modules.assets.mapper.AssetsInfoMapper;
import com.ema.admin.modules.assets.service.AssetsInfoService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  资产信息表 服务层实现。
 *
 * @author LIJIAN
 * @since 2026-05-13
 */
@Service
public class AssetsInfoServiceImpl extends ServiceImpl<AssetsInfoMapper, AssetsInfo> implements AssetsInfoService {

    @Override
    public Page<AssetsInfo> page(AssetsInfoQueryVo queryVo) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.like(AssetsInfo::getDeptName, queryVo.getDeptName(), StrUtil.isNotBlank(queryVo.getDeptName()));
        queryWrapper.like(AssetsInfo::getAssetCode, queryVo.getAssetCode(), StrUtil.isNotBlank(queryVo.getAssetCode()));
        queryWrapper.eq(AssetsInfo::getAssetType, queryVo.getAssetType(), StrUtil.isNotBlank(queryVo.getAssetType()));
        queryWrapper.like(AssetsInfo::getBrand, queryVo.getBrand(), StrUtil.isNotBlank(queryVo.getBrand()));
        queryWrapper.like(AssetsInfo::getModel, queryVo.getModel(), StrUtil.isNotBlank(queryVo.getModel()));
        queryWrapper.eq(AssetsInfo::getInvstkStatus, queryVo.getInvstkStatus(), StrUtil.isNotBlank(queryVo.getInvstkStatus()));
        queryWrapper.orderBy(AssetsInfo::getCreateTime, false);
        return this.page(new Page<>(queryVo.getPageNumber(), queryVo.getPageSize()), queryWrapper);
    }

    @Override
    public AssetsStatisticsVo getStatistics() {
        AssetsStatisticsVo vo = new AssetsStatisticsVo();

        // 查询所有资产
        List<AssetsInfo> allAssets = this.list();

        // 资产总数
        long totalCount = allAssets.size();
        vo.setTotalCount(totalCount);

        // 资产总价值
        BigDecimal totalValue = allAssets.stream()
                .filter(a -> a.getPurchaseValue() != null)
                .map(AssetsInfo::getPurchaseValue)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        vo.setTotalValue(totalValue);

        // 已盘点数量
        long invstkYesCount = allAssets.stream()
                .filter(a -> "1".equals(a.getInvstkStatus()))
                .count();
        vo.setInvstkYesCount(invstkYesCount);

        // 未盘点数量
        long invstkNoCount = totalCount - invstkYesCount;
        vo.setInvstkNoCount(invstkNoCount);

        // 盘点率
        double invstkRate = totalCount > 0 ? (double) invstkYesCount / totalCount * 100 : 0;
        vo.setInvstkRate(Math.round(invstkRate * 100.0) / 100.0);

        // 资产类型分布
        Map<String, Long> typeCountMap = new HashMap<>();
        Map<String, BigDecimal> typeValueMap = new HashMap<>();
        for (AssetsInfo asset : allAssets) {
            String type = asset.getAssetType();
            if (StrUtil.isNotBlank(type)) {
                typeCountMap.merge(type, 1L, Long::sum);
                if (asset.getPurchaseValue() != null) {
                    typeValueMap.merge(type, asset.getPurchaseValue(), BigDecimal::add);
                }
            }
        }
        List<AssetsStatisticsVo.TypeCount> typeDistribution = new ArrayList<>();
        typeCountMap.forEach((type, count) -> {
            AssetsStatisticsVo.TypeCount tc = new AssetsStatisticsVo.TypeCount();
            tc.setName(type);
            tc.setCount(count);
            tc.setValue(typeValueMap.getOrDefault(type, BigDecimal.ZERO));
            typeDistribution.add(tc);
        });
        vo.setTypeDistribution(typeDistribution);

        // 使用状态分布（从资产状态历史表获取最新状态，需要关联查询，这里简化为从资产表统计）
        // 由于资产表没有直接的使用状态字段，这里返回空列表或根据invstkStatus统计
        Map<String, Long> statusCountMap = new HashMap<>();
        statusCountMap.put("已盘点", invstkYesCount);
        statusCountMap.put("未盘点", invstkNoCount);
        List<AssetsStatisticsVo.TypeCount> statusDistribution = new ArrayList<>();
        statusCountMap.forEach((status, count) -> {
            AssetsStatisticsVo.TypeCount sc = new AssetsStatisticsVo.TypeCount();
            sc.setName(status);
            sc.setCount(count);
            statusDistribution.add(sc);
        });
        vo.setStatusDistribution(statusDistribution);

        return vo;
    }
}
