package com.buy507.mall.portal.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.buy507.mall.mapper.OmsOrderMapper;
import com.buy507.mall.mapper.UmsMemberAccountTransactionMapper;
import com.buy507.mall.mapper.UmsMemberMapper;
import com.buy507.mall.model.*;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

@Component
@Slf4j
public class MonthlyLastDayTask {

    @Resource
    private UmsMemberMapper memberMapper;

    @Resource
    private OmsOrderMapper orderMapper;

    @Resource
    private UmsMemberAccountTransactionMapper umsMemberAccountTransactionMapper;

    /**
     * 全球分红
     * 在月低结算市代会员分红
     * 每位在当月晋升为市代理的会员，将有权参与总收益的分红。
     * 具体来说，公司将从总收益中提取3%，作为市代理级别会员的分红基金
     */

    BigDecimal threePercent = new BigDecimal("0.03");

    @Scheduled(cron = "0 0 23 28-31 * ?")
    public void executeMonthlyLastDayTask() {
        // 检查当前日期是否为每月的最后一天
        if (isLastDayOfMonth()) {
            DateTime nowTime = DateTime.now();
            DateTime firstDayOfMonth  =  DateUtil.beginOfMonth(nowTime);
            UmsMemberExample memberExample = new UmsMemberExample();
            memberExample.createCriteria().andMemberLevelEqualTo(MemberLevel.OneDiamond.getValue())
                    .andCreateTimeBetween(firstDayOfMonth, nowTime);

            List<UmsMember> memberList = memberMapper.selectByExample(memberExample);
            if(memberList.isEmpty()){
                return;
            }

            //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
            List<Integer> stats = Lists.newArrayList(0, 4,5);
            OmsOrderExample orderExample = new OmsOrderExample();
            orderExample.createCriteria().andStatusNotIn(stats);
            List<OmsOrder> sumOrder = orderMapper.selectByExample(orderExample);
            Optional<BigDecimal> payAmountSum = sumOrder.stream().map(OmsOrder::getPayAmount)
                    .reduce(BigDecimal::add);

            if(payAmountSum.isPresent()){
                BigDecimal amountSum =  payAmountSum.get();
                BigDecimal rewardAmount = amountSum.multiply(threePercent).setScale(2, RoundingMode.HALF_UP);
                for (UmsMember member : memberList) {
                    member.setBalance(member.getBalance().add(rewardAmount));
                    memberMapper.updateByPrimaryKey(member);

                    UmsMemberAccountTransaction accountTransaction = new UmsMemberAccountTransaction();
                    accountTransaction.setCommissionRatio(3);
                    accountTransaction.setMemberId(member.getId());
                    accountTransaction.setOrderId(-1L);
                    accountTransaction.setRemarks("{}月-全球分红"+ Integer.valueOf(DateUtil.dayOfMonth(nowTime)));
                    accountTransaction.setRevenueAmount(rewardAmount);
                    //即时到账
                    accountTransaction.setTransferPaymentTime(DateUtil.date());
                    umsMemberAccountTransactionMapper.insert(accountTransaction);

                }
            }
        }
    }

//    @Scheduled(cron = "0 * * * * ?")
//    public void executeEveryMinute() {
//        DateTime nowTime = DateTime.now();
//        DateTime firstDayOfMonth  =  DateUtil.beginOfMonth(nowTime);
//        UmsMemberExample memberExample = new UmsMemberExample();
//        memberExample.createCriteria().andMemberLevelEqualTo(MemberLevel.OneDiamond.getValue());
//
//        List<UmsMember> memberList = memberMapper.selectByExample(memberExample);
//        if(memberList.isEmpty()){
//            return;
//        }
//        //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
//        List<Integer> stats = Lists.newArrayList(0, 4,5);
//        OmsOrderExample orderExample = new OmsOrderExample();
//        orderExample.createCriteria().andStatusNotIn(stats).andPaymentTimeBetween(firstDayOfMonth, nowTime);
//        List<OmsOrder> sumOrder = orderMapper.selectByExample(orderExample);
//        Optional<BigDecimal> payAmountSum = sumOrder.stream().map(OmsOrder::getPayAmount)
//                .reduce(BigDecimal::add);
//
//        if(payAmountSum.isPresent()){
//            BigDecimal amountSum =  payAmountSum.get();
//            BigDecimal rewardAmount = amountSum.multiply(threePercent).setScale(2, RoundingMode.HALF_UP);
//            rewardAmount = rewardAmount.divide(new BigDecimal(memberList.size()),2, RoundingMode.HALF_UP);
//            for (UmsMember member : memberList) {
//              log.info("member : {}, rewardAmount: {}, {}月-全球分红", member, rewardAmount, Integer.valueOf(DateUtil.dayOfMonth(nowTime)));
//
//            }
//        }
//    }

    private boolean isLastDayOfMonth() {
        java.util.Calendar cal = java.util.Calendar.getInstance();
        int lastDay = cal.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
        return cal.get(java.util.Calendar.DAY_OF_MONTH) == lastDay;
    }
}