package com.kxs.system.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.kxs.common.core.constant.SecurityConstants;
import com.kxs.common.core.exception.GlobalCustomerException;
import com.kxs.common.core.util.R;
import com.kxs.common.security.util.SecurityUtils;
import com.kxs.product.api.dto.kxsapp.GetActivityMachineByIdAndTimeDTO;
import com.kxs.product.api.feign.RemoteKxsProductService;
import com.kxs.stat.api.dto.statUser.GetActivityStatByIdAndTimeDTO;
import com.kxs.stat.api.feign.RemoteKxsStatService;
import com.kxs.stat.api.vo.GetActivityStatByIdAndTimeVO;
import com.kxs.system.api.dto.admin.GetByBcqtPageDTO;
import com.kxs.system.api.dto.kxsapp.camp.CampAddBcqtTeamDTO;
import com.kxs.system.api.dto.kxsapp.camp.CampOpenActivityDTO;
import com.kxs.system.api.dto.kxsapp.camp.CampReturnTeamDTO;
import com.kxs.system.api.model.KxsBcqtTeamDetail;
import com.kxs.system.api.vo.admin.GetByBcqtPageVO;
import com.kxs.system.api.vo.kxsapp.camp.CampGetBcqtDetailVO;
import com.kxs.system.api.vo.kxsapp.camp.CampGetBcqtListVO;
import com.kxs.system.api.vo.kxsapp.camp.CampGetMyBcqtListVO;
import com.kxs.system.api.vo.kxsapp.camp.TeamUserItem;
import com.kxs.system.biz.mapper.KxsBcqtTeamDetailMapper;
import com.kxs.system.biz.mapper.KxsBcqtTeamMapper;
import com.kxs.system.api.model.KxsBcqtTeam;
import com.kxs.system.biz.service.KxsBcqtTeamService;
import com.kxs.user.api.feign.RemoteKxsUserService;
import com.kxs.user.api.model.KxsUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.K;
import org.jacoco.agent.rt.internal_43f5073.core.internal.flow.IFrame;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Array;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 百城千团团队表(KxsBcqtTeam)表服务实现类
 *
 * @author 系统
 * @since 2024-05-22 14:29:03
 */
@Service("kxsBcqtTeamService")
@RequiredArgsConstructor
@Slf4j
public class KxsBcqtTeamServiceImpl extends ServiceImpl<KxsBcqtTeamMapper, KxsBcqtTeam> implements KxsBcqtTeamService {
    private final KxsBcqtTeamDetailMapper kxsBcqtTeamDetailMapper;
    private final RemoteKxsUserService remoteKxsUserService;
    private final RemoteKxsStatService remoteKxsStatService;
    private final KxsBcqtTeamMapper kxsBcqtTeamMapper;
    private final RemoteKxsProductService remoteKxsProductService;

    @Override
    public R getBcqtList(Page<KxsBcqtTeam> page, String keyword) {
        Page<CampGetBcqtListVO> kxsBcqtTeamPage = baseMapper.getBcqtList(page, keyword);
        Long userId = SecurityUtils.getUser().getId();
        KxsBcqtTeamDetail kxsBcqtTeamDetail = kxsBcqtTeamDetailMapper.selectOne(Wrappers.<KxsBcqtTeamDetail>query().lambda().eq(KxsBcqtTeamDetail::getUserId, userId).eq(KxsBcqtTeamDetail::getEndFlag, 0));
        if (kxsBcqtTeamDetail == null) {
            return R.ok(kxsBcqtTeamPage);
        }
        //当用户存在正在参加的活动  需要判断列表关系
        for (CampGetBcqtListVO record : kxsBcqtTeamPage.getRecords()) {
            if (Objects.equals(kxsBcqtTeamDetail.getTeamId(), Long.valueOf(record.getId()))) {
                record.setRelation(1);
            }
        }
        return R.ok(kxsBcqtTeamPage);
    }

    @Override
    public R getMyBcqtList(Page<KxsBcqtTeam> page) {
        Long userId = SecurityUtils.getUser().getId();
        return R.ok(kxsBcqtTeamDetailMapper.getMyBcqtList(page, userId));
    }

