package com.fs.store.service.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.ResponseResult;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.utils.DateUtils;
import com.fs.company.cache.ICompanyUserCacheService;
import com.fs.company.domain.CompanyTagUser;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyTagUserMapper;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.vo.CompanyQueryVo;
import com.fs.course.mapper.FsUserCourseVideoMapper;
import com.fs.course.param.newfs.FsUserCourseBeMemberParam;
import com.fs.course.param.newfs.UserCourseVideoPageParam;
import com.fs.course.vo.newfs.FsCourseAnalysisCountVO;
import com.fs.course.vo.newfs.FsCourseAnalysisVO;
import com.fs.course.vo.newfs.FsUserCourseVideoPageListVO;
import com.fs.qw.param.QwFsUserParam;
import com.fs.qw.vo.QwFsUserVO;
import com.fs.store.domain.FsStoreOrder;
import com.fs.store.domain.FsStoreOrderItem;
import com.fs.store.domain.FsUserBill;
import com.fs.store.dto.FsStoreCartDTO;
import com.fs.store.dto.FsUserTransferParamDTO;
import com.fs.store.enums.BillDetailEnum;
import com.fs.store.mapper.FsStoreOrderMapper;
import com.fs.store.mapper.FsStoreProductAttrValueMapper;
import com.fs.store.param.h5.CourseAnalysisParam;
import com.fs.store.param.h5.FsUserPageListParam;
import com.fs.store.param.SelectCusListPageParam;
import com.fs.store.param.h5.UserStatisticsCommonParam;
import com.fs.store.service.IFsUserBillService;
import com.fs.store.vo.FSUserVO;
import com.fs.store.vo.FsCompanyUserListQueryVO;
import com.fs.store.vo.FsUserTuiVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.util.Asserts;
import com.fs.store.vo.h5.FsUserPageListVO;
import com.fs.store.vo.h5.UserDetailsVO;
import com.fs.store.vo.h5.UserListCountVO;
import com.fs.store.vo.h5.UserListPageVO;
import com.fs.store.vo.h5.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.store.mapper.FsUserMapper;
import com.fs.store.domain.FsUser;
import com.fs.store.service.IFsUserService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import static com.fs.store.enums.BillDetailEnum.CATEGORY_1;
import static com.fs.store.enums.BillDetailEnum.CATEGORY_3;

/**
 * 用户Service业务层处理
 *
 * @author fs
 * @date 2022-03-15
 */
@Service
@Slf4j
public class FsUserServiceImpl implements IFsUserService
{
    @Autowired
    private FsUserMapper fsUserMapper;

    @Autowired
    private FsStoreProductAttrValueMapper storeProductAttrValueMapper;

    @Autowired
    private IFsUserBillService billService;
    @Autowired
    private FsStoreOrderMapper storeOrderMapper;

    @Autowired
    private ICompanyUserCacheService companyUserCacheService;
    @Autowired
    private ICompanyUserService companyUserService;
    @Autowired
    private FsUserCourseVideoMapper userCourseVideoMapper;

    @Autowired
    private CompanyUserMapper companyUserMapper;

    @Autowired
    private CompanyTagUserMapper  companyTagUserMapper;

    /**
     * 查询用户
     *
     * @param userId 用户ID
     * @return 用户
     */
    @Override
    public FsUser selectFsUserById(Long userId)
    {
        return fsUserMapper.selectFsUserById(userId);
    }


    @Override
    public FSUserVO selectFsUserByUserId(Long userId) {
        return fsUserMapper.selectFsUserByUserId(userId);
    }

    /**
     * 查询用户列表
     *
     * @param fsUser 用户
     * @return 用户
     */
    @Override
    public List<FsUser> selectFsUserList(FsUser fsUser)
    {
        return fsUserMapper.selectFsUserList(fsUser);
    }


    @Override
    public List<FSUserVO> selectFsUserVOList(FsUser fsUser) {
        return fsUserMapper.selectFsUserVOList(fsUser);
    }

