package vip.xiaonuo.disk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.disk.domain.StorageBean;
import vip.xiaonuo.disk.mapper.FileStasticMapper;
import vip.xiaonuo.disk.mapper.StorageMapper;
import vip.xiaonuo.disk.service.FileStasticService;

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

@Slf4j
@Service
@Transactional(rollbackFor=Exception.class)
public class FileStasticServiceImpl implements FileStasticService {
   @Resource
   private  FileStasticMapper fileStasticMapper;
    @Resource
    private StorageMapper storageMapper;
    @Override
    public Map<String, Object> queryList() {
        Map<String, Object> rsMap=new HashMap<>();
        String userId = StpLoginUserUtil.getLoginUser().getId();
        LambdaQueryWrapper<StorageBean> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StorageBean::getUserId, userId);

        StorageBean storageBean = storageMapper.selectOne(lambdaQueryWrapper);



        List<Map<String,Object>> list=fileStasticMapper.queryList(userId);
        int totalSize = list.stream()
                .mapToInt(map -> Integer.parseInt(map.get("userFileId").toString()))
                .sum();
        Long totalFileSizeNum = list.stream()
                .mapToLong(map -> Long.parseLong(map.get("fileSizeNum").toString()))
                .sum();
        double totalFileSizeInGB = (double) totalFileSizeNum / (1024 * 1024);
        rsMap.put("list",list);
        rsMap.put("totalSize",totalSize);
        rsMap.put("totalFileSize",String.format("%.2f", totalFileSizeInGB));
        rsMap.put("totalStorageSize",storageBean.getTotalStorageSize());
        rsMap.put("remainStorageSize",subtractNumbers(String.valueOf(storageBean.getTotalStorageSize()),String.valueOf(totalFileSizeInGB)));
        return rsMap;
    }


    public static String subtractNumbers(String num1, String num2) {
        try {
            BigDecimal number1 = new BigDecimal(num1);
            BigDecimal number2 = new BigDecimal(num2);
            BigDecimal result = number1.subtract(number2).setScale(2, RoundingMode.HALF_UP); // 保留两位小数
            return result.toString();
        } catch (Exception e) {
            return "0.00"; // 出现异常时返回默认值
        }
    }
}