    @Override
    @Transactional
    public R addBcqtTeam(CampAddBcqtTeamDTO param) {
        log.info("开始创建团队" + param );
        String teamName = param.getTeamName();
        if (param.getTeamName().isEmpty()){
            throw new GlobalCustomerException("团队名不能为空");
        }
        if (param.getCaptainId() == null){
            throw new GlobalCustomerException("队长id不能为空");
        }
        Long captainId = param.getCaptainId();
        R r = verifyAddTeam(param);
        if (r.getStatus() == 0) {
            throw new GlobalCustomerException("校验未通过,非法参数");
        }
        R<KxsUser> kxsUserR = remoteKxsUserService.loadUserById(Math.toIntExact(captainId), SecurityConstants.FROM_IN);
        KxsUser kxsUser = kxsUserR.getData();
        //团队数据
        KxsBcqtTeam kxsBcqtTeam = new KxsBcqtTeam();
        kxsBcqtTeam.setCreateTime(LocalDateTime.now());
        kxsBcqtTeam.setDelFlag("0");
        kxsBcqtTeam.setTeamName(teamName);
        kxsBcqtTeam.setStatus(0);
        kxsBcqtTeam.setReachStatus(0);
        kxsBcqtTeam.setCaptainId(captainId);
        kxsBcqtTeam.setTeamNumber(1);
        kxsBcqtTeam.setUsername(kxsUser.getUsername());
        save(kxsBcqtTeam);
        //团队人员数据
        KxsBcqtTeamDetail kxsBcqtTeamDetail = new KxsBcqtTeamDetail();
        kxsBcqtTeamDetail.setCreateTime(LocalDateTime.now());
        kxsBcqtTeamDetail.setDelFlag("0");
        kxsBcqtTeamDetail.setUserId(captainId);
        kxsBcqtTeamDetail.setUsername(kxsUser.getUsername());
        kxsBcqtTeamDetail.setUserCode(kxsUser.getUserCode());
        kxsBcqtTeamDetail.setPosActivateNumber(0);
        kxsBcqtTeamDetail.setLkbActivateNumber(0);
        kxsBcqtTeamDetail.setGdActivateNumber(0);
        kxsBcqtTeamDetail.setCaptainStatus(1);
        kxsBcqtTeamDetail.setEndFlag(0);
        kxsBcqtTeamDetail.setTeamId(Long.valueOf(kxsBcqtTeam.getId()));
        kxsBcqtTeamDetailMapper.insert(kxsBcqtTeamDetail);
        log.info("团队创建完毕:" + kxsBcqtTeam + kxsBcqtTeamDetail);
        return R.ok();


    }

    @Override
    public R verifyAddTeam(CampAddBcqtTeamDTO param) {

        Long captainId = param.getCaptainId();
        //不存在未结束的团队
        KxsBcqtTeamDetail kxsBcqtTeamDetail = kxsBcqtTeamDetailMapper.selectOne(Wrappers.<KxsBcqtTeamDetail>query().lambda().eq(KxsBcqtTeamDetail::getUserId, captainId).eq(KxsBcqtTeamDetail::getEndFlag, 0));
        if (kxsBcqtTeamDetail != null) {
            return R.failed("您的参团还未结束");
        }
        //用户存在
        R<KxsUser> kxsUserR = remoteKxsUserService.loadUserById(Math.toIntExact(captainId), SecurityConstants.FROM_IN);
        if (kxsUserR.getData() == null){
            return R.failed("非法参数,用户不存在");
        }
        //用户状态正常且已实名
        if (!kxsUserR.getData().getStatus().equals(1) || !kxsUserR.getData().getRealStatus().equals(1)){
            return R.failed("用户状态异常或用户未实名");
        }
        //有效创客创客校验
        boolean b = remoteKxsUserService.validUserVerify(captainId, SecurityConstants.FROM_IN);
        if (!b){
            return R.failed("该用户非有效创客");

        }
        return R.ok();
    }

