package cn.wisenergy.service.app.impl;

import cn.wisenergy.common.utils.DateUtil;
import cn.wisenergy.common.utils.R;
import cn.wisenergy.mapper.*;
import cn.wisenergy.model.app.*;
import cn.wisenergy.model.enums.MemberPercentEnum;
import cn.wisenergy.model.enums.TradeRecordEnum;
import cn.wisenergy.model.enums.TradeStatusEnum;
import cn.wisenergy.model.enums.UserLevelEnum;
import cn.wisenergy.service.Manager.AccountManager;
import cn.wisenergy.service.Manager.PublicManager;
import cn.wisenergy.service.app.AccountService;
import cn.wisenergy.service.app.MonthTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 86187
 */
@Slf4j
@Service
public class MonthTaskServiceImpl implements MonthTaskService {

    @Autowired
    private LastAccountMapper lastAccountMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private MemberPercentMapper memberPercentMapper;

    @Autowired
    private AccountManager accountManager;

    @Autowired
    private PublicManager publicManager;

    @Autowired
    private TradeRecordMapper tradeRecordMapper;

    @Autowired
    private TeamPerformanceMapper teamPerformanceMapper;

    @Autowired
    private ProgressPrizeMapper progressPrizeMapper;

    @Autowired
    private AccountService accountService;

    @Autowired
    private MonthManureMapper monthManureMapper;


    @Autowired
    private OrderMapper orderMapper;

    private static final String PATTERN = "yyyy-MM";

    private static final Integer TWENTY = 20;

    @Override
    public R<Boolean> orderRebate() {
        return null;
    }

    @Override
    public R<Boolean> performanceCount(List<OrderInfo> list) {
        log.info("shop-mall[]AccountServiceImpl[]performanceCount[]input.param.list:{}", list.size());
        if (CollectionUtils.isEmpty(list)) {
            return R.ok(0, true);
        }

        Date date = new Date();
        String yearMonth = DateUtil.convertDateToStr(date, PATTERN);

        //计算当月所有订单成交额
        BigDecimal totalMoney = new BigDecimal(0);
        for (OrderInfo orderInfo : list) {
            //判断是否是本月
            boolean bool = publicManager.isThisMonth(orderInfo.getCreateTime(), PATTERN);
            if (bool && orderInfo.getMonthlyTaskStatus() == 0) {
                totalMoney = totalMoney.add(orderInfo.getPayment());
            }
        }

        //遍历订单  订单状态创建时间,当月时间小于当前时间
        for (OrderInfo orderInfo : list) {
            long createTime = orderInfo.getCreated().getTime();
            long time = System.currentTimeMillis();
            if (createTime <= time) {
                //获取用户信息
                User user = usersMapper.selectById(orderInfo.getBuyerId());
                if (null == user) {
                    continue;
                }

                List<TeamPerformance> teamPerformances = new ArrayList<>();

                //获取团队业绩信息
                TeamPerformance teamPerformance = teamPerformanceMapper.getByUserIdAndTime(user.getUserId(), yearMonth);
                if (null == teamPerformance) {
                    continue;
                }

                //1、统计当前用户月度业绩
                BigDecimal userCount = teamPerformance.getMonthTeamPerformance().add(orderInfo.getPayment());
                teamPerformance.setMonthTeamPerformance(userCount);
                teamPerformances.add(teamPerformance);

                //2、获取当前用户的上级用户列表 todo 邀请码等于一个固定值,停止 等于两个值  七位XXXXXXX 和 7777777
                List<User> userList = accountService.getByList(user.getUserId());
                if (CollectionUtils.isEmpty(userList)) {
                    continue;
                }

                //3、统计当前用户上级月度绩效
                for (User userInfo : userList) {
                    TeamPerformance team = teamPerformanceMapper.getByUserIdAndTime(userInfo.getUserId(), yearMonth);
                    if (null == team) {
                        continue;
                    }
                    //1)、统计当前用户月度绩效
                    BigDecimal monthCount = team.getMonthTeamPerformance().add(orderInfo.getPayment());
                    team.setMonthTeamPerformance(monthCount);
                    teamPerformances.add(team);
                }

                //4、更新账户月度绩效
                accountManager.updateAccountPerformanceMonth(teamPerformances);
            }
        }
        //5、获取所有用户,如果会员等级是黄金以上,计算月度收益
        List<User> userList = usersMapper.getAllGoldUser();
        if (CollectionUtils.isEmpty(userList)) {
            //添加月度肥料剩余奖金
            MonthManure monthManure = new MonthManure();
            monthManure.setManureAward(totalMoney.doubleValue());
            monthManure.setYearMonth(yearMonth);
            int count = monthManureMapper.add(monthManure);
            if (count == 0) {
                return R.ok(1, false);
            }
            return R.ok(0, true);
        }

        //7、计算收益
        boolean bool = monthlyIncome(totalMoney, userList);
        if (!bool) {
            return R.ok(1, false);
        }
        return R.ok(0, true);
    }