    /**
     * 新增用户
     *
     * @param fsUser 用户
     * @return 结果
     */
    @Override
    public int insertFsUser(FsUser fsUser)
    {
        fsUser.setCreateTime(DateUtils.getNowDate());
        return fsUserMapper.insertFsUser(fsUser);
    }

    /**
     * 修改用户
     *
     * @param fsUser 用户
     * @return 结果
     */
    @Override
    public int updateFsUser(FsUser fsUser)
    {
        fsUser.setUpdateTime(DateUtils.getNowDate());
        return fsUserMapper.updateFsUser(fsUser);
    }

    /**
     * 批量删除用户
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteFsUserByIds(Long[] userIds)
    {
        return fsUserMapper.deleteFsUserByIds(userIds);
    }

    /**
     * 删除用户信息
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteFsUserById(Long userId)
    {
        return fsUserMapper.deleteFsUserById(userId);
    }

    @Override
    public int decIntegral(Long uid, double usedIntegral) {
        return fsUserMapper.decIntegral(uid,usedIntegral);
    }

    @Override
    public int incPayCount(Long userId) {
        return fsUserMapper.incPayCount(userId);
    }

    @Override
    public FsUser selectFsUserByPhone(String phone) {
        return fsUserMapper.selectFsUserByPhone(phone);
    }

    @Override
    public TableDataInfo selectCusListPage(SelectCusListPageParam param) {
        Asserts.check(ObjectUtils.isNotNull(param.getPageNum()), "页数不能为空");
        Asserts.check(ObjectUtils.isNotNull(param.getPageSize()), "页大小不能为空");

        List<FsUser> fsUsers = fsUserMapper.selectCusListPage(param);
        for (FsUser fsUser : fsUsers) {
            if(ObjectUtils.isNotNull(fsUser.getStatus())){
                if(ObjectUtil.equal(0,fsUser.getStatus())){
                    fsUser.setStatusText("禁止");
                } else {
                    fsUser.setStatusText("正常");
                }
            }
            if(ObjectUtils.isNotNull(fsUser.getCompanyUserId())){
                CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(fsUser.getCompanyUserId());
                if(ObjectUtils.isNotNull(companyUser)){
                    fsUser.setCompanyUserName(String.format("%s_%d",companyUser.getUserName(),companyUser.getUserId()));
                }
            }
        }
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(fsUsers);
        tableDataInfo.setTotal(fsUserMapper.selectCusListPageCount(param));
        return tableDataInfo;
    }


    @Override
    public List<FsCompanyUserListQueryVO> selectFsCompanyUserListQuery(FsUser fsUser) {
        return fsUserMapper.selectFsCompanyUserListQuery(fsUser);
    }

    @Override
    public List<FsUserTuiVO> selectFsUserTuiList(String userId) {
        return fsUserMapper.selectFsUserTuiList(userId);
    }

    @Override
    public Long selectFsUserCount(int type,Long companyId) {
        return fsUserMapper.selectFsUserCount(type,companyId);
    }

    @Override
    @Transactional
    public void     addTuiMoney(FsStoreOrder order , List<FsStoreOrderItem> items) {
        //更新推荐人
//        FsUser user= fsUserMapper.selectFsUserById(order.getUserId());
//        if(user.getSpreadUserId()==null||user.getSpreadUserId()==0){
//            FsUser userMap=new FsUser();
//            userMap.setUserId(user.getUserId());
//            userMap.setSpreadUserId(order.getTuiUserId());
//            userMap.setIsPromoter(1);
//            fsUserMapper.updateFsUser(userMap);
//        }
        //获取一级二级佣金
        BigDecimal brokerage=BigDecimal.ZERO;
        BigDecimal brokerageTwo=BigDecimal.ZERO;
        BigDecimal brokerageThree=BigDecimal.ZERO;
        try {
            for(FsStoreOrderItem item: items){
                FsStoreCartDTO cartDTO= JSONUtil.toBean(item.getJsonInfo(),FsStoreCartDTO.class);
                if(cartDTO.getBrokerage()!=null){
                    brokerage=cartDTO.getBrokerage().multiply(new BigDecimal(cartDTO.getNum().toString()));
                }
                if(cartDTO.getBrokerageTwo()!=null){
                    brokerageTwo=cartDTO.getBrokerageTwo().multiply(new BigDecimal(cartDTO.getNum().toString()));
                }
                if(cartDTO.getBrokerageThree()!=null){
                    brokerageThree=cartDTO.getBrokerageThree().multiply(new BigDecimal(cartDTO.getNum().toString()));
                }
            }
            //返佣金
            FsUser tuiUser=null;
            //如果推广员是自己，一级拿佣金
            FsUser user= fsUserMapper.selectFsUserById(order.getUserId());
            if(user.getIsPromoter().equals(1)){
                tuiUser=user;
            }
            else{
                tuiUser= fsUserMapper.selectFsUserById(order.getTuiUserId());
            }
            //一级
            if(tuiUser!=null&&tuiUser.getIsPromoter()==1){
                if(brokerage.compareTo(BigDecimal.ZERO)==1){
                    FsUser tuiUserMap=new FsUser();
                    tuiUserMap.setUserId(tuiUser.getUserId());
                    tuiUserMap.setBrokeragePrice(tuiUser.getBrokeragePrice().add(brokerage));
                    fsUserMapper.updateFsUser(tuiUserMap);
                    billService.addBill(tuiUserMap.getUserId(), CATEGORY_3.getValue(),1,BillDetailEnum.TYPE_5.getDesc(),brokerage.doubleValue(),tuiUserMap.getBrokeragePrice().doubleValue(),"订单返佣金",order.getId().toString(),order.getUserId());
                }
            }
            //二级返
            if(tuiUser!=null){
                FsUser tuiUserTwo= fsUserMapper.selectFsUserById(tuiUser.getSpreadUserId());
                if(tuiUserTwo!=null&&tuiUserTwo.getIsPromoter()==1){
                    if(brokerageTwo.compareTo(BigDecimal.ZERO)==1){
                        FsUser tuiUserTwoMap=new FsUser();
                        tuiUserTwoMap.setUserId(tuiUserTwo.getUserId());
                        tuiUserTwoMap.setBrokeragePrice(tuiUserTwo.getBrokeragePrice().add(brokerageTwo));
                        fsUserMapper.updateFsUser(tuiUserTwoMap);
                        billService.addBill(tuiUserTwoMap.getUserId(), CATEGORY_3.getValue(),1,BillDetailEnum.TYPE_5.getDesc(),brokerageTwo.doubleValue(),tuiUserTwoMap.getBrokeragePrice().doubleValue(),"订单返佣金",order.getId().toString(),tuiUser.getUserId());
                    }
                    //三级
                    FsUser tuiUserThree= fsUserMapper.selectFsUserById(tuiUserTwo.getSpreadUserId());
                    if(tuiUserThree!=null&&tuiUserThree.getIsPromoter()==1){
                        if(brokerageThree.compareTo(BigDecimal.ZERO)==1){
                            FsUser tuiUserThreeMap=new FsUser();
                            tuiUserThreeMap.setUserId(tuiUserThree.getUserId());
                            tuiUserThreeMap.setBrokeragePrice(tuiUserThree.getBrokeragePrice().add(brokerageThree));
                            fsUserMapper.updateFsUser(tuiUserThreeMap);
                            billService.addBill(tuiUserThreeMap.getUserId(), CATEGORY_3.getValue(),1,BillDetailEnum.TYPE_5.getDesc(),brokerageThree.doubleValue(),tuiUserThreeMap.getBrokeragePrice().doubleValue(),"订单返佣金",order.getId().toString(),tuiUser.getUserId());
                        }

                    }
                }

            }
        }
        catch (Exception e){

        }
    }

    @Override
    @Transactional
    public void subTuiMoney(FsStoreOrder order) {
        FsUserBill map=new FsUserBill();
        map.setCategory(CATEGORY_3.getValue());
        map.setBusinessId(order.getId().toString());
        map.setBillType(1);
        List<FsUserBill> list=billService.selectFsUserBillList(map);
        if(list!=null&&list.size()>0){
            for(FsUserBill bill:list){
                FsUser tuiUser= fsUserMapper.selectFsUserByIdForUpdate(bill.getUserId());
                if(tuiUser!=null){
                    FsUser tuiUserMap=new FsUser();
                    tuiUserMap.setUserId(tuiUser.getUserId());
                    tuiUserMap.setBrokeragePrice(tuiUser.getBrokeragePrice().subtract(new BigDecimal(bill.getNumber())));
                    fsUserMapper.updateFsUser(tuiUserMap);
                    billService.addBill(tuiUserMap.getUserId(), CATEGORY_3.getValue(),0,BillDetailEnum.TYPE_6.getDesc(),bill.getNumber().doubleValue(),tuiUserMap.getBrokeragePrice().doubleValue(),"订单退佣金",order.getId().toString(),bill.getTuiUserId());
                }
            }
        }

    }

    @Override
    @Transactional
    public void addMoney(FsStoreOrder order) {
        FsUserBill map=new FsUserBill();
        map.setCategory(CATEGORY_3.getValue());
        map.setBusinessId(order.getId().toString());
        map.setBillType(1);
        List<FsUserBill> list=billService.selectFsUserBillList(map);
        if(list!=null&&list.size()>0){
            for(FsUserBill bill:list){
                FsUser tuiUser= fsUserMapper.selectFsUserByIdForUpdate(bill.getUserId());
                if(tuiUser!=null){
                    FsUser tuiUserMap=new FsUser();
                    tuiUserMap.setUserId(tuiUser.getUserId());
                    tuiUserMap.setNowMoney(tuiUser.getNowMoney().add(new BigDecimal(bill.getNumber())));
                    tuiUserMap.setBrokeragePrice(tuiUser.getBrokeragePrice().subtract(new BigDecimal(bill.getNumber())));
                    fsUserMapper.updateFsUser(tuiUserMap);
                    billService.addBill(tuiUserMap.getUserId(), CATEGORY_3.getValue(),0,BillDetailEnum.TYPE_6.getDesc(),bill.getNumber().doubleValue(),tuiUserMap.getBrokeragePrice().doubleValue(),"订单分佣金",order.getId().toString(),bill.getTuiUserId());
                    billService.addBill(tuiUserMap.getUserId(), CATEGORY_1.getValue(),1,BillDetailEnum.TYPE_5.getDesc(),bill.getNumber().doubleValue(),tuiUserMap.getNowMoney().doubleValue(),"订单分佣金",order.getId().toString(),bill.getTuiUserId());
                }
            }
        }
        FsStoreOrder orderMap=new FsStoreOrder();
        orderMap.setId(order.getId());
        orderMap.setTuiUserMoneyStatus(1);
        storeOrderMapper.updateFsStoreOrder(orderMap);
    }

    @Override
    public FsUser selectFsUserByMaOpenId(String openid) {
        return fsUserMapper.selectFsUserByMaOpenId(openid);
    }

    @Override
    public FsUser selectFsUserByMpOpenId(String openid) {
        return fsUserMapper.selectFsUserByMpOpenId(openid);
    }

    @Override
    public FsUser selectFsUserByUnionId(String unionId) {
        return fsUserMapper.selectFsUserByUnionId(unionId);
    }

    @Override
    public FsUser selectFsUserByUserCode(String userCode) {
        return fsUserMapper.selectFsUserByUserCode(userCode);
    }


    //CRM客户绑定 小程序客户之 查询小程序客户
    @Override
    public List<QwFsUserVO> selecQwFsUserListVO(QwFsUserParam qwFsUserParam) {

        return  fsUserMapper.selecQwFsUserListVO(qwFsUserParam);
    }

    @Override
    public List<QwFsUserVO> selectQwFsUserListVO(QwFsUserParam qwFsUserParam) {
        return fsUserMapper.selectQwFsUserListVO(qwFsUserParam);
    }

    @Override
    public R clearUserVip(Long userId) {
        FsUser user = new FsUser();
        user.setUserId(userId);
        user.setIsVip(0);
        user.setVipStartDate(null);
        user.setVipEndDate(null);
        if (fsUserMapper.updateFsUser(user)>0){
            return R.ok("清除成功");
        }
        return R.error("清除vip失败");
    }

    @Override
    public FsUser selectFsUserByUnionid(String unionId) {
        return fsUserMapper.selectFsUserByUnionid(unionId);
    }

    @Override
    public List<FsUser> getUserListLimit(FsUser fsUser) {
        return fsUserMapper.selectFsUserListLimit(fsUser);
    }

    @Override
    public List<FsUserPageListVO> selectFsUserPageList(FsUserPageListParam param) {
        return fsUserMapper.selectFsUserPageList(param);
    }

    @Override
    public List<FsUserPageListVO> selectFsUserPageListNew(FsUserPageListParam param) {
        return fsUserMapper.selectFsUserPageListNew(param);
    }

    @Override
    public Long selectFsUserCount(FsUserPageListParam param) {
        return fsUserMapper.selectFsUserPageListCount(param);
    }

    @Override
    public UserListPageVO getUserNumber(Long userId) {
        List<UserListCountVO> list = fsUserMapper.getUserNumber(userId);
        Map<String, Integer> map = list.stream()
                .collect(Collectors.toMap(UserListCountVO::getStatus, UserListCountVO::getNum, (v1, v2) -> v1));
        UserListPageVO pageVO = new UserListPageVO();
        pageVO.setNumber(map.getOrDefault("1", 0));
        pageVO.setBlackNum(map.getOrDefault("0", 0));
        return pageVO;
    }

    @Override
    public UserDetailsVO getUserDetails(Long userId, Long fsUserId, String dateTag) {
        UserDetailsVO countAnswer = fsUserMapper.getCountAnswer(userId, fsUserId, dateTag);
        UserDetailsVO countRedPacket = fsUserMapper.getCountRedPacket(userId, fsUserId, dateTag);
        UserDetailsVO vo = new UserDetailsVO();
        if (countRedPacket != null) {
            BeanUtils.copyProperties(countRedPacket, vo);
        }
        if (countAnswer != null) {
            vo.setAnswerTime(countAnswer.getAnswerTime());
            vo.setAnswerRightTime(countAnswer.getAnswerRightTime());
        }
        return vo;
    }

    @Override
    public Boolean disabledUser(String[] ids, boolean status) {
        boolean result;
        if (status) {
            // 启用
            result = fsUserMapper.batchUpdateFsUserByIds(ids, 1) > 0;
        } else {
            // 禁用
            result = fsUserMapper.batchUpdateFsUserByIds(ids, 0) > 0;
        }
        return result;
    }
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    public void transfer(FsUserTransferParamDTO param) {
        Asserts.check(ObjectUtils.isNotNull(param.getSourceCompanyUserId()), "来源用户不能为空！");
        Asserts.check(ObjectUtils.isNotNull(param.getTargetCompanyUserId()), "转移用户不能为空！");
        Asserts.check(CollectionUtils.isNotEmpty(param.getUserIds()), "要转移的客户列表不能为空！");

        fsUserMapper.transferCompanyUser(param);
    }

    /**
     * 查询销售会员总数,今日新增会员数
     * @param companyUserId 销售ID
     * @return map
     */
    @Override
    public Map<String, Long> getUserVipCountByCompanyUserId(Long companyUserId) {
        return fsUserMapper.getUserVipCountByCompanyUserId(companyUserId);
    }

