package com.hzs.member.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.domain.member.base.CuMemberTeam;
import com.hzs.common.domain.member.ext.CuMemberTeamExt;
import com.hzs.member.base.mapper.CuMemberTeamMapper;
import com.hzs.member.base.service.ICuMemberTeamService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 隶属团队列表 服务实现类
 */
@Service
public class CuMemberTeamServiceImpl extends ServiceImpl<CuMemberTeamMapper, CuMemberTeam> implements ICuMemberTeamService {

    @Override
    public CuMemberTeamExt getCuMemberTeamById(Long pkMember) {
        CuMemberTeamExt cuMemberTeamExtParam = new CuMemberTeamExt();
        cuMemberTeamExtParam.setPkMember(pkMember);
        List<CuMemberTeamExt> cmtExtList = baseMapper.queryCuMemberTeam(cuMemberTeamExtParam);
        if (null != cmtExtList && cmtExtList.size() > 0) {
            return cmtExtList.get(0);
        }
        return null;
    }

    @Override
    public List<CuMemberTeamExt> queryCuMemberTeam(CuMemberTeamExt cuMemberTeamExt) {
        return baseMapper.queryCuMemberTeam(cuMemberTeamExt);
    }

    @Override
    public List<CuMemberTeamExt> queryCuMemberTeam(Integer pkCountry) {
        CuMemberTeamExt cuMemberTeamExt = new CuMemberTeamExt();
        cuMemberTeamExt.setPkCountry(pkCountry);
        return baseMapper.queryCuMemberTeam(cuMemberTeamExt);
    }

    @Override
    public Boolean checkVertex(Integer pkVertex) {
        LambdaQueryWrapper<CuMemberTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberTeam::getPkBdVertex, pkVertex);
        return this.count(queryWrapper) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCuMemberTeamByVertex(Long pkTeamCode) {
        // 查询体系下的所有团队，团队的编号代表没有团队
        CuMemberTeam cuMemberTeam = baseMapper.selectById(pkTeamCode);
        if (null != cuMemberTeam) {
            baseMapper.updateTeamNullById(pkTeamCode);
            baseMapper.updateTeamById(cuMemberTeam.getPkMember(), pkTeamCode, cuMemberTeam.getPkBdVertex());
        }
    }

    @Override
    public void flushAllTeam(Integer pkCountry) {
        List<CuMemberTeam> list = this.list(Wrappers.<CuMemberTeam>lambdaQuery()
                .eq(CuMemberTeam::getPkCountry, pkCountry)
        );
        for (CuMemberTeam memberTeam : list) {
            baseMapper.updateTeamNew(memberTeam.getPkMember(), memberTeam.getPkId(), memberTeam.getPkBdVertex(), pkCountry);
        }
    }

}