    @Override
    @Transactional
    public R returnTeam(CampReturnTeamDTO param) {
        Long id = param.getId();
        Long userId = SecurityUtils.getUser().getId();
        KxsBcqtTeam kxsBcqtTeam = getById(id);
        if (kxsBcqtTeam == null){
            return R.failed("该活动不存在");
        }
        if (kxsBcqtTeam.getCaptainId().equals(userId)){
            return R.failed("团长无法退出");
        }
        if (!kxsBcqtTeam.getStatus().equals(0)){
            return R.failed("非报名期间无法退出");
        }
        //退出
        //修改团队人数
        kxsBcqtTeam.setTeamNumber(kxsBcqtTeam.getTeamNumber()-1);
        updateById(kxsBcqtTeam);
        //删除明细
        kxsBcqtTeamDetailMapper.delete(Wrappers.<KxsBcqtTeamDetail>query().lambda().eq(KxsBcqtTeamDetail::getTeamId, kxsBcqtTeam.getId()).eq(KxsBcqtTeamDetail::getUserId, userId));
        return R.ok();
    }




    @Override
    public R openActivity(CampOpenActivityDTO param) {
        Long userId = SecurityUtils.getUser().getId();
        Integer id = param.getId();
     Integer activityDate = param.getActivityDate();
        KxsBcqtTeam kxsBcqtTeam = getById(id);
        if (kxsBcqtTeam == null){
            return R.failed("活动不存在");
        }
        if (!kxsBcqtTeam.getStatus().equals(0)){
            return R.failed("活动已开始");
        }
        if (!kxsBcqtTeam.getTeamNumber().equals(10)){
            return R.failed("人员不足无法开启活动");
        }
        if (!userId.equals(kxsBcqtTeam.getCaptainId())){
            return R.failed("您无法开启该活动,请联系团长开启活动");
        }
        LocalDateTime dateTime = LocalDateTime.now();
        LocalDate currentDate = dateTime.toLocalDate();
        // 计算次日凌晨0点
        LocalDateTime startTime = currentDate.plusDays(1).atStartOfDay();
        // 计算次日后+活动时长凌晨0点
        LocalDateTime endTime = currentDate.plusDays(activityDate + 1).atStartOfDay();
        kxsBcqtTeam.setUpdateTime(dateTime);
        kxsBcqtTeam.setStartTime(startTime);//开始时间
        kxsBcqtTeam.setEndTime(endTime);//结束时间
        kxsBcqtTeam.setStatus(1);//活动开启
        kxsBcqtTeam.setActivityDate(activityDate);//活动时长
        updateById(kxsBcqtTeam);
        return R.ok();
    }

    @Override
    public R getBcqtDetail(Integer id) {
        CampGetBcqtDetailVO campGetBcqtDetailVO = new CampGetBcqtDetailVO();
        KxsBcqtTeam kxsBcqtTeam = getById(id);
        if (kxsBcqtTeam ==null){
            return R.failed("该活动不存在");
        }
        Long userId = SecurityUtils.getUser().getId();
        KxsBcqtTeamDetail bcqtTeamDetail = kxsBcqtTeamDetailMapper.selectOne(Wrappers.<KxsBcqtTeamDetail>query().lambda().eq(KxsBcqtTeamDetail::getTeamId, id).eq(KxsBcqtTeamDetail::getUserId, userId));
        if (bcqtTeamDetail == null){
            return R.failed("非法参数,无法查看未加入的团队");
        }
        //复制活动信息
        BeanUtil.copyProperties(kxsBcqtTeam,campGetBcqtDetailVO);
        //总激活
        int activityTotal = 0;
        //查询并复制人员信息
        List<KxsBcqtTeamDetail> kxsBcqtTeamDetails = kxsBcqtTeamDetailMapper.selectList(Wrappers.<KxsBcqtTeamDetail>query().lambda().eq(KxsBcqtTeamDetail::getTeamId, id));
        ArrayList<TeamUserItem> teamUserItems = new ArrayList<>();
        for (KxsBcqtTeamDetail kxsBcqtTeamDetail : kxsBcqtTeamDetails) {
            TeamUserItem teamUserItem = new TeamUserItem();
            //个人激活数
            int personageActivity = 0;
            BeanUtil.copyProperties(kxsBcqtTeamDetail,teamUserItem);
            if (kxsBcqtTeamDetail.getGdActivateNumber() != null){
                activityTotal += kxsBcqtTeamDetail.getGdActivateNumber();
                personageActivity += kxsBcqtTeamDetail.getGdActivateNumber();
            }
            if (kxsBcqtTeamDetail.getLkbActivateNumber() != null){
                activityTotal += kxsBcqtTeamDetail.getLkbActivateNumber();
                personageActivity += kxsBcqtTeamDetail.getLkbActivateNumber();

            }
            if (kxsBcqtTeamDetail.getPosActivateNumber() != null){
                activityTotal += kxsBcqtTeamDetail.getPosActivateNumber();
                personageActivity += kxsBcqtTeamDetail.getPosActivateNumber();
            }
            //个人总激活数返回字段归于posActivateNumber
            teamUserItem.setPosActivateNumber(personageActivity);
            teamUserItems.add(teamUserItem);
        }
        //计算奖池
        BigDecimal totalAmount = BigDecimal.ZERO;
        if (activityTotal > 100 && 200 > activityTotal){
            totalAmount = new BigDecimal(1000);
        } else if (200 < activityTotal) {
            totalAmount = new BigDecimal(2200);
        }
        //赋值
        campGetBcqtDetailVO.setTotalAmount(totalAmount);
        campGetBcqtDetailVO.setActiviteTotal(activityTotal);
        campGetBcqtDetailVO.setTeamUser(teamUserItems);
        return R.ok(campGetBcqtDetailVO);
    }