    @Override
    public FsUserSummaryCountVO userSummaryCount(Long userId) {
        FsUserSummaryCountVO fsUserSummaryCountVO = fsUserMapper.countUserSummary(userId);
        List<FsUserSummaryCountTagVO> countTagList = fsUserMapper.countTag(userId);
        fsUserSummaryCountVO.setTagList(countTagList);
        return fsUserSummaryCountVO;
    }

    @Override
    public FsUserStatisticsVO userStatistics(UserStatisticsCommonParam param) {
        return getUserStatistics(param);
    }

    private FsUserStatisticsVO getUserStatistics(UserStatisticsCommonParam param) {
        FsUserStatisticsVO fsUserStatisticsVO = new FsUserStatisticsVO();

        // 获取课程统计
        Map<String, Long> couserMap = fsUserMapper.countUserCourse(param);
        if (couserMap != null) {
            fsUserStatisticsVO.setCourseWatchNum(couserMap.get("courseWatchNum").intValue()).setCourseCompleteNum(couserMap.get("courseCompleteNum").intValue());

            if (couserMap.get("courseCompleteNum") != null && couserMap.get("courseWatchNum") > 0) {
                int courseCompleteRate = BigDecimal.valueOf(couserMap.get("courseCompleteNum"))
                        .divide(BigDecimal.valueOf(couserMap.get("courseWatchNum")), 2, RoundingMode.HALF_UP)
                        .multiply(BigDecimal.valueOf(100))
                        .intValue();
                fsUserStatisticsVO.setCourseCompleteRate(courseCompleteRate);
            }
        }

        // 获取答题统计
        Map<String, Long> answerMap = fsUserMapper.countUserAnswer(param);
        if (answerMap != null) {
            fsUserStatisticsVO.setAnswerNum(answerMap.get("answerNum").intValue()).setAnswerRightNum(answerMap.get("answerRightNum").intValue());

            if (answerMap.get("answerRightNum") != null && answerMap.get("answerNum") > 0) {
                int answerCompleteRate = BigDecimal.valueOf(answerMap.get("answerRightNum"))
                        .divide(BigDecimal.valueOf(answerMap.get("answerNum")), 2, RoundingMode.HALF_UP)
                        .multiply(BigDecimal.valueOf(100))
                        .intValue();
                fsUserStatisticsVO.setAnswerRightRate(answerCompleteRate);
            }
        }

        // 获取红包统计
        Map<String, Object> redPacketMap = fsUserMapper.countUserRedPacket(param);
        if(redPacketMap != null && redPacketMap.get("redPacketNum") != null && redPacketMap.get("redPacketAmount") != null) {
            fsUserStatisticsVO.setRedPacketNum(Integer.parseInt(redPacketMap.get("redPacketNum").toString()))
                    .setRedPacketAmount(new BigDecimal(redPacketMap.get("redPacketAmount").toString()));
        }
        return fsUserStatisticsVO;
    }

