package cn.pluss.platform.app.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.pluss.platform.app.MainPageService;
import cn.pluss.platform.entity.MerchantOrderStatistics;
import cn.pluss.platform.entity.UserAccount;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.entity.UserPromotion;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantProfitMapper;
import cn.pluss.platform.mapper.UserAccountFlowMapper;
import cn.pluss.platform.mapper.UserAppMapper;
import cn.pluss.platform.mapper.UserPromotionMapper;
import cn.pluss.platform.merchantOrder.MerchantOrderStatisticsService;
import cn.pluss.platform.merchantProfit.MerchantProfitService;
import cn.pluss.platform.userAccount.UserAccountService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.DateUtils;
import cn.pluss.platform.util.N;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.vo.MerchantOrderStatisticsVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

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

import static com.baomidou.mybatisplus.core.toolkit.StringPool.N;

/**
 * 推广者的主页面信息查询实现类
 */
@RequiredArgsConstructor
@Service("promoterMainPageService")
public class PromoterMainPageServiceImpl implements MainPageService {

    private final UserAppService userAppService;

    private final MerchantProfitService merchantProfitService;

    @Autowired
    @Lazy
    private MerchantOrderStatisticsService mosService;
    @Resource
    private MerchantProfitMapper merchantProfitMapper;
    @Resource
    private UserPromotionMapper userPromotionMapper;
    @Resource
    private UserAppMapper userAppMapper;
    @Resource
    private UserAccountFlowMapper userAccountFlowMapper;
    @Resource
    private UserAccountService userAccountService;

    @Override
    public Map<String, Object> getSpreadData(String userId) {
        Map<String, Object> resultMap = new HashMap<>();

        if (StringUtil.isEmpty(userId)) {
            throw new MsgException("无用户Id！");
        }

        // 获取当前的用户信息
        UserApp queryUserApp = new UserApp();
        queryUserApp.setUserId(Long.parseLong(userId));
        List<UserApp> queryUserAppList2 = userAppService.queryUserAppList(queryUserApp);
        if (queryUserAppList2 == null || queryUserAppList2.size() == 0) {
            throw new MsgException("无用户信息！");
        } else {
            queryUserApp = queryUserAppList2.get(0);
        }

        BigDecimal promoteFee;
        Double todayProfit;
        Integer totalOrderCount;

        //分润
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("userId", userId);
        queryMap.put("status", 1);
        // 累计总收益
        UserAccount userAccountByUserId = userAccountService.getUserAccountByUserId(Integer.valueOf(userId));
        if(ObjectUtil.isEmpty(userAccountByUserId)){
            promoteFee=BigDecimal.ZERO;
        }else {
            promoteFee = userAccountByUserId.getBalance().add(userAccountByUserId.getOutBalance());
        }

        //今日收款笔数
        queryMap.put("recordDate", DateUtils.getDayBegin());
        queryMap.put("retype", "1");
        totalOrderCount = merchantProfitMapper.queryMerchantProfitPageCountV2(userId,DateUtils.getDayBegin(),DateUtils.getDayEnd());
        todayProfit = merchantProfitService.queryMerchantProfitSumPrice(queryMap);

        //今日收益
        BigDecimal todaySum = userAccountFlowMapper.selectSumByUserId(Long.valueOf(userId), DateUtils.getDayBegin(), DateUtils.getDayEnd());;

        //今日新增商户数
        Integer newMerchantCount = userAppMapper.selectUserAppWithChannelStatusCountV2(userId, DateUtils.getDayBegin(), DateUtils.getDayEnd());
        //直属商户交易
        BigDecimal consumeFee = merchantProfitMapper.getConsumeFee(userId);
        //团队商户交易
        BigDecimal consumeFeeTeam = merchantProfitMapper.getConsumeFeeTeam(userId);
        //今日收款
        BigDecimal consumeFeeTeamToday = merchantProfitMapper.getConsumeFeeTeamToday(userId);
        //总商户数
        Integer countChildAll = merchantProfitMapper.getCountChildV2(Long.valueOf(userId));

        resultMap.put("promoteFee", promoteFee + "");
        resultMap.put("totalOrderCount", totalOrderCount + "");
        resultMap.put("newMerchantCount", newMerchantCount + "");
        resultMap.put("todayProfit", todayProfit == null? "0.00": todayProfit + "");

        resultMap.put("todaySum", todaySum);
        resultMap.put("consumeFee", consumeFee);
        resultMap.put("consumeFeeTeam", consumeFeeTeam);
        resultMap.put("consumeFeeTeamToday", consumeFeeTeamToday);
        resultMap.put("countChildAll", countChildAll);

        String currentMonth = DateUtil.format(new Date(), "yyyy-MM");

        MerchantOrderStatistics directTotalCurrentMonth = mosService.getDirectTotal(queryUserApp.getUserId() + "", currentMonth);
        MerchantOrderStatistics teamTotalCurrentMonth = mosService.getIndirectTotal(queryUserApp.getUserId() + "", currentMonth);

        MerchantOrderStatisticsVO mosVO = new MerchantOrderStatisticsVO();
        mosVO.setMonthCount((directTotalCurrentMonth.getCount() + teamTotalCurrentMonth.getCount()) + "");
        mosVO.setDirectMonthTotalFee(directTotalCurrentMonth.getTotalFee());
        mosVO.setTeamMonthTotalFee(teamTotalCurrentMonth.getTotalFee());

        MerchantOrderStatistics directTotal = mosService.getDirectTotal(queryUserApp.getUserId() + "", null);
        MerchantOrderStatistics teamTotal = mosService.getIndirectTotal(queryUserApp.getUserId() + "", null);
        mosVO.setCount(directTotal.getCount() + teamTotal.getCount());
        mosVO.setDirectTotalFee(directTotal.getTotalFee());
        mosVO.setTeamTotalFee(teamTotal.getTotalFee());

        resultMap.put("merchStatistics", mosVO);

        return resultMap;
    }