    @Override
    public R<Boolean> progressPrizeCount() {
        return null;
    }

    @Override
    public void mirrorImage() {
        //1、把账户表account_info复制给表account_image  CREATE TABLE table_2  SELECT * FROM table_1;
        lastAccountMapper.copyTable("account_info", "account_image");

        //删除上月备份
        lastAccountMapper.deleteTable("account_backup");

        //备份
        lastAccountMapper.copyTable("account_info", "account_backup");

        //2、把上月账户表last_month_account 复制给month_account_image
        lastAccountMapper.copyTable("last_month_account", "month_account_image");

        //3、删除last_month_account
        lastAccountMapper.deleteTable("last_month_account");

        //4、把account_image 更名为 last_month_account  rename table table_2 to table_1;
        lastAccountMapper.updateTableName("account_image", "last_month_account");

        //5、删除month_account_image   DROP table table_2;
        lastAccountMapper.deleteTable("month_account_image");
    }


    /**
     * 如果会员等级是黄金以上,计算月度收益
     *
     * @param totalMoney 月金额总额
     * @param userList   用户列表
     * @return
     */
    private boolean monthlyIncome(BigDecimal totalMoney, List<User> userList) {
        double total = totalMoney.doubleValue();
        Date date = new Date();
        String yearMonth = DateUtil.convertDateToStr(date, PATTERN);

        //当月所有人订单成交总金额/3980/12  向下取整
        double moneyMonth = Math.floor(total / 3980 / 12);
        List<AccountInfo> accountInfoList = new ArrayList<>();
        List<TradeRecord> tradeRecordList = new ArrayList<>();

        //获取上月未分配完的奖金
        double lastMonthAward;
        Date last = DateUtil.getLastMonth(new Date());
        String yearMonthTime = DateUtil.convertDateToStr(last, PATTERN);
        MonthManure monthManure = monthManureMapper.queryByTime(yearMonthTime);
        if (null == monthManure) {
            lastMonthAward = 0.00;
        } else {
            lastMonthAward = monthManure.getManureAward();
        }
        moneyMonth = moneyMonth + lastMonthAward;

        //判断每个等级是否都有用户,没有用户的,记录下剩余奖金
        MonthManure manure = checkUserLevel(moneyMonth);

        for (User user : userList) {
            if (moneyMonth != 0) {
                //获取等级优惠百分比
                MemberPercent memberPercent = memberPercentMapper.getByLevelAndType(user.getUserLevel(),
                        MemberPercentEnum.MONTH_MANURE.getCode());
                if (null != memberPercent) {
                    //获取本月团队总金额
                    TeamPerformance teamPerformance = teamPerformanceMapper.getByUserIdAndTime(user.getUserId(), yearMonth);

                    //获取该等级团队总金额
                    Double teamTotal = teamPerformanceMapper.countTeamMoney(user.getUserLevel(), yearMonth);
                    if (null != teamPerformance && null != teamTotal) {
                        double month = teamPerformance.getMonthTeamPerformance().doubleValue();
                        double percent = memberPercent.getPercent().doubleValue();
                        //计算收益
                        double income = moneyMonth * 3980 * percent * month / teamTotal;

                        //获取账户信息
                        AccountInfo accountInfo = accountMapper.getByUserId(user.getUserId());
                        BigDecimal bigDecimal = new BigDecimal(income);
                        BigDecimal performanceMonth = accountInfo.getEarningsMonth().add(bigDecimal);
                        accountInfo.setEarningsMonth(performanceMonth);

                        BigDecimal performanceTotal = accountInfo.getEarningsMonth().add(bigDecimal);
                        accountInfo.setEarningsMonth(performanceTotal);
                        accountInfoList.add(accountInfo);


                        //5、添加交易流水记录
                        TradeRecord tradeRecord = new TradeRecord();
                        tradeRecord.setUserId(user.getUserId());
                        tradeRecord.setTradeType(TradeRecordEnum.MONTHLY_FERTILIZER.getCode());
                        tradeRecord.setTradeNo(null);
                        tradeRecord.setStatus(TradeStatusEnum.ALREADY_SETTLE_ACCOUNTS.getCode());
                        tradeRecordList.add(tradeRecord);
                    }
                }
            }
        }
        //更新账户信息,新增交易流水记录
        return accountManager.updateAccountAddRecordAndManure(accountInfoList, tradeRecordList, manure);
    }