    @Override
    public FsUserStatisticsVO userStatisticsDetails(UserStatisticsCommonParam param) {
        FsUserStatisticsVO userStatisticsVO = getUserStatistics(param);

        //统计课程数据详情，在查询统计详情的时候需要显示
        Map<String, Long> courseDetailsMap = fsUserMapper.countCourseDetails(param);
        if(courseDetailsMap != null && courseDetailsMap.get("courseNum") != null && courseDetailsMap.get("videoNum") != null && courseDetailsMap.get("courseUserNum") != null){
            userStatisticsVO.setCourseNum(Integer.parseInt(courseDetailsMap.get("courseNum").toString()))
                    .setVideoNum(Integer.parseInt(courseDetailsMap.get("videoNum").toString()))
                    .setCourseUserNum(Integer.parseInt(courseDetailsMap.get("courseUserNum").toString()));
        }
        return userStatisticsVO;
    }

    @Override
    public List<FsUserRankingVO> userRanking(Long userId, String startTime, String endTime, String periodId, String videoId, String order, Integer type) {
        List<FsUserRankingVO> listVO = Collections.emptyList();
        if(type == 1){
            //按完播率
            listVO = fsUserMapper.countUserRankingByComplete(userId, startTime, endTime, periodId, videoId, order);
        }
        if(type == 2){
            //按正确率
            listVO = fsUserMapper.countUserRankingByRight(userId, startTime, endTime, periodId, videoId, order);
        }
        return listVO;
    }

