package com.sqx.modules.invite.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.entity.UserVip;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.app.service.UserVipService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.invite.dao.InviteDao;
import com.sqx.modules.invite.entity.Invite;
import com.sqx.modules.invite.entity.InviteAward;
import com.sqx.modules.invite.service.InviteAwardService;
import com.sqx.modules.invite.service.InviteMoneyService;
import com.sqx.modules.invite.service.InviteService;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 邀请记录
 */
@Service
public class InviteServiceImpl extends ServiceImpl<InviteDao, Invite> implements InviteService {


    @Autowired
    private InviteDao inviteDao;
    @Autowired
    private UserService userService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private InviteMoneyService inviteMoneyService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private InviteAwardService inviteAwardService;
    @Autowired
    private UserVipService userVipService;
    @Autowired
    private SysUserService sysUserService;

    @Override
    public PageUtils selectInviteList(int page, int limit, Integer state, Long userId) {
        PageHelper.startPage(page, limit);
        if (state == null || state == -1) {
            state = null;
        }
        List<Invite> inviteList = inviteDao.selectInviteList(state, userId);
        return PageUtils.page(new PageInfo<>(inviteList));
    }


    @Override
    public PageUtils selectInviteUser(int page, int limit, Long userId, Integer state, Integer userType) {
        UserEntity userEntity = userService.queryByUserId(userId);
        PageHelper.startPage(page, limit);
        return PageUtils.page(new PageInfo<>(inviteDao.selectInviteUser(userEntity.getInvitationCode())));
    }

    @Override
    public Integer selectInviteByUserIdCountNotTime(Long userId) {
        return inviteDao.selectInviteByUserIdCountNotTime(userId);
    }

    @Override
    public Integer selectInviteByUserIdCount(Long userId, Date startTime, Date endTime) {
        return inviteDao.selectInviteByUserIdCount(userId, startTime, endTime);
    }

    @Override
    public Double selectInviteByUserIdSum(Long userId, Date startTime, Date endTime) {
        return inviteDao.selectInviteByUserIdSum(userId, startTime, endTime);
    }

    @Override
    public Double sumInviteMoney(String time, Integer flag) {
        return inviteDao.sumInviteMoney(time, flag);
    }

    @Override
    public PageUtils inviteAnalysis(int page, int limit, String time, Integer flag) {
        PageHelper.startPage(page, limit);
        return PageUtils.page(new PageInfo<>(inviteDao.inviteAnalysis(time, flag)));
    }

    @Override
    public Integer selectInviteCount(Integer state, Long userId) {
        if (state == null || state == -1) {
            state = null;
        }
        return inviteDao.selectInviteCount(state, userId);
    }

    @Override
    public Integer selectInviteCount2(String code) {
        return inviteDao.selectInviteCount2(code);
    }

    @Override
    public Integer selectInviteSignCount(String code) {
        return inviteDao.selectInviteSignCount(code);
    }


    @Override
    public Double selectInviteSum(Integer state, Long userId) {
        if (state == null || state == -1) {
            state = null;
        }
        return inviteDao.selectInviteSum(state, userId);
    }

    @Override
    public List<Long> selectInviteSignByUser(String code) {
        return inviteDao.selectInviteSignByUser(code);
    }

