package com.game.business.task;

import com.game.business.domain.*;
import com.game.business.service.*;
import com.game.common.constant.finance.FinTranType1;
import com.game.common.constant.finance.FinTranType2;
import com.game.common.constant.finance.FinTranType3;
import com.game.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Component
public class AppUserLiveDividedTask {

    @Autowired
    private IAppUserLiveDividedService appUserLiveDividedService;

    @Autowired
    private IAppUserLiveDividedRecordService appUserLiveDividedRecordService;

    @Autowired
    private IAppUserAgentService appUserAgentService;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private IFinTranRecordService finTranRecordService;

    @Autowired
    private RedisCache redisCache;

    @Value("${task.switch}")
    private Boolean taskSwitch;

    @Scheduled(cron = "0 0/5 * * * ? ")
    public void liveDividedTask(){
        if(!taskSwitch){
            return;
        }
        AppUserLiveDivided appUserLiveDivided = new AppUserLiveDivided();
        appUserLiveDivided.setStatus(0);
        List<AppUserLiveDivided> list = appUserLiveDividedService.selectAppUserLiveDividedList(appUserLiveDivided);

        if(list == null || list.isEmpty()){
            return;
        }

        for (int i = 0; i < list.size(); i++) {
            AppUserLiveDivided item = list.get(i);

            List<AppUserAgent> liveRateList = new ArrayList<>();

            // 迭代次数记录
            int num = 0;

            // 获取直播分成比例
            getLiveRate(item.getUserId(), liveRateList, num);

            if(liveRateList.isEmpty()){
                continue;
            }

            try {
                liveRateHandler(liveRateList, item);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private void getLiveRate(Long userId, List<AppUserAgent> liveRateList, int num){

        AppUserAgent userIdObject = new AppUserAgent();
        userIdObject.setUserId(userId);
        List<AppUserAgent> userAgents = appUserAgentService.selectAppUserAgentList(userIdObject);

        if(userAgents == null || userAgents.isEmpty()){
            return;
        }

        AppUserAgent userAgent = userAgents.get(0);
        if(userAgent.getLiveRate() == null){
            userAgent.setLiveRate(0.00);
        }
        liveRateList.add(userAgent);

        /*// 只需要获取直属上级
        if(num == 1){
            return;
        }*/
        num ++;
        getLiveRate(userAgent.getPid(), liveRateList, num);

    }

    @Transactional
    public void liveRateHandler(List<AppUserAgent> liveRateList, AppUserLiveDivided item) throws Exception {

        // 升序排序
        liveRateList.stream().sorted(Comparator.comparing(AppUserAgent::getLiveRate));

        AppUserAgent topUserAgent = liveRateList.get(liveRateList.size() - 1);
        BigDecimal liveRate = new BigDecimal((topUserAgent.getLiveRate() / 100.00) + "");

        // 总佣金
        BigDecimal liveCommission = item.getMoney().multiply(liveRate).setScale(4, RoundingMode.DOWN);

        double indexCommission = 0;
        FinTranRecord superTran = finTranRecordService.selectFinTranRecordById(item.getOtherId());

        for (int i = 0; i < liveRateList.size(); i++) {

            // 计算佣金
            AppUserAgent appUserAgent = liveRateList.get(i);

            AppUser appUser = appUserService.selectAppUserByUserid(appUserAgent.getUserId());
            if(appUser == null){
                continue;
            }

            // 计算上级佣金
            BigDecimal userLiveRate = new BigDecimal("0.00");
            if(appUserAgent.getLiveRate() > 0){
                userLiveRate = new BigDecimal(((appUserAgent.getLiveRate() - indexCommission) / 100.00) + "");
            }
            BigDecimal userCommission = item.getMoney().multiply(userLiveRate).setScale(4, RoundingMode.DOWN);

            // 上一次费率
            indexCommission = appUserAgent.getLiveRate();

            // 更新用户余额
            //if(item.getCurrencyType() == 4){
            //    appUser.setDiamondCoin(appUser.getDiamondCoin() + userCommission.doubleValue());
            //    appUser.setDiamondCoinTotal(appUser.getDiamondCoinTotal() + userCommission.doubleValue());
            //    appUser.setDiamondCoinCash(appUser.getDiamondCoinTotal() + userCommission.doubleValue());
            //    appUserService.updateAppUser(appUser);
                // 更新用户金币
            //}else{
            //    appUser.setCoin(appUser.getCoin() + userCommission.doubleValue());
            //    appUser.setCoinCash(appUser.getCoinCash() + userCommission.doubleValue());
            //    appUserService.updateAppUser(appUser);
            //}

            //redisCache.deleteObject("U:UserInfo:" + appUser.getUserid());

            FinTranRecord finTranRecord = new FinTranRecord();

            //finTranRecord.setAfterDiamondCoin(appUser.getDiamondCoin());
            //finTranRecord.setAfterCoin(appUser.getCoin());

            if(item.getCurrencyType() == 4){
                finTranRecord.setCurrencyType(4);
                finTranRecord.setDiamondCoinChange(userCommission.doubleValue());
                finTranRecord.setCoinChange(0.00);
            }else{
                finTranRecord.setCurrencyType(2);
                finTranRecord.setCoinChange(userCommission.doubleValue());
                finTranRecord.setDiamondCoinChange(0.00);
            }

            finTranRecord.setAfterMoney(0.00);
            finTranRecord.setMoneyChange(0.00);

            finTranRecord.setAfterTicket(0.00);
            finTranRecord.setTicketChange(0.00);

            finTranRecord.setToUid(appUser.getUserid());
            finTranRecord.setUid(appUser.getUserid());

            finTranRecord.setProId(0L);
            finTranRecord.setProCount(0L);
            finTranRecord.setSceneId1(0L);
            finTranRecord.setSceneId2(null);
            finTranRecord.setSceneType(0L);

            //主播记录礼物来源为刷礼物的人
            if(null != superTran && item.getUserId().equals(appUser.getUserid())){
                finTranRecord.setFromUid(superTran.getUid());
                finTranRecord.setProId(superTran.getProId());
                finTranRecord.setProCount(superTran.getProCount());
                finTranRecord.setSceneId1(superTran.getSceneId1());
                finTranRecord.setSceneId2(superTran.getSceneId2());
                finTranRecord.setSceneType(superTran.getSceneType());
            }else{
                finTranRecord.setFromUid(item.getUserId());
            }


            finTranRecord.setTranGroupId(item.getId());

            if(item.getCurrencyType() == 4){
                finTranRecord.setTranType1(FinTranType1.U_Income_Coin_Balance.getType());
            }else if(item.getCurrencyType() == 2){
                finTranRecord.setTranType1(FinTranType1.U_Income_Coin.getType());
            }

            finTranRecord.setTranType2(FinTranType2.REWARD_Income.getType());
            finTranRecord.setTranType3(FinTranType3.RECOMMEND_ADD_AMOUNT.getType());


            finTranRecord.setRemarks(null==superTran?"直播分佣":superTran.getRemarks());

            finTranRecord.setConsumptionCoin(0.00);
            finTranRecord.setConsumptionMoney(0.00);
            finTranRecord.setCommissionRelatedUid(0L);
            finTranRecord.setAgentId(appUser.getAgentId());

            finTranRecord.setCreateTime(new Date());

            finTranRecord.setGoodsId(0L);
            finTranRecord.setGuildId(0L);
            finTranRecord.setManagerCoId(0L);
            finTranRecord.setManagerId(0L);

            finTranRecord.setPerc(0.00);

            finTranRecord.setOrderId(item.getId());
            //finTranRecordService.insertFinTranRecord(finTranRecord);
            //本人已在直播系统分成过 停止流水生成以及金额更新
            if(!item.getUserId().equals(appUser.getUserid())){
                appUserService.updateUserAmount(finTranRecord,true);
                // 插入分佣记录
                AppUserLiveDividedRecord appUserLiveDividedRecord = new AppUserLiveDividedRecord();
                appUserLiveDividedRecord.setRate(userLiveRate);
                appUserLiveDividedRecord.setUserId(appUser.getUserid());
                appUserLiveDividedRecord.setUserLiveDividedId(item.getId());
                appUserLiveDividedRecord.setMoney(userCommission);
                appUserLiveDividedRecord.setCurrencyType(item.getCurrencyType());
                appUserLiveDividedRecord.setCreateTime(new Date());
                appUserLiveDividedRecordService.insertAppUserLiveDividedRecord(appUserLiveDividedRecord);
            }

        }

        AppUserLiveDivided appUserLiveDivided = new AppUserLiveDivided();
        appUserLiveDivided.setId(item.getId());
        appUserLiveDivided.setStatus(1);
        appUserLiveDivided.setUpdateTime(new Date());

        appUserLiveDividedService.updateAppUserLiveDivided(appUserLiveDivided);
    }
}