    @Override
    public List<FsCourseRankingVO> courseRanking(Long userId, String startTime, String endTime, String periodId, String videoId, String order, Integer type) {
        List<FsCourseRankingVO> list = Collections.emptyList();
        if(type == 1){
            list = fsUserMapper.countCourseRankingByComplete(userId, startTime, endTime, periodId, videoId, order);
        }
        if(type == 2){
            list = fsUserMapper.countCourseRankingByRight(userId, startTime, endTime, periodId, videoId, order);
        }

        return list;
    }

    @Override
    public List<FsUserGraphicStatisticsVO> graphicStatistics(UserStatisticsCommonParam param) {
        FsUserStatisticsVO userStatistics = getUserStatistics(param);
        List<FsUserGraphicStatisticsVO> list = new ArrayList<>();
        list.add(new FsUserGraphicStatisticsVO("观看人数",userStatistics.getCourseWatchNum(), userStatistics.getCourseWatchNum()));
        list.add(new FsUserGraphicStatisticsVO("完播人数", userStatistics.getCourseCompleteNum(), userStatistics.getCourseCompleteNum()));
        list.add(new FsUserGraphicStatisticsVO("答题人数", userStatistics.getAnswerNum(), userStatistics.getAnswerNum()));
        list.add(new FsUserGraphicStatisticsVO("正确人数", userStatistics.getAnswerRightNum(), userStatistics.getAnswerRightNum()));
        list.add(new FsUserGraphicStatisticsVO("答题红包数", userStatistics.getRedPacketNum(), userStatistics.getRedPacketNum()));
        return list;
    }

