package cn.com.ty.lift.ud.userRebate.service.impl;

import cn.com.ty.lift.ud.operation.mapper.entity.UserLevelRuleEntity;
import cn.com.ty.lift.ud.operation.mapper.entity.VipFeeSettingEntity;
import cn.com.ty.lift.ud.operation.service.IUserLevelRuleService;
import cn.com.ty.lift.ud.operation.service.IVipFeeSettingService;
import cn.com.ty.lift.ud.userAccount.mapper.entity.UserAccount;
import cn.com.ty.lift.ud.userAccount.service.IUserAccountService;
import cn.com.ty.lift.ud.userInfo.mapper.entity.UserInfoEntity;
import cn.com.ty.lift.ud.userInfo.service.IUserInfoService;
import cn.com.ty.lift.ud.userRebate.service.IUserRebateService;
import cn.com.ty.lift.ud.userRebate.mapper.UserRebateMapper;
import cn.com.ty.lift.ud.userRebate.mapper.entity.UserRebateEntity;
import cn.com.ty.lift.ud.userRebate.mapper.entity.UserRebateVo;
import cn.com.xwy.boot.web.dto.RestResponse;
import cn.com.xwy.util.collection.ListUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 个人返利记录 -ServiceImpl
 *
 * @author Xson
 * @date 2020-05-19
 */