    @Override
    public int saveBody(Long userId, UserEntity userEntity) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date());
        Invite invite = new Invite();
        invite.setState(0);
        invite.setMoney(0.00);
        invite.setUserId(userEntity.getUserId());
        invite.setInviteeUserId(userId);
        invite.setCreateTime(format);
        invite.setUserType(1);
        inviteDao.insert(invite);
        //同步二级
        UserEntity two = userService.queryByInvitationCode(userEntity.getInviterCode());
        if (two != null) {
            invite = new Invite();
            invite.setState(0);
            invite.setMoney(0.00);
            invite.setUserId(two.getUserId());
            invite.setInviteeUserId(userId);
            invite.setCreateTime(format);
            invite.setUserType(2);
            inviteDao.insert(invite);
        }
        UserEntity user = new UserEntity();
        user.setUserId(userId);
        user.setInviterCode(userEntity.getInvitationCode());
        userService.updateById(user);

        // 金币
        int money = Integer.parseInt(commonInfoService.findOne(911).getValue());
        if (money > 0 && userEntity.getUserId() != 1) {
            userMoneyService.updateMoney(1, userEntity.getUserId(), money);
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(userEntity.getUserId());
            userMoneyDetails.setType(1);
            // ✅
            userMoneyDetails.setClassify(1);
            userMoneyDetails.setMoney(new BigDecimal(money));
            userMoneyDetails.setCreateTime(format);
            userMoneyDetails.setTitle("[分享奖励金币]");
            userMoneyDetails.setContent("获取金币:" + money);
            userMoneyDetails.setState(2);
            userMoneyDetails.setMoneyType(2);
            userMoneyDetailsService.save(userMoneyDetails);
        }

        //助力活动
        String value = commonInfoService.findOne(813).getValue();
        if (!"是".equals(value)) {
            return 0;
        }
        //获取邀请人的邀请数量
        int inviterCount = userService.queryInviterCount(userEntity.getInvitationCode());
        InviteAward inviteAward = inviteAwardService.getOne(new QueryWrapper<InviteAward>().eq("invite_count", inviterCount));
        if (inviteAward == null) {
            return 0;
        }
        if (inviteAward.getInviteMonth() == 0) {
            userVipService.update(null, Wrappers.<UserVip>lambdaUpdate()
                    .set(UserVip::getIsVip, 2)
                    .set(UserVip::getEndTime, null)
                    .set(UserVip::getVipType, 1)
                    .eq(UserVip::getUserId, userEntity.getUserId()));

            return 1;
        }
        UserVip userVip = userVipService.selectUserVipByUserId(userEntity.getUserId());
        Calendar calendar = Calendar.getInstance();
        if (userVip != null && userVip.getIsVip() == 2) {
            Date date = DateUtils.stringToDate(userVip.getEndTime(), DateUtils.DATE_TIME_PATTERN);
            calendar.setTime(date);
        } else {
            userVip = new UserVip();
            userVip.setUserId(userEntity.getUserId());
            userVip.setCreateTime(DateUtils.format(new Date()));
        }
        userVip.setIsVip(2);
        userVip.setVipType(1);
        calendar.add(Calendar.MONTH, inviteAward.getInviteMonth());
        userVip.setEndTime(DateUtils.format(calendar.getTime()));
        if (userVip.getVipId() != null) {
            userVipService.updateById(userVip);
        } else {
            userVipService.save(userVip);
        }

        return 1;
    }


    @Override
    public Map<String, Object> updateInvite(UserEntity userEntity, String format, Long userId, BigDecimal price) {
        Map<String, Object> result = new HashMap<>();
        if (userEntity != null && userId != null && price != null) {
            Invite invite1 = inviteDao.selectInviteByUser(userEntity.getUserId(), userId, 1);
            if (invite1 == null) {
                Invite invite = new Invite();
                invite.setState(0);
                invite.setMoney(0.00);
                invite.setUserId(userEntity.getUserId());
                invite.setInviteeUserId(userId);
                invite.setCreateTime(format);
                invite.setUserType(1);
                inviteDao.insert(invite);
                invite1 = inviteDao.selectInviteByUser(userEntity.getUserId(), userId, 1);
            }
            UserEntity userEntity1 = userService.selectUserById(userId);
            BigDecimal oneMoney = BigDecimal.ZERO;
            BigDecimal twoMoney = BigDecimal.ZERO;
            if (userEntity.getRate() != null && userEntity.getRate().doubleValue() > 0) {
                BigDecimal rateMoney = userEntity.getRate();
                oneMoney = rateMoney;
                Double money = rateMoney.doubleValue();
                invite1.setUserType(1);
                invite1.setState(1);
                BigDecimal add = BigDecimal.valueOf(invite1.getMoney()).add(BigDecimal.valueOf(money));
                invite1.setMoney(add.doubleValue());
                inviteDao.updateById(invite1);
                inviteMoneyService.updateInviteMoneySum(money, userEntity.getUserId());
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                userMoneyDetails.setUserId(userEntity.getUserId());
                userMoneyDetails.setType(1);
                // ✅
                userMoneyDetails.setClassify(1);
                userMoneyDetails.setMoney(new BigDecimal(money));
                userMoneyDetails.setCreateTime(format);
                userMoneyDetails.setTitle("[邀请好友]好友名称：" + userEntity1.getUserName());
                userMoneyDetails.setContent("获取佣金:" + money);
                userMoneyDetails.setMoneyType(1);
                userMoneyDetails.setState(2);
                userMoneyDetailsService.save(userMoneyDetails);
                userMoneyService.updateAmount(1, userEntity.getUserId(), money);
                result.put("oneUserId", userEntity.getUserId());
                result.put("oneMoney", money);
            }
            UserEntity two = userService.queryByInvitationCode(userEntity.getInviterCode());
            if (two != null) {
                Invite invite2 = inviteDao.selectInviteByUser(two.getUserId(), userId, 2);
                if (invite2 == null) {
                    Invite invite = new Invite();
                    invite.setState(0);
                    invite.setMoney(0.00);
                    invite.setUserId(two.getUserId());
                    invite.setInviteeUserId(userId);
                    invite.setCreateTime(format);
                    invite.setUserType(2);
                    inviteDao.insert(invite);
                    invite2 = inviteDao.selectInviteByUser(two.getUserId(), userId, 2);
                }
                if (two.getTwoRate() != null && two.getTwoRate().doubleValue() > 0) {
                    BigDecimal rateMoney = two.getTwoRate();
                    twoMoney = rateMoney;
                    Double money = rateMoney.doubleValue();
                    invite2.setUserType(2);
                    invite2.setState(1);
                    BigDecimal add = BigDecimal.valueOf(invite2.getMoney()).add(BigDecimal.valueOf(money));
                    invite2.setMoney(add.doubleValue());
                    inviteDao.updateById(invite2);
                    inviteMoneyService.updateInviteMoneySum(money, two.getUserId());
                    UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                    userMoneyDetails.setUserId(two.getUserId());
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setMoney(new BigDecimal(money));
                    userMoneyDetails.setCreateTime(format);
                    // ✅
                    userMoneyDetails.setClassify(1);
                    userMoneyDetails.setTitle("[邀请好友]好友名称：" + userEntity1.getUserName());
                    userMoneyDetails.setContent("获取佣金:" + money);
                    userMoneyDetails.setMoneyType(1);
                    userMoneyDetails.setState(2);
                    userMoneyDetailsService.save(userMoneyDetails);
                    userMoneyService.updateAmount(1, two.getUserId(), money);
                    result.put("twoUserId", two.getUserId());
                    result.put("twoMoney", money);
                }
            }

            if (StringUtils.isNotEmpty(userEntity1.getQdCode())) {
                SysUserEntity sysUserEntity = sysUserService.selectSysUserByQdCode(userEntity1.getQdCode());
                if (sysUserEntity != null) {
//                    BigDecimal rateMoney = price.multiply(sysUserEntity.getQdRate()).setScale(2, RoundingMode.HALF_UP);
                    BigDecimal rateMoney = sysUserEntity.getQdRate();
                    BigDecimal sumMoney = rateMoney.subtract(oneMoney);
                    sumMoney = sumMoney.subtract(twoMoney);
                    if (sumMoney.compareTo(BigDecimal.ZERO) <= 0) {
                        return result;
                    }
                    userMoneyService.updateSysAmount(1, sysUserEntity.getUserId(), sumMoney.doubleValue());
                    UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                    userMoneyDetails.setSysUserId(sysUserEntity.getUserId());
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setMoney(sumMoney);
                    userMoneyDetails.setCreateTime(format);
                    userMoneyDetails.setState(2);
                    userMoneyDetails.setClassify(10);
                    userMoneyDetails.setTitle("[渠道用户]用户名称：" + userEntity1.getUserName());
                    String title = "总佣金：" + rateMoney;
                    if (oneMoney.doubleValue() > 0) {
                        title = title + "，一级推广员扣除收益：" + oneMoney;
                    }
                    if (twoMoney.doubleValue() > 0) {
                        title = title + "，二级推广员扣除收益：" + twoMoney;
                    }
                    userMoneyDetails.setContent(title + "，到账佣金:" + sumMoney);
                    userMoneyDetails.setMoneyType(1);
                    userMoneyDetailsService.save(userMoneyDetails);
                    result.put("sysUserId", sysUserEntity.getUserId());
                    result.put("qdMoney", sumMoney);
                    return result;
                }
            }

        }
        return result;
    }

    @Override
    public Invite selectInviteByUser(Long userId, Long inviteeUserId, Integer userType) {
        return inviteDao.selectInviteByUser(userId, inviteeUserId, userType);
    }
}