    @Override
    public List<FsCourseAnalysisVO> courseAnalysis(CourseAnalysisParam param) {
        //1、查询课程视频信息
        UserCourseVideoPageParam userCourseVideoPageParam = new UserCourseVideoPageParam();
        BeanUtils.copyProperties(param, userCourseVideoPageParam);
        List<FsUserCourseVideoPageListVO> videoList = userCourseVideoMapper.selectFsUserCourseVideoPageList(userCourseVideoPageParam);

        //2、查询统计
        List<FsCourseAnalysisCountVO> courseCountList = fsUserMapper.courseAnalysisCourseCount(param);

        List<FsCourseAnalysisCountVO> redPacketCountList = fsUserMapper.courseAnalysisRedPacketCount(param);
        List<FsCourseAnalysisCountVO> answerCountList = fsUserMapper.courseAnalysisAnswerCount(param);

        //3、转化为map
        Map<Long, FsCourseAnalysisCountVO> courseMap = courseCountList.stream()
                .collect(Collectors.toMap(
                        FsCourseAnalysisCountVO::getVideoId,
                        Function.identity()
                ));
        Map<Long, FsCourseAnalysisCountVO> redPacketMap = redPacketCountList.stream()
                .collect(Collectors.toMap(
                        FsCourseAnalysisCountVO::getVideoId,
                        Function.identity()
                ));
        Map<Long, FsCourseAnalysisCountVO> answerMap = answerCountList.stream()
                .collect(Collectors.toMap(
                        FsCourseAnalysisCountVO::getVideoId,
                        Function.identity()
                ));

        //4、处理数据
        return videoList.stream().map(v -> {
            FsCourseAnalysisVO allVO = new FsCourseAnalysisVO();
            BeanUtils.copyProperties(v, allVO);

            FsCourseAnalysisCountVO countVO = new FsCourseAnalysisCountVO();
            FsCourseAnalysisCountVO courseVO = courseMap.getOrDefault(v.getVideoId(), countVO);
            FsCourseAnalysisCountVO redPacketVO = redPacketMap.getOrDefault(v.getVideoId(), countVO);
            FsCourseAnalysisCountVO answerVO = answerMap.getOrDefault(v.getVideoId(), countVO);
            //单独赋值
            countVO.setVideoId(v.getVideoId()).setCourseWatchNum(courseVO.getCourseWatchNum()).setCourseCompleteNum(courseVO.getCourseWatchNum())
                    .setCompleteRate(courseVO.getCompleteRate() != null ? courseVO.getCompleteRate() : new BigDecimal(BigInteger.ZERO));
            countVO.setRedPacketNum(redPacketVO.getRedPacketNum())
                    .setRedPacketAmount(redPacketVO.getRedPacketAmount() != null ? redPacketVO.getRedPacketAmount() : new BigDecimal(BigInteger.ZERO));
            countVO.setAnswerNum(answerVO.getAnswerNum()).setAnswerRightNum(answerVO.getAnswerRightNum())
                    .setAnswerRightRate(answerVO.getAnswerRightRate()!=null ? answerVO.getAnswerRightRate() : new BigDecimal(BigInteger.ZERO));
            allVO.setCountVO(countVO);
            return allVO;
        }).collect(Collectors.toList());
    }