    @Override
    public void modifyFee(Long userId, Integer id, BigDecimal fee) {
        QueryWrapper<UserPromotion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        UserPromotion promotion = userPromotionMapper.selectOne(queryWrapper);
        if(ObjectUtil.isEmpty(promotion)){
            throw new MsgException("费率信息不存在");
        }
        UserPromotion userPromotion = userPromotionMapper.selectByPrimaryKey(userId);
        if(ObjectUtil.isEmpty(userPromotion)){
            throw new MsgException("父级机构信息异常");
        }

        Boolean flag=true;
        switch (userPromotion.getTypeCode()){
            case "MG":
                if(promotion.getTypeCode().equals("FO")){
                    flag=false;
                }
                break;
            case "FO":
                if(promotion.getTypeCode().equals("SO")){
                    flag=false;
                }
                break;
            case "SO" :
                if(promotion.getTypeCode().equals("AG")){
                    flag=false;
                }
                break;
            case "AG":
                if(promotion.getTypeCode().equals("FB")){
                    flag=false;
                }
                break;
            case "FB":
                if(promotion.getTypeCode().equals("SB")){
                    flag=false;
                }
                break;
        }
        if(flag){
            throw new MsgException("当前用户权限不足");
        }

        if(cn.pluss.platform.util.N.gt(new BigDecimal(userPromotion.getCurrentFee()),fee)){
            throw new MsgException("修改费率不允许小于上级费率");
        }

        BigDecimal lowFee=userPromotionMapper.selectMaxFeeByUserId(id.toString());
        if(ObjectUtil.isNotEmpty(lowFee)&&cn.pluss.platform.util.N.gt(fee,lowFee)){
           throw new MsgException("修改费率不允许小于下级最大费率");
        }

        promotion.setCurrentFee(String.valueOf(fee));
        promotion.setUpdateTime(new Date());
        int i = userPromotionMapper.updateByPrimaryKey(promotion);
        if (i < 1){
            throw new MsgException("修改失败");
        }

    }

    @Override
    public Map<String, Object> getHomeData(String userId) {
        return null;
    }
}