    @Override
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void setUserActivityTimeStat() {
        //获取全部活动中团队
        List<KxsBcqtTeam> list = list(Wrappers.<KxsBcqtTeam>query().lambda().eq(KxsBcqtTeam::getStatus, 1));
        //处理查询数据
        for (KxsBcqtTeam kxsBcqtTeam : list) {
            //构造该团队的查询日期
            LocalDateTime startTime = kxsBcqtTeam.getStartTime();//开始时间
            Integer activityDate = kxsBcqtTeam.getActivityDate();//活动时长
            //获取从开始时间开始未来活动时长的每天字符串
            List<String> futureDates = new ArrayList<>();
            for (int i = 0; i <= activityDate; i++) {
                LocalDate currentDate = startTime.toLocalDate().plusDays(i);
                String currentDateString = LocalDateTimeUtil.format(currentDate, DatePattern.PURE_DATE_PATTERN);
                futureDates.add(currentDateString);
            }
            //查询团队所有成员
            List<KxsBcqtTeamDetail> kxsBcqtTeamDetailS = kxsBcqtTeamDetailMapper.selectList(Wrappers.<KxsBcqtTeamDetail>query().lambda()
                    .eq(KxsBcqtTeamDetail::getTeamId,kxsBcqtTeam.getId()).eq(KxsBcqtTeamDetail::getEndFlag, 0));
            //构造查询dto
            List<GetActivityStatByIdAndTimeVO> activityStatByIdAndTimes = new ArrayList<>();
            for (KxsBcqtTeamDetail kxsBcqtTeamDetail : kxsBcqtTeamDetailS) {
                ArrayList<GetActivityStatByIdAndTimeDTO> getActivityStatByIdAndTimeDTOS = new ArrayList<>();
                GetActivityStatByIdAndTimeDTO getActivityStatByIdAndTimeDTO = new GetActivityStatByIdAndTimeDTO();
                getActivityStatByIdAndTimeDTO.setUserId(kxsBcqtTeamDetail.getUserId());
                getActivityStatByIdAndTimeDTO.setTimes(futureDates);
                getActivityStatByIdAndTimeDTOS.add(getActivityStatByIdAndTimeDTO);
                //查询得到统计数据
                List<GetActivityStatByIdAndTimeVO> activityStatByIdAndTime = remoteKxsStatService.getActivityStatByIdAndTime(getActivityStatByIdAndTimeDTOS, SecurityConstants.FROM_IN);
                Integer lkbNumber = 0;
                for (GetActivityStatByIdAndTimeVO getActivityStatByIdAndTimeVO : activityStatByIdAndTime) {
                    lkbNumber = getActivityStatByIdAndTimeVO.getLkbActivityNumber();
                }
                //查询pos和广电数据
                //查询dto
                GetActivityMachineByIdAndTimeDTO getActivityMachineByIdAndTimeDTO = new GetActivityMachineByIdAndTimeDTO();
                getActivityMachineByIdAndTimeDTO.setStartTime(kxsBcqtTeam.getStartTime());
                getActivityMachineByIdAndTimeDTO.setEndTime(kxsBcqtTeam.getEndTime());
                getActivityMachineByIdAndTimeDTO.setUserId(kxsBcqtTeamDetail.getUserId());
                GetActivityStatByIdAndTimeVO activityMachineByIdAndTime =  remoteKxsProductService.getActivityMachineByIdAndTime(getActivityMachineByIdAndTimeDTO,SecurityConstants.FROM_IN);
                activityMachineByIdAndTime.setLkbActivityNumber(lkbNumber);
                activityMachineByIdAndTime.setUserId(kxsBcqtTeamDetail.getUserId());
                activityStatByIdAndTimes.add(activityMachineByIdAndTime);
            }
            int reachNumber = 0;
            //修改查询到的数据的当前激活数
            for (GetActivityStatByIdAndTimeVO getActivityStatByIdAndTimeVO : activityStatByIdAndTimes) {
                Long userId = getActivityStatByIdAndTimeVO.getUserId();
                Integer posActivityNumber = getActivityStatByIdAndTimeVO.getPosActivityNumber();
                if (posActivityNumber != null){
                    reachNumber += posActivityNumber;
                }
                Integer gdActivityNumber = getActivityStatByIdAndTimeVO.getGdActivityNumber();
                if (gdActivityNumber != null){
                    reachNumber += gdActivityNumber;
                }
                Integer lkbActivityNumber = getActivityStatByIdAndTimeVO.getLkbActivityNumber();
                if (lkbActivityNumber != null){
                    reachNumber += lkbActivityNumber;
                }
                //查询当前在活动的该用户
                KxsBcqtTeamDetail kxsBcqtTeamDetail = kxsBcqtTeamDetailMapper.selectOne(Wrappers.<KxsBcqtTeamDetail>query().lambda().eq(KxsBcqtTeamDetail::getUserId, userId).eq(KxsBcqtTeamDetail::getEndFlag, 0));
                kxsBcqtTeamDetail.setUpdateTime(LocalDateTime.now());
                kxsBcqtTeamDetail.setPosActivateNumber(posActivityNumber == null ? 0 :posActivityNumber);
                kxsBcqtTeamDetail.setLkbActivateNumber(lkbActivityNumber == null ? 0 :lkbActivityNumber);
                kxsBcqtTeamDetail.setGdActivateNumber(gdActivityNumber == null ? 0 :gdActivityNumber);
                //修改激活数
                kxsBcqtTeamDetailMapper.updateById(kxsBcqtTeamDetail);
            }
            //判断当前团队是否达标
            if (reachNumber >= 100 && kxsBcqtTeam.getReachStatus() != 1){
                kxsBcqtTeam.setReachStatus(1);
                updateById(kxsBcqtTeam);
            }
        }
    }