    @Override
    public CompanyUserSummaryCountVO companyUserSummaryCount(Long userId, String companyUserId) {
        CompanyUserSummaryCountVO companyUserCount = fsUserMapper.companyUserCount(companyUserId);
        CompanyUserSummaryCountVO newUserRedPacketCount = fsUserMapper.newUserRedPacketCount(companyUserId);
        CompanyUserSummaryCountVO vo = new CompanyUserSummaryCountVO();
        BeanUtils.copyProperties(companyUserCount, vo);
        vo.setUserRedPacketNum(newUserRedPacketCount.getUserRedPacketNum());
        vo.setTodayUserRedPacketAmount(newUserRedPacketCount.getTodayUserRedPacketAmount());
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<Boolean> becomeMember(FsUserCourseBeMemberParam param) {
        //查询用户
        FsUser fsUser = fsUserMapper.selectFsUserById(param.getUserId());
        if (Objects.isNull(fsUser)){
            return ResponseResult.fail(401,"未授权");
        }
        if (fsUser.getCompanyUserId() != null && !param.getCompanyUserId().equals(fsUser.getCompanyUserId())){
            return ResponseResult.fail(500,"该用户已成为其他销售会员");
        }

        //判断该销售是否存在
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(param.getCompanyUserId());
        if (Objects.isNull(companyUser)){
            return ResponseResult.fail(500,"销售不存在");
        }

        // 关联销售
        fsUser.setCompanyId(param.getCompanyId());
        fsUser.setCompanyUserId(param.getCompanyUserId());
        fsUserMapper.updateFsUser(fsUser);

        // 不为空则添加新标签
        if (Objects.nonNull(param.getTagIds()) && param.getTagIds().length > 0) {
            //关联会员标签，先删除再新增
            Map<String, Object> map = new HashMap<>();
            map.put("userId", param.getUserId());
            map.put("companyId", fsUser.getCompanyId());
            map.put("companyUserId", fsUser.getCompanyUserId());
            companyTagUserMapper.deleteCompanyTagUserByMap(map);

            CompanyTagUser companyTagUser = new CompanyTagUser();
            companyTagUser.setUserId(param.getUserId());
            companyTagUser.setCompanyId(fsUser.getCompanyId());
            companyTagUser.setCompanyUserId(fsUser.getCompanyUserId());
            companyTagUser.setTagIds(String.join(",", param.getTagIds()));
            companyTagUser.setCreateTime(new Date());
            companyTagUserMapper.insertCompanyTagUser(companyTagUser);
        }
        return ResponseResult.ok(Boolean.TRUE);
    }
}