    /**
     * 计算上月未分配完的月度肥料奖金
     *
     * @param moneyMonth 奖金总额
     * @return 月度肥料奖金
     */
    private MonthManure checkUserLevel(double moneyMonth) {
        MonthManure monthManure = new MonthManure();
        double total = 0.00;
        //1、判断是否有黄金等级的用户
        List<User> goldList = usersMapper.getByLevel(UserLevelEnum.GOLD_TREE.getCode());
        if (CollectionUtils.isEmpty(goldList)) {
            //获取等级优惠百分比
            MemberPercent memberPercent = memberPercentMapper.getByLevelAndType(UserLevelEnum.GOLD_TREE.getCode(),
                    MemberPercentEnum.MONTH_MANURE.getCode());
            double percent = memberPercent.getPercent().doubleValue();

            //计算该等级剩余奖金
            double goldAward;
            if (moneyMonth != 0) {
                goldAward = moneyMonth * 3980 * percent;
                total = total + goldAward;
            }
        }

        //2、判断是否有农场主等级的用户
        List<User> farmerList = usersMapper.getByLevel(UserLevelEnum.FARMER.getCode());
        if (CollectionUtils.isEmpty(farmerList)) {
            //获取等级优惠百分比
            MemberPercent memberPercent = memberPercentMapper.getByLevelAndType(UserLevelEnum.FARMER.getCode(),
                    MemberPercentEnum.MONTH_MANURE.getCode());
            double percent = memberPercent.getPercent().doubleValue();

            //计算该等级剩余奖金
            double goldAward;
            if (moneyMonth != 0) {
                goldAward = moneyMonth * 3980 * percent;
                total = total + goldAward;
            }
        }

        //3、判断是否有森林之星等级的用户
        List<User> startList = usersMapper.getByLevel(UserLevelEnum.FOREST_START.getCode());
        if (CollectionUtils.isEmpty(startList)) {
            //获取等级优惠百分比
            MemberPercent memberPercent = memberPercentMapper.getByLevelAndType(UserLevelEnum.FOREST_START.getCode(),
                    MemberPercentEnum.MONTH_MANURE.getCode());
            double percent = memberPercent.getPercent().doubleValue();

            //计算该等级剩余奖金
            double goldAward;
            if (moneyMonth != 0) {
                goldAward = moneyMonth * 3980 * percent;
                total = total + goldAward;
            }
        }

        //4、判断是否有西田森等级的用户
        List<User> partnerList = usersMapper.getByLevel(UserLevelEnum.PARTNER.getCode());
        if (CollectionUtils.isEmpty(partnerList)) {
            //获取等级优惠百分比
            MemberPercent memberPercent = memberPercentMapper.getByLevelAndType(UserLevelEnum.FOREST_START.getCode(),
                    MemberPercentEnum.MONTH_MANURE.getCode());
            double percent = memberPercent.getPercent().doubleValue();

            //计算该等级剩余奖金
            double goldAward;
            if (moneyMonth != 0) {
                goldAward = moneyMonth * 3980 * percent;
                total = total + goldAward;
            }
        }

        //获取当前时间上一月
        Date date = DateUtil.getLastMonth(new Date());
        String yearMonth = DateUtil.convertDateToStr(date, PATTERN);
        monthManure.setYearMonth(yearMonth);
        monthManure.setManureAward(total);
        return monthManure;
    }
}