    @Override
    @Transactional
    public void setUserActiviteStatus() {
        //获取全部活动中团队
        List<KxsBcqtTeam> list = list(Wrappers.<KxsBcqtTeam>query().lambda().eq(KxsBcqtTeam::getStatus, 1));
        LocalDateTime now = LocalDateTime.now();
        for (KxsBcqtTeam kxsBcqtTeam : list) {
            LocalDateTime endTime = kxsBcqtTeam.getEndTime();
            //当前时间在结束时间之后
            if (now.isAfter(endTime)){
                //设置活动状态为已结束
                kxsBcqtTeam.setStatus(2);
                updateById(kxsBcqtTeam);
                //修改团队人员明细
                List<KxsBcqtTeamDetail> kxsBcqtTeamDetailS = kxsBcqtTeamDetailMapper.selectList(Wrappers.<KxsBcqtTeamDetail>query().lambda()
                        .eq(KxsBcqtTeamDetail::getTeamId,kxsBcqtTeam.getId()));
                for (KxsBcqtTeamDetail kxsBcqtTeamDetail : kxsBcqtTeamDetailS) {
                    //结束参与状态
                    kxsBcqtTeamDetail.setEndFlag(1);
                    kxsBcqtTeamDetailMapper.updateById(kxsBcqtTeamDetail);
                }
            }
        }
    }

