package com.fs.hisStore.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fs.common.constant.HttpStatus;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.ResponseResult;
import com.fs.common.core.domain.entity.SysDictData;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.DictUtils;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.cache.ICompanyTagCacheService;
import com.fs.company.cache.ICompanyUserCacheService;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyTag;
import com.fs.company.domain.CompanyTagUser;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyMapper;
import com.fs.company.mapper.CompanyTagMapper;
import com.fs.company.mapper.CompanyTagUserMapper;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.company.service.ICompanyTagService;
import com.fs.company.service.ICompanyUserService;
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.his.domain.FsUserBill;
import com.fs.his.vo.OptionsVO;
import com.fs.live.domain.LiveOrder;
import com.fs.qw.param.QwFsUserParam;
import com.fs.qw.vo.QwFsUserVO;
import com.fs.hisStore.domain.*;
import com.fs.hisStore.dto.FsStoreCartDTO;
import com.fs.hisStore.dto.FsUserTransferParamDTO;
import com.fs.hisStore.enums.BillDetailEnum;
import com.fs.hisStore.mapper.FsStoreOrderScrmMapper;
import com.fs.hisStore.mapper.FsStoreProductAttrValueScrmMapper;
import com.fs.hisStore.mapper.FsUserCourseCountScrmMapper;
import com.fs.hisStore.mapper.FsUserScrmMapper;
import com.fs.hisStore.param.SelectCusListPageParam;
import com.fs.hisStore.param.h5.CourseAnalysisParam;
import com.fs.hisStore.param.h5.FsUserPageListParam;
import com.fs.hisStore.param.h5.UserStatisticsCommonParam;
import com.fs.hisStore.service.IFsUserBillScrmService;
import com.fs.hisStore.service.IFsUserCompanyUserScrmService;
import com.fs.hisStore.service.IFsUserProjectTagScrmService;
import com.fs.hisStore.service.IFsUserScrmService;
import com.fs.hisStore.service.cache.IFsUserCourseCountCacheService;
import com.fs.hisStore.vo.FSUserVO;
import com.fs.hisStore.vo.FsCompanyUserListQueryVO;
import com.fs.hisStore.vo.FsUserLastCount;
import com.fs.hisStore.vo.FsUserTuiVO;
import com.fs.hisStore.vo.h5.*;
import com.fs.system.mapper.SysDictDataMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.util.Asserts;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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 static com.fs.hisStore.enums.BillDetailEnum.CATEGORY_1;
import static com.fs.hisStore.enums.BillDetailEnum.CATEGORY_3;

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

    @Autowired
    private FsStoreProductAttrValueScrmMapper storeProductAttrValueMapper;

    @Autowired
    private IFsUserBillScrmService billService;
    @Autowired
    private FsStoreOrderScrmMapper storeOrderMapper;

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

    @Autowired
    private CompanyUserMapper companyUserMapper;

    @Autowired
    private CompanyTagUserMapper  companyTagUserMapper;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private IFsUserCourseCountCacheService fsUserCourseCountCacheService;

    @Autowired
    private ICompanyTagCacheService companyTagCacheService;

    @Autowired
    private IFsUserCompanyUserScrmService userCompanyUserService;

    @Autowired
    private ICompanyTagService companyTagService;

    @Autowired
    CompanyTagMapper companyTagMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private FsUserCourseCountScrmMapper fsUserCourseCountMapper;

    @Autowired
    private IFsUserProjectTagScrmService userProjectTagService;

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


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

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


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

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

    /**
     * 修改用户
     *
     * @param fsUser 用户
     * @return 结果
     */
    @Override
    public int updateFsUser(FsUserScrm fsUser)
    {
        String nickname = fsUser.getNickname();
        if (StringUtils.isNotBlank(nickname)){
            if (nickname.length()>100){
                return 0;
            }
        }
        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 FsUserScrm 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<FsUserScrm> fsUsers = fsUserMapper.selectCusListPage(param);
        for (FsUserScrm fsUser : fsUsers) {
            if(ObjectUtils.isNotNull(fsUser.getStatus())){
                if(ObjectUtil.equal(0,fsUser.getStatus())){
                    fsUser.setStatusText("禁止");
                } else {
                    fsUser.setStatusText("正常");
                }
            }
        }
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(fsUsers);
        tableDataInfo.setTotal(fsUserMapper.selectCusListPageCount(param));
        return tableDataInfo;
    }


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

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

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

    @Override
    @Transactional
    public void     addTuiMoney(FsStoreOrderScrm order , List<FsStoreOrderItemScrm> 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(FsStoreOrderItemScrm 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()));
                }
            }
            //返佣金
            FsUserScrm tuiUser=null;
            //如果推广员是自己，一级拿佣金
            FsUserScrm 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){
                    FsUserScrm tuiUserMap=new FsUserScrm();
                    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,tuiUserMap.getBrokeragePrice(),"订单返佣金",order.getId().toString(),order.getUserId());
                }
            }
            //二级返
            if(tuiUser!=null){
                FsUserScrm tuiUserTwo= fsUserMapper.selectFsUserById(tuiUser.getSpreadUserId());
                if(tuiUserTwo!=null&&tuiUserTwo.getIsPromoter()==1){
                    if(brokerageTwo.compareTo(BigDecimal.ZERO)==1){
                        FsUserScrm tuiUserTwoMap=new FsUserScrm();
                        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,tuiUserTwoMap.getBrokeragePrice(),"订单返佣金",order.getId().toString(),tuiUser.getUserId());
                    }
                    //三级
                    FsUserScrm tuiUserThree= fsUserMapper.selectFsUserById(tuiUserTwo.getSpreadUserId());
                    if(tuiUserThree!=null&&tuiUserThree.getIsPromoter()==1){
                        if(brokerageThree.compareTo(BigDecimal.ZERO)==1){
                            FsUserScrm tuiUserThreeMap=new FsUserScrm();
                            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,tuiUserThreeMap.getBrokeragePrice(),"订单返佣金",order.getId().toString(),tuiUser.getUserId());
                        }

                    }
                }

            }
        }
        catch (Exception e){
            log.error("分佣异常",e);
        }
    }

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

    }

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

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

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

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

    @Override
    public FsUserScrm selectFsUserByCourseMaOpenId(String openId) {
        return fsUserMapper.selectFsUserByCourseMaOpenId(openId);
    }

    @Override
    public FsUserScrm 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) {
        FsUserScrm user = new FsUserScrm();
        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 FsUserScrm selectFsUserByUnionid(String unionId) {
        return fsUserMapper.selectFsUserByUnionid(unionId);
    }

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

    @Override
    public PageInfo<FsUserPageListVO> selectFsUserPageList(FsUserPageListParam param) {
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(param.getUserId());
        if (companyUser!=null && companyUser.isAdmin()){
            param.setUserId(0L);
            param.setCompanyId(companyUser.getCompanyId());
        }
        //筛选问题
        if (StringUtils.isNotBlank(param.getCompanyUserId())){
            param.setUserId(Long.valueOf(param.getCompanyUserId()));
        }

        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        if (param.getTagIds() != null && param.getTagIds().length > 0) {
            boolean containsZero = Arrays.asList(param.getTagIds()).contains("0");
            // 如果包含 "0"，则设置 isNullTag 为 true
            System.out.println("是否包含 0：" + containsZero + "，参数：" + Arrays.toString(param.getTagIds()));
            if (containsZero) {
                param.setIsNullTag(true);
            }
        }
        List<FsUserPageListVO> fsUserPageListVOS = fsUserMapper.selectFsUserPageList(param);


        List<SysDictData> courseProject = dictDataMapper.selectDictDataByType("sys_course_project");
        for (FsUserPageListVO fsUserPageListVO : fsUserPageListVOS) {
            // 项目
            courseProject.stream()
                    .filter(c -> c.getDictValue().equals(fsUserPageListVO.getProjectId().toString()))
                    .findFirst()
                    .ifPresent(c -> fsUserPageListVO.setProjectName(c.getDictLabel()));
            if (StringUtils.isEmpty(fsUserPageListVO.getNickname())){
                fsUserPageListVO.setNickname("用户暂未授权昵称");
            }
        }

        return new PageInfo<>(fsUserPageListVOS);

    }

    private static StringBuilder removeRepeatFansTag(FsUserPageListVO fsUserPageListVO) {
        String tag = fsUserPageListVO.getTag();
        String[] splitTag = tag.split(",");
        StringBuilder newTag = new StringBuilder();
        for (String s : splitTag) {
            if(!"重粉".equals(s)){
                newTag.append(s);
            }
        }
        return newTag;
    }

    @Override
    public TableDataInfo selectFsUserPageListNew(FsUserPageListParam param) {
        // 找出下级销售
        String companyUserId = param.getCompanyUserId();
        if(StringUtils.isNotBlank(companyUserId)) {
            Long companyUser = Long.parseLong(companyUserId);
            Set<Long> userIds = companyUserCacheService.selectUserAllCompanyUserId(companyUser);
            if (userIds != null || userIds.size() <= 1) {
                if (param.getIsAdmin() != null && param.getIsAdmin()) {
                    List<CompanyUser> companyUsers = companyUserMapper.selectCompanyUserByCompanyId(param.getCompanyId());
                    userIds = companyUsers.stream().map(CompanyUser::getUserId).collect(Collectors.toSet());
                }
            }
            param.setCompanyUserIds(userIds);
        }

        List<FsUserPageListVO> fsUserPageListVOS = fsUserMapper.selectFsUserPageListNew(param);
        Map<Long, CompanyTag> tagMap = companyTagCacheService.queryAllTagMap();
        //获取会员的最新的看课状态和最后看课时间
        Set<Long> userIds = fsUserPageListVOS.stream().map(FsUserPageListVO::getUserId).collect(Collectors.toSet());
        List<FsUserLastCount> fsUserCourseCounts = Collections.emptyList();
        if(!userIds.isEmpty()){
            fsUserCourseCounts = fsUserCourseCountMapper.selectUserLastCount(userIds);
        }
        Map<Long, FsUserLastCount> countMap = fsUserCourseCounts.stream().collect(Collectors.toMap(FsUserLastCount::getUserId, Function.identity()));

        for (FsUserPageListVO item : fsUserPageListVOS) {
            if(item.getCompanyUserId() != null) {
                String companyUserName = companyUserCacheService.selectCompanyUserNameUserById(item.getCompanyUserId());
                if(companyUserName != null) {
                    item.setCompanyUserNickName(companyUserName);
                }
            }
            if(item.getPhone() != null) {
                item.setPhone(ParseUtils.parsePhone(item.getPhone()));
            }
            if(item.getStatus() != null) {
                String userStatus = DictUtils.getDictLabel("user_status", String.valueOf(item.getStatus()));
                if(StringUtils.isNotBlank(userStatus)){
                    item.setStatusText(userStatus);
                }
            }
            if(item.getUserId() != null) {
                FsUserCourseCountScrm byUserId = fsUserCourseCountCacheService.findByUserId(item.getUserId());
                if(byUserId != null) {
                    item.setWatchCourseCount(byUserId.getWatchCourseCount());
                    item.setMissCourseCount(byUserId.getMissCourseCount());
                    item.setMissCourseStatus(byUserId.getMissCourseStatus());
                    if(StringUtils.isNotEmpty(byUserId.getPartCourseCount())){
                        item.setPartCourseCount(new BigDecimal(byUserId.getPartCourseCount()).longValue());
                    }
//                    item.setCourseCountStatus(byUserId.getStatus());
                    item.setStopWatchDays(byUserId.getStopWatchDays());
                    item.setCompleteWatchDate(byUserId.getCompleteWatchDate());
                    item.setLastWatchDate(byUserId.getLastWatchDate());
                }
                FsUserLastCount fsUserCourseCount = countMap.get(item.getUserId());
                if(fsUserCourseCount != null){
                    item.setCourseCountStatus(fsUserCourseCount.getStatus());
                }
                String userTagByUserId = companyTagCacheService
                        .findUserTagByUserId(item.getUserId(),item.getCompanyUserId());
                if(StringUtils.isNotEmpty(userTagByUserId)) {
                    String[] split = userTagByUserId.split(",");
                    Set<String> tagNames = new HashSet<>();
                    for (String tag : split) {
                        if(StringUtils.isNotBlank(tag)) {
                            Long tagL = Long.parseLong(tag);
                            CompanyTag companyTag = tagMap.get(tagL);
                            if(companyTag != null) {
                                tagNames.add(companyTag.getTag());
                            }
                        }
                    }
                    item.setTagIds(userTagByUserId);
                    item.setTag(String.join(",",tagNames));
                }

                // 是否宠粉
//                Integer isRepeat = qwExternalContactCacheService.selectQwIsRepeat(item.getUserId());
//                if(isRepeat != null) {
//                    item.setIsRepeat(isRepeat);
//                }
            }
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(fsUserPageListVOS);

        rspData.setTotal(this.selectFsUserCount(param));
        return rspData;
    }

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

    @Override
    public UserListPageVO getUserNumber(Long userId) {
        // 判断是否是管理员
        Long companyId = null;
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(userId);
        if (companyUser != null && companyUser.isAdmin()){
            userId = 0L;
            companyId = companyUser.getCompanyId();
        }
        List<UserListCountVO> list = fsUserMapper.getUserNumber(userId, companyId);
        Map<String, Integer> map = list.stream()
                .collect(Collectors.toMap(UserListCountVO::getStatus, UserListCountVO::getNum, (v1, v2) -> v1 + v2));
        UserListPageVO pageVO = new UserListPageVO();
        Integer normalNum = map.getOrDefault("1", 0);
        Integer smallBlackNum = map.getOrDefault("0", 0);
        Integer blackNum = map.getOrDefault("2", 0);

        // 黑名单人数加上重粉的数量，正常人数去掉重粉数量
        int repeatUserNumber = fsUserMapper.getRepeatUserNumber(userId);
        pageVO.setNumber(normalNum - repeatUserNumber);
        pageVO.setBlackNum(blackNum + repeatUserNumber);
        pageVO.setSmallBlackNum(smallBlackNum + repeatUserNumber);

        return pageVO;
    }

    @Override
    public UserDetailsVO getUserDetails(Long userId, Long fsUserId, String dateTag, Long userCompanyId) {
        UserDetailsVO countWatchCourse = fsUserMapper.getCountWatchCourse(userId, fsUserId, dateTag,userCompanyId);
        FsUserCompanyUserScrm fsUserCompanyUser = userCompanyUserService.selectFsUserCompanyUserById(userCompanyId);

        UserDetailsVO countAnswer = fsUserMapper.getCountAnswer(fsUserCompanyUser.getCompanyUserId(), fsUserId, dateTag);
        UserDetailsVO countRedPacket = fsUserMapper.getCountRedPacket(fsUserCompanyUser.getCompanyUserId(), fsUserId, dateTag);
        UserDetailsVO vo = new UserDetailsVO();
        if (countWatchCourse != null){
            BeanUtils.copyProperties(countWatchCourse, vo);
        }
        if (countRedPacket != null) {
            vo.setAnswerRedPacketTime(countRedPacket.getAnswerRedPacketTime());
            vo.setAnswerRedPacketAmount(countRedPacket.getAnswerRedPacketAmount());
        } else {
            vo.setAnswerRedPacketAmount(BigDecimal.ZERO);
        }
        if (countAnswer != null) {
            vo.setAnswerTime(countAnswer.getAnswerTime());
            vo.setAnswerRightTime(countAnswer.getAnswerRightTime());
        }
        return vo;
    }

    @Override
    public Integer selectFsUserByUserIds(String[] userIds, Long companyUserId) {
        return fsUserMapper.selectFsUserByUserIds(userIds, companyUserId);
    }

    @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) {
        // 判断是否是管理员
        Long companyId = null;
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(userId);
        if (companyUser != null && companyUser.isAdmin()){
            userId = 0L;
            companyId = companyUser.getCompanyId();
        }
        FsUserSummaryCountVO fsUserSummaryCountVO = fsUserMapper.countUserSummary(userId, companyId);
        List<FsUserSummaryCountTagVO> countTagList = fsUserMapper.countTag(userId, companyId);
        fsUserSummaryCountVO.setTagList(countTagList);
        return fsUserSummaryCountVO;
    }

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

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

        // 判断是否是管理员
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(param.getUserId());
        if (companyUser != null && companyUser.isAdmin()){
            param.setUserId(0L);
            param.setCompanyId(companyUser.getCompanyId());
        }
        // 获取课程统计
//        Map<String, Long> couserMap = fsUserMapper.countUserCourse(param);
        Map<String, Long> couserMap = fsUserMapper.countUserCourse2(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);
//        FsUserStatisticsVO userStatisticsVO = getUserStatistics2(param);

        // 判断是否是管理员
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(param.getUserId());
        if (companyUser != null && companyUser.isAdmin()){
            param.setUserId(0L);
        }
        //统计课程数据详情，在查询统计详情的时候需要显示
        Map<String, Long> courseDetailsMap = fsUserMapper.countCourseDetailsNew(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;
    }

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

        // 判断是否是管理员
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(param.getUserId());
        if (companyUser != null && companyUser.isAdmin()){
            param.setUserId(0L);
            param.setCompanyId(companyUser.getCompanyId());
        }
        // 获取课程统计
        Map<String, Long> couserMap = fsUserMapper.countUserCourse2(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 List<FsUserRankingVO> userRanking(Long userId, String startTime, String endTime, String periodId, String videoId, String order, Integer type) {
        List<FsUserRankingVO> listVO = Collections.emptyList();
        // 判断是否是管理员
        Long companyId = null;
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(userId);
        if (companyUser != null && companyUser.isAdmin()){
            userId = 0L;
            companyId = companyUser.getCompanyId();
        }
        if(type == 1){
            //按完播率
            listVO = fsUserMapper.countUserRankingByComplete(userId, companyId, startTime, endTime, periodId, videoId, order);
        }
        if(type == 2){
            //按正确率
            listVO = fsUserMapper.countUserRankingByRight(userId, companyId, 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) {
        // 判断是否是管理员
        Long companyId = null;
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(userId);
        if (companyUser != null && companyUser.isAdmin()){
            userId = 0L;
            companyId = companyUser.getCompanyId();
        }
        List<FsCourseRankingVO> list = Collections.emptyList();
        if(type == 1){
            list = fsUserMapper.countCourseRankingByComplete(userId, companyId, startTime, endTime, periodId, videoId, order);
        }
        if(type == 2){
            list = fsUserMapper.countCourseRankingByRight(userId, companyId, 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()));
        list.sort(Comparator.comparingInt(FsUserGraphicStatisticsVO::getValue).reversed());
        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) {
        // 判断是否是管理员
        Long companyId = null;
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(userId);
        if (companyUser != null && companyUser.isAdmin()){
            companyUserId = String.valueOf(0);
            companyId = companyUser.getCompanyId();
        }
        CompanyUserSummaryCountVO companyUserCount = fsUserMapper.companyUserCount(companyUserId, companyId);
        CompanyUserSummaryCountVO newUserRedPacketCount = fsUserMapper.newUserRedPacketCount(companyUserId, companyId);
        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) {
        //查询用户
        FsUserScrm fsUser = fsUserMapper.selectFsUserById(param.getUserId());
        if (Objects.isNull(fsUser)){
            return ResponseResult.fail(404,"当前用户信息不存在");
        }

        //判断该销售是否存在
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(param.getCompanyUserId());
        if (Objects.isNull(companyUser)){
            return ResponseResult.fail(405,"销售不存在");
        }
        // 通过字段值判断该销售是否允许注册会员
        if(companyUser.getIsAllowedAllRegister() != null && companyUser.getIsAllowedAllRegister() == 0){
            return ResponseResult.fail(407,"不允许注册会员，请联系管理员");
        }

        // 逻辑调整：如果会员已经绑定了销售，直接提示，不添加重粉数据了-2025年6月16日14点53分
        // 逻辑调整：会员与销售的绑定关系通过中间表关联 /20250625 17:13
        FsUserCompanyUserScrm userCompanyUser = userCompanyUserService.selectByUserIdAndProjectId(fsUser.getUserId(), param.getProjectId());
        if (Objects.nonNull(userCompanyUser) && !userCompanyUser.getCompanyUserId().equals(param.getCompanyUserId())){
            return ResponseResult.fail(500,"该用户("+fsUser.getUserId() + ")已成为其他销售会员");
        }

        // 特殊（需求设计：需要根据公司是否开启黑名单来设置会员初始化的状态）
        Company company = companyMapper.selectCompanyById(param.getCompanyId());
        // isDefaultBlack 值为1 ，表示需要加入小黑屋，否则不加
        int isDefaultBlack = company != null ? company.getFsUserIsDefaultBlack() : 0;

        // 添加关系表数据
        if (Objects.isNull(userCompanyUser)){
            int defaultStatus = isDefaultBlack == 1 ? 0 : 1;
            userCompanyUser = userCompanyUserService.bindRelationship(param.getUserId(), param.getProjectId(), companyUser.getCompanyId(), companyUser.getUserId(), defaultStatus);
        }

        // 不为空则添加新标签
        if (Objects.nonNull(param.getTagIds()) && param.getTagIds().length > 0) {
            userProjectTagService.addUserProjectTag(userCompanyUser.getId(), Arrays.stream(param.getTagIds()).map(Long::valueOf).collect(Collectors.toList()));
        }

//        // 如果是重粉，直接打上重粉的标签
//        if(1 == fsUserCompanyUser.getIsRepeatFans()){
//            this.setRepeatFansTag(param);
//        }

        //如果是设置了需要进入小黑屋，则需要返回提示，否则正常返回
        if(isDefaultBlack == 1){
            return ResponseResult.fail(402, "已成功注册，待管理审核");
        }
        return ResponseResult.ok(Boolean.TRUE);
    }

    @Transactional(rollbackFor = Exception.class)
    public void setRepeatFansTag(FsUserCourseBeMemberParam param) {
        Map<String, Object> map = new HashMap<>();
        map.put("tagName", "重粉");
        map.put("companyId", param.getCompanyId());
        List<CompanyTag> companyTags = companyTagMapper.selectCompanyTagListByMap(map);
        Long tagId;
        if(companyTags == null || companyTags.isEmpty()){
            CompanyTag companyTag = new CompanyTag();
            companyTag.setCompanyId(param.getCompanyId());
            companyTag.setTag("重粉");
            companyTagService.insertCompanyTag(companyTag);
            tagId = companyTag.getTagId();
        } else {
            tagId = companyTags.get(0).getTagId();
        }
        //  查询
        CompanyTagUser companyTagUserParam = new CompanyTagUser();
        companyTagUserParam.setUserId(param.getUserId());
        companyTagUserParam.setTagIds(tagId.toString());
        companyTagUserParam.setCompanyUserId(param.getCompanyUserId());
        List<CompanyTagUser> companyTagUsers = companyTagUserMapper.selectCompanyTagUserList(companyTagUserParam);
        if(companyTagUsers == null || companyTagUsers.isEmpty()){
            CompanyTagUser companyTagUser = new CompanyTagUser();
            companyTagUser.setUserId(param.getUserId());
            companyTagUser.setCompanyId(param.getCompanyId());
            companyTagUser.setCompanyUserId(param.getCompanyUserId());
            companyTagUser.setTagIds(tagId.toString());
            companyTagUser.setCreateTime(new Date());
            companyTagUserMapper.insertCompanyTagUser(companyTagUser);
        }
    }

    @Override
    public List<FsUserScrm> selectFsUserListByJointUserNameKey(String userNameKey) {
        return fsUserMapper.selectFsUserListByJointUserNameKey(userNameKey);
    }

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

    @Override
    public FsUserScrm selectFsUserByOpenId(String openid) {
        return fsUserMapper.selectFsUserByOpenId(openid);
    }

    @Override
    @Transactional
    public void addTuiLiveMoney(LiveOrder order, List<FsStoreProductAttrValueScrm> productAttrValues) {
        BigDecimal brokerage=BigDecimal.ZERO;
        //返佣金
        FsUserScrm user= fsUserMapper.selectFsUserById(order.getCompanyUserId());
        for (FsStoreProductAttrValueScrm productAttrValue : productAttrValues) {
            brokerage=brokerage.add(productAttrValue.getBrokerage().multiply(new BigDecimal(order.getTotalNum())));
        }
        if(brokerage.compareTo(BigDecimal.ZERO)==1){
            FsUserScrm tuiUserMap=new FsUserScrm();
            tuiUserMap.setUserId(user.getUserId());
            tuiUserMap.setBrokeragePrice(user.getBrokeragePrice().add(brokerage));
            fsUserMapper.updateFsUser(tuiUserMap);
            billService.addBill(tuiUserMap.getUserId(), CATEGORY_3.getValue(),1,BillDetailEnum.TYPE_5.getDesc(),brokerage,tuiUserMap.getBrokeragePrice(),"订单返佣金",order.getOrderId().toString(),order.getCompanyUserId());
        }
    }

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

    /**
     * 查询会员选项列表
     * @param params    参数
     * @return  list
     */
    @Override
    public List<OptionsVO> selectUserListByMap(Map<String, Object> params) {
        return fsUserMapper.selectUserListByMap(params);
    }
}