@Service
@Transactional
@Slf4j
public class UserRebateServiceImpl extends ServiceImpl<UserRebateMapper,UserRebateEntity>
    implements IUserRebateService {

    @Autowired
    private UserRebateMapper userRebateMapper;

    @Autowired
    private IUserLevelRuleService iUserLevelRuleService;

    @Autowired
    private IUserInfoService iUserInfoService;

    @Autowired
    private IVipFeeSettingService iVipFeeSettingService;

    @Autowired
    private IUserAccountService iUserAccountService;

    /**
     * 邀请其他人成为下线
     * @param entity
     * @return
     */
    @Override
    public RestResponse create(UserRebateEntity entity) {
        log.info("开始邀请下线的判断");
        //只有会员或者专家才能邀请人
        UserRebateVo vipOrExpert = userRebateMapper.isVipOrExpert(entity.getUserId());
        if(null == vipOrExpert){
            log.info("您没有邀请的权限，请升级为会员或成为专家");
            return RestResponse.fail("您没有邀请的权限，请升级为会员或成为专家");
        }else{
            //被邀请人的所有上线中，不能有自己
            //邀请人的上级中不能有被邀请人  比如 A-B-A 或者  A-B-C-A 都是不行的
            boolean flag = true;
            Long userId = entity.getUserId();
            while(flag){
                UserRebateEntity upUser1 = userRebateMapper.getUpUser(userId);
                if(null != upUser1){
                    //邀请人有上级，不能是被邀请人
                    if(upUser1.getUserId().equals(entity.getLowerUserId())){
                        log.info("不能循环邀请");
                        return RestResponse.fail("不能循环邀请");
                    }else{
                        userId = upUser1.getUserId();
                        flag = true;
                    }
                }else{
                    flag  = false;
                }
            }
            //被邀请人不能是会员
            UserInfoEntity byId = iUserInfoService.getByUserId(entity.getLowerUserId());
            if(null != byId && byId.getVipFlag() != null && byId.getVipFlag() != 1){
                log.info("抱歉，您是会员，不能被其他人邀请");
                return RestResponse.fail("抱歉，您是会员，不能被其他人邀请");
            }
            //被邀请人不能是其他人的下级,也不能被重复邀请
            UserRebateEntity upUser = userRebateMapper.getUpUser(entity.getLowerUserId());
            if(null == upUser){
                entity.setVipFee(new BigDecimal("0"));
                entity.setVipFeeUp(new BigDecimal("0"));
                int insert = userRebateMapper.insert(entity);
                //邀请人信息
                UserInfoEntity byUserId = iUserInfoService.getByUserId(entity.getUserId());
                if(insert == 1){
                    log.info("邀请下线成功");
                    return RestResponse.success(byUserId.getName(),"邀请成功");
                }else{
                    return RestResponse.fail("邀请失败");
                }
            }else{
                log.info("抱歉，您已经被邀请过，不能被重复邀请");
                return RestResponse.fail("抱歉，您已经被邀请过，不能被重复邀请");
            }
        }

    }


    /**
     * app查询个人返利信息,只显示会员下线
     * @param id
     * @return
     */
    @Override
    public RestResponse getAllRebate(Long id) {
        UserInfoEntity byUserId = iUserInfoService.getByUserId(id);
        if(null != byUserId){
            // 查询当前用户的一级下线
            List<UserRebateVo> oneLowerUserList = userRebateMapper.getOneLowerUser(id);
            //获取会员用户
            List<UserRebateVo> oneList = isVip(oneLowerUserList,1);

            //查询当前用户的二级下线
            List<UserRebateVo> twoLowerUserList = userRebateMapper.getTwoLowerUser(id);
            //获取会员用户
            List<UserRebateVo> twoList = isVip(twoLowerUserList,2);
            oneList.addAll(twoList);
            return RestResponse.success(oneList,"查询成功");
        }else{
            return RestResponse.fail("当前用户不存在");
        }

    }



    /**
     * 后台查询个人返利信息，显示所有下线
     * @param id
     * @return
     */
    @Override
    public RestResponse getAllRebateOfWeb(Long id) {
        //总返利金额
        BigDecimal rebateAll = new BigDecimal("0");

        UserInfoEntity byUserId = iUserInfoService.getByUserId(id);
        if(null != byUserId){
            // 查询当前用户的一级下线
            List<UserRebateVo> oneLowerUserList = userRebateMapper.getOneLowerUser(id);

            //分别查询每个一级用户的下一级用户，并赋值关联
            if(ListUtil.isNotEmpty(oneLowerUserList)){
                //集合循环遍历的时候，不管是删除还是新增元素，都会改变原来的索引顺序
                for(UserRebateVo userRebateVo:oneLowerUserList){
                    //累加一级下线返利
                    if(userRebateVo.getVipFee() != null){
                        rebateAll = rebateAll.add(userRebateVo.getVipFee());
                        userRebateVo.setRebate(userRebateVo.getVipFee());
                    }
                    // 查询当前用户的一级下线
                    List<UserRebateVo> twoLowerUserList = userRebateMapper.getOneLowerUser(userRebateVo.getUserId());
                    //累加二级下线返利
                    if(ListUtil.isNotEmpty(twoLowerUserList)){
                        for(UserRebateVo urVo : twoLowerUserList){
                            if(urVo.getVipFeeUp() != null){
                                rebateAll = rebateAll.add(urVo.getVipFeeUp());
                                urVo.setRebate(urVo.getVipFeeUp());
                            }
                            urVo.setLowerLevel(2);
                        }
                    }
                    userRebateVo.setLowerUserInfoList(twoLowerUserList);
                    userRebateVo.setLowerLevel(1);
                }
                oneLowerUserList.get(0).setRebateAll(rebateAll);
            }
            return RestResponse.success(oneLowerUserList,"查询成功");
        }else{
            return RestResponse.fail("当前用户不存在");
        }

    }


    /**
     * 查询上一级邀请人
     * @param lowerUserId
     * @return
     */
    @Override
    public UserRebateEntity getUpUser(Long lowerUserId) {
        return userRebateMapper.getUpUser(lowerUserId);
    }

    /**
     * 根据用户ID和下级用户ID修改
     * @param ubEntity
     */
    @Override
    public void updateByTwoId(UserRebateEntity ubEntity) {
        userRebateMapper.updateByTwoId(ubEntity.getUserId(),ubEntity.getLowerUserId(),
                ubEntity.getVipFee(),ubEntity.getVipFeeUp());
    }

    /**
     * 判断是否是专家或者VIP
     * @param id
     * @return
     */
    @Override
    public RestResponse isVipOrExpert(Long id) {
        UserRebateVo vipOrExpert = userRebateMapper.isVipOrExpert(id);
        if(null != vipOrExpert){
            return RestResponse.success("是专家或者VIP","查询成功");
        }else{
            return RestResponse.success(null,"查询成功");
        }


    }

    /**
     * 获取会员用户的会费
     * @param userList
     * @return
     */
    private List<UserRebateVo> isVip(List<UserRebateVo> userList,Integer level){
        List<UserRebateVo> idList = new ArrayList<>();
        if(ListUtil.isNotEmpty(userList)){
            //获取会员用户,下线第一次成为会员时，会在user_rebate记录返利金额
            for(UserRebateVo userRebateVo:userList){
                BigDecimal vipFee = null;
                if(level == 1){
                     vipFee = userRebateVo.getVipFee();
                }else{
                    vipFee = userRebateVo.getVipFeeUp();
                }
                BigDecimal zero = new BigDecimal("0.00");
                if(vipFee.compareTo(zero) == 1){
                    //会员
                    userRebateVo.setRebate(vipFee);
                    idList.add(userRebateVo);
                }
            }
        }
        return idList;
    }


    /**
     * 计算一级返利金额
     * @param userList
     * @param rebate 返利比率
     * @return
     */
    private List<UserRebateVo> getMoneyCount(List<UserRebateVo> userList, BigDecimal rebate){
        if(ListUtil.isNotEmpty(userList)){
            for(UserRebateVo userRebateVo:userList){
                if(null != userRebateVo.getPrice()){
                    BigDecimal price = new BigDecimal("0.01");
                    if(userRebateVo.getPrice().multiply(rebate).compareTo(price) < 1 ){
                        userRebateVo.setRebate(price);
                    }else{
                        userRebateVo.setRebate(userRebateVo.getPrice().multiply(rebate));
                    }
                    userRebateVo.setLowerLevel(1);
                }
            }
        }
        return userList;
    }

    /**
     * 计算二级返利金额
     * @param userList
     * @param rebate 返利比率
     * @return
     */
    private List<UserRebateVo> getMoneyCountTwo(List<UserRebateVo> userList, BigDecimal rebate){
        if(ListUtil.isNotEmpty(userList)){
            for(UserRebateVo userRebateVo:userList){
                if(null != userRebateVo.getPrice()){
                    BigDecimal price = new BigDecimal("0.01");
                    if(userRebateVo.getPrice().multiply(rebate).compareTo(price) < 1 ){
                        userRebateVo.setRebate(price);
                    }else{
                        userRebateVo.setRebate(userRebateVo.getPrice().multiply(rebate));
                    }
                    userRebateVo.setLowerLevel(2);
                }
            }
        }
        return userList;
    }

}