    @Override
    public R getByBcqtPage(Page<KxsBcqtTeam> page, GetByBcqtPageDTO param) {
        ArrayList<Long> teamIds = new ArrayList<>();
        //当传入的用户编码不为null时先行查询用户
        if (param.getUserCode() != null && !param.getUserCode().equals("")){
            List<KxsBcqtTeamDetail> kxsBcqtTeamDetails = kxsBcqtTeamDetailMapper.selectList(Wrappers.<KxsBcqtTeamDetail>query().lambda().eq(KxsBcqtTeamDetail::getUserCode, param.getUserCode()));
            //当用户未查询到时直接返回空
            if (kxsBcqtTeamDetails.size() == 0){
                return R.ok();
            }
            for (KxsBcqtTeamDetail kxsBcqtTeamDetail : kxsBcqtTeamDetails) {
                teamIds.add(kxsBcqtTeamDetail.getTeamId());
            }
        }
        //查询团队列表
        Page<KxsBcqtTeam> kxsBcqtTeamPage = page(page, Wrappers.<KxsBcqtTeam>query().lambda()
                .eq(param.getStatus() != null, KxsBcqtTeam::getStatus, param.getStatus())
                .eq(param.getReachStatus() != null, KxsBcqtTeam::getReachStatus, param.getReachStatus())
                .like(param.getTeamName() != null && !param.getTeamName().equals(""),KxsBcqtTeam::getTeamName,param.getTeamName())
                .in(teamIds.size() != 0, KxsBcqtTeam::getId, teamIds)
                .orderByDesc(KxsBcqtTeam::getCreateTime));
        //构造返回列表VO集合
        ArrayList<GetByBcqtPageVO> getByBcqtPageVOS = new ArrayList<>();
        for (KxsBcqtTeam record : kxsBcqtTeamPage.getRecords()) {
            //构造返回实体
            GetByBcqtPageVO getByBcqtPageVO = new GetByBcqtPageVO();
            BeanUtil.copyProperties(record,getByBcqtPageVO);
            //查询团体详情数据 构造总激活数
            List<KxsBcqtTeamDetail> kxsBcqtTeamDetails = kxsBcqtTeamDetailMapper.selectList(Wrappers.<KxsBcqtTeamDetail>query().lambda().eq(KxsBcqtTeamDetail::getTeamId, record.getId()));
            //总激活数
            int activityTotal = 0;
            for (KxsBcqtTeamDetail kxsBcqtTeamDetail : kxsBcqtTeamDetails) {
                if (kxsBcqtTeamDetail.getGdActivateNumber() != null){
                    activityTotal += kxsBcqtTeamDetail.getGdActivateNumber();
                }
                if (kxsBcqtTeamDetail.getLkbActivateNumber() != null){
                    activityTotal += kxsBcqtTeamDetail.getLkbActivateNumber();

                }
                if (kxsBcqtTeamDetail.getPosActivateNumber() != null){
                    activityTotal += kxsBcqtTeamDetail.getPosActivateNumber();
                }
                if (kxsBcqtTeamDetail.getCaptainStatus() == 1){
                    //队长编号
                    getByBcqtPageVO.setUserCode(kxsBcqtTeamDetail.getUserCode());
                }
            }
            //总激活
            getByBcqtPageVO.setActivityTotal(activityTotal);
            getByBcqtPageVOS.add(getByBcqtPageVO);
        }
        //构造返回page
        Page<GetByBcqtPageVO> kxsBcqtTeamDetailPage = new Page<>();
        kxsBcqtTeamDetailPage.setTotal(kxsBcqtTeamPage.getTotal());
        kxsBcqtTeamDetailPage.setRecords(getByBcqtPageVOS);
        return R.ok(kxsBcqtTeamDetailPage);
    }

