package com.limap.core.basic.service.impl;

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

import com.limap.common.core.domain.entity.SysUser;
import com.limap.common.core.redis.RedisCache;
import com.limap.common.exception.ServiceException;
import com.limap.common.utils.DateUtils;
import com.limap.core.basic.vo.SharingUserTaskVo;
import com.limap.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.limap.common.utils.StringUtils;
import com.limap.core.basic.mapper.BasicProfitSharingUserMapper;
import com.limap.core.basic.domain.BasicProfitSharingUser;
import com.limap.core.basic.service.IBasicProfitSharingUserService;

import javax.annotation.Resource;

/**
 * 用户分润基础信息Service业务层处理
 *
 * @author jjb
 * @date 2025-04-11
 */
@Service
@Slf4j
public class BasicProfitSharingUserServiceImpl extends ServiceImpl<BasicProfitSharingUserMapper, BasicProfitSharingUser> implements IBasicProfitSharingUserService {
    @Autowired
    private BasicProfitSharingUserMapper basicProfitSharingUserMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Resource
    private RedisCache redisCache;

    private static final String listCacheKey = "BasicProfitSharingUser:list";

    /**
     * 查询用户分润基础信息列表
     *
     * @param basicProfitSharingUser 用户分润基础信息
     * @return 用户分润基础信息
     */
    @Override
    public List<BasicProfitSharingUser> selectBasicProfitSharingUserList(BasicProfitSharingUser basicProfitSharingUser) {
    	LambdaQueryWrapper<BasicProfitSharingUser> queryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotNull(basicProfitSharingUser.getUserId())) {
			queryWrapper.eq(BasicProfitSharingUser::getUserId, basicProfitSharingUser.getUserId());
		}
        if (StringUtils.isNotEmpty(basicProfitSharingUser.getSharingCode())) {
			queryWrapper.eq(BasicProfitSharingUser::getSharingCode, basicProfitSharingUser.getSharingCode());
		}
        if (StringUtils.isNotEmpty(basicProfitSharingUser.getName())) {
			queryWrapper.like(BasicProfitSharingUser::getName, basicProfitSharingUser.getName());
		}
        queryWrapper.orderByDesc(BasicProfitSharingUser::getCreateTime);
        return basicProfitSharingUserMapper.selectList(queryWrapper);
    }

    /**
     * 查询用户分润基础数据
     *
     * @return 用户分润基础数据
     */
    @Override
    public List<SharingUserTaskVo> selectBasicInfoList() {
        return basicProfitSharingUserMapper.selectBasicInfoList();
    }

    @Override
    public Map<String, BigDecimal> getSuperiorRatio(Long userId) {
        Map<String, BigDecimal> result = new HashMap<>();
        result.put("omRatio",BigDecimal.ZERO);
        result.put("controlRatio",BigDecimal.ZERO);
        BasicProfitSharingUser byId = this.getById("101");
        if (byId!= null) {
            result.put("controlRatio",byId.getControlRatio());
        }
        SysUser user = sysUserService.selectUserById(userId);

        if (user != null) {
            Long parentId = user.getParentId();
            if (parentId == null) {
                return result;
            }

            List<SharingUserTaskVo> list = null;
            if (redisCache.getCacheObject(listCacheKey) == null) {
                list = basicProfitSharingUserMapper.selectCacheList();
                redisCache.setCacheObject(listCacheKey, list);
            }else{
                list = (List<SharingUserTaskVo>) redisCache.getCacheObject(listCacheKey);
            }

            while (parentId != null) {
                try{
                    Long finalParentId = parentId;
                    SharingUserTaskVo parent = list.stream()
                            .filter(f -> f != null && f.getUserId() != null && f.getUserId().equals(finalParentId))
                            .findFirst()
                            .orElse(null);


                    result.put("omRatio",result.get("omRatio").add(parent.getOmRatio()));
                    result.put("controlRatio",result.get("controlRatio").add(parent.getControlRatio()));
                    parentId = parent.getParentId();
                }catch (Exception e){
                    log.error("获取上级分润比例异常：{},parentId{}",e.getMessage(),parentId);
                    return result;
                }

            }

        }
        return result;
    }

    @Override
    public boolean checkRatio(BasicProfitSharingUser basicProfitSharingUser) {

        try{
            Map<String, BigDecimal> superiorRatio = this.getSuperiorRatio(basicProfitSharingUser.getUserId());
            BigDecimal omRatio = superiorRatio.get("omRatio");
            BigDecimal controlRatio = superiorRatio.get("controlRatio");

            BigDecimal omRatio1 = basicProfitSharingUser.getOmRatio();
            BigDecimal val = BigDecimal.valueOf(100);
            if(omRatio1 != null){
                BigDecimal add = omRatio1.add(omRatio);
                if(add.compareTo(val)>0){
                    throw new ServiceException("溶氧分润比例总和不能超过100%,当前已分配比例："+omRatio+"%,最大比例为："+val.subtract(omRatio)+"%");
                }
            }
            BigDecimal controlRatio1 = basicProfitSharingUser.getControlRatio();
            if(controlRatio1 != null){
                BigDecimal add = controlRatio1.add(controlRatio);
                if(add.compareTo(val)>0){
                    throw new ServiceException("控制器分润比例总和不能超过100%,当前已分配比例："+controlRatio+"%,最大比例为："+val.subtract(controlRatio)+"%");
                }
            }
            redisCache.deleteObject(listCacheKey);
            return true;
        }catch (Exception e){
            log.error("分润校验异常：{}",e.getMessage());
        }
        return false;
    }
}