    @Override
    public void updateBcqt(KxsBcqtTeam kxsBcqtTeam) {
        KxsBcqtTeam kxsBcqtTeam1 = kxsBcqtTeamMapper.selectById(kxsBcqtTeam.getId());
        if (kxsBcqtTeam1 == null){
            throw new GlobalCustomerException("团队不存在");
        }
        kxsBcqtTeam1.setTeamName(kxsBcqtTeam.getTeamName());
        kxsBcqtTeamMapper.updateById(kxsBcqtTeam1);
    }

    @Override
    public R bcqtGetDetail(Long id) {
        KxsBcqtTeam kxsBcqtTeam = kxsBcqtTeamMapper.selectById(id);
        if (kxsBcqtTeam == null){
            return R.failed("团队不存在");
        }
        List<KxsBcqtTeamDetail> kxsBcqtTeamDetails = kxsBcqtTeamDetailMapper.selectList(Wrappers.<KxsBcqtTeamDetail>query().lambda().eq(KxsBcqtTeamDetail::getTeamId, kxsBcqtTeam.getId()));
        return R.ok(kxsBcqtTeamDetails);
    }

    @Override
    @Transactional
    public R joinTheTeam(long id) {
        Long userId = SecurityUtils.getUser().getId();
        KxsBcqtTeamDetail bcqtTeamDetail = kxsBcqtTeamDetailMapper.selectOne(Wrappers.<KxsBcqtTeamDetail>query().lambda().eq(KxsBcqtTeamDetail::getUserId, userId).eq(KxsBcqtTeamDetail::getEndFlag, 0));
        if (bcqtTeamDetail != null){
            return R.failed("每个用户同一时间只能加入一个团队");
        }
        KxsBcqtTeam kxsBcqtTeam = kxsBcqtTeamMapper.selectById(id);
        if (kxsBcqtTeam == null){
            return R.failed("非法参数,团队不存在");
        }
        if (kxsBcqtTeam.getStatus() != 0){
            return R.failed("只能加入未开始的团队");
        }
        R<KxsUser> kxsUserR = remoteKxsUserService.loadUserById(Math.toIntExact(userId),SecurityConstants.FROM_IN);
        KxsUser kxsUser = kxsUserR.getData();
        if (kxsUser == null){
            return R.failed("系统错误,请重新登录");
        }
        if (kxsUser.getRealStatus() != 1 || kxsUser.getStatus() != 1){
            return R.failed("用户状态异常或未实名");
        }
        Long captainId = kxsBcqtTeam.getCaptainId();
        String pidPath = kxsUser.getPidPath();
        String pid = "," + captainId + ",";
        if (!pidPath.contains(pid)){
            return R.failed("您无法加入您体系外的团队");
        }
        Integer teamNumber = kxsBcqtTeam.getTeamNumber();
        if (teamNumber >= 10){
            return R.failed("该团队人数已满");
        }
        //加入
        kxsBcqtTeam.setTeamNumber(teamNumber + 1);
        kxsBcqtTeamMapper.updateById(kxsBcqtTeam);
        KxsBcqtTeamDetail kxsBcqtTeamDetail = new KxsBcqtTeamDetail();
        kxsBcqtTeamDetail.setCreateTime(LocalDateTime.now());
        kxsBcqtTeamDetail.setDelFlag("0");
        kxsBcqtTeamDetail.setUserId(Long.valueOf(kxsUser.getId()));
        kxsBcqtTeamDetail.setUsername(kxsUser.getUsername());
        kxsBcqtTeamDetail.setUserCode(kxsUser.getUserCode());
        kxsBcqtTeamDetail.setPosActivateNumber(0);
        kxsBcqtTeamDetail.setLkbActivateNumber(0);
        kxsBcqtTeamDetail.setGdActivateNumber(0);
        kxsBcqtTeamDetail.setCaptainStatus(0);
        kxsBcqtTeamDetail.setEndFlag(0);
        kxsBcqtTeamDetail.setTeamId(id);
        kxsBcqtTeamDetailMapper.insert(kxsBcqtTeamDetail);

        return R.ok();
    }
























}

