package com.ruoyi.bst.team.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.github.pagehelper.PageHelper;
import com.ruoyi.bst.account.domain.AccountQuery;
import com.ruoyi.bst.account.domain.AccountVO;
import com.ruoyi.bst.booth.domain.BoothVO;
import com.ruoyi.bst.booth.service.BoothService;
import com.ruoyi.bst.team.domain.enums.TeamStatus;
import com.ruoyi.bst.teamUser.domain.TeamUser;
import com.ruoyi.bst.teamUser.domain.TeamUserQuery;
import com.ruoyi.bst.teamUser.domain.TeamUserVO;
import com.ruoyi.bst.teamUser.domain.enums.JoinType;
import com.ruoyi.bst.teamUser.domain.enums.RoleType;
import com.ruoyi.bst.teamUser.domain.enums.UserStatus;
import com.ruoyi.bst.teamUser.mapper.TeamUserMapper;
import com.ruoyi.bst.teamUser.service.TeamUserService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.system.notice.domain.Notice;
import com.ruoyi.system.notice.domain.NoticeQuery;
import com.ruoyi.system.notice.domain.NoticeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.bst.team.mapper.TeamMapper;
import com.ruoyi.bst.team.domain.Team;
import com.ruoyi.bst.team.domain.TeamVO;
import com.ruoyi.bst.team.domain.TeamQuery;
import com.ruoyi.bst.team.service.TeamService;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 拼桌Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-22
 */
@Service
public class TeamServiceImpl implements TeamService {
    @Autowired
    private TeamMapper teamMapper;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private TeamUserService teamUserService;
    @Autowired
    private TeamUserMapper teamUserMapper;
    @Autowired
    private TeamService teamService;
    @Autowired
    private BoothService boothService;

    /**
     * 查询拼桌
     *
     * @param id 拼桌主键
     * @return 拼桌
     */
    @Override
    public TeamVO selectTeamById(Long id) {
        return teamMapper.selectTeamById(id);
    }

    /**
     * 查询拼桌列表
     *
     * @param team 拼桌
     * @return 拼桌
     */
    @Override
    public List<TeamVO> selectTeamList(TeamQuery team) {
        return teamMapper.selectTeamList(team);
    }

    /**
     * 新增拼桌
     *
     * @param team 拼桌
     * @return 结果
     */
    @Override
    public int insertTeam(Team team) {
        team.setCreateTime(DateUtils.getNowDate());
        return teamMapper.insertTeam(team);
    }

    /**
     * 修改拼桌
     *
     * @param team 拼桌
     * @return 结果
     */
    @Override
    public int updateTeam(Team team) {
        return teamMapper.updateTeam(team);
    }

    /**
     * 批量删除拼桌
     *
     * @param ids 需要删除的拼桌主键
     * @return 结果
     */
    @Override
    public int deleteTeamByIds(Long[] ids) {
        return teamMapper.deleteTeamByIds(ids);
    }

    /**
     * 删除拼桌信息
     *
     * @param id 拼桌主键
     * @return 结果
     */
    @Override
    public int deleteTeamById(Long id) {
        return teamMapper.deleteTeamById(id);
    }

    @Override
    public int joinTeam(Long teamId, Long userId) {
        TeamUser teamUser = new TeamUser();
        return this.insertTeamUser(teamId, teamUser,userId, RoleType.MEMBERS.getCode(), JoinType.ACTIVE.getCode(),UserStatus.JOINED.getCode());
    }

    @Override
    public int invitedTeam(Long teamId, Long userId, Long inviterId) {
        TeamUser teamUser = new TeamUser();
        teamUser.setInviterId(inviterId);
        return this.insertTeamUser(teamId, teamUser, userId, RoleType.MEMBERS.getCode(), JoinType.INVITED.getCode(),UserStatus.JOINED.getCode());
    }

    @Override
    public int exitTeam(Long teamId, Long userId) {
        TeamUserQuery query = new TeamUserQuery();
        query.setTeamId(teamId);
        query.setUserId(userId);
        query.setStatus(UserStatus.JOINED.getCode());
        TeamUserVO vo = teamUserService.selectOne(query);
        ServiceUtil.assertion(vo == null,"您不属于该拼桌的成员");
        ServiceUtil.assertion(vo.getRole().equals(RoleType.CREATOR.getCode()),"发起者如果要退出请选择解散拼桌");
        vo.setStatus(UserStatus.EXITED.getCode());
        return teamUserService.updateTeamUser(vo);
    }

    @Override
    public int disTeam(Long teamId) {
        TeamVO team = teamService.selectTeamById(teamId);
        ServiceUtil.assertion(team == null,"id为%s的拼桌信息不存在", teamId);
        Integer result = transactionTemplate.execute(status -> {
            team.setStatus(TeamStatus.DIS.getCode());
            int i = teamService.updateTeam(team);
            ServiceUtil.assertion(i<= 0,"拼桌信息更新失败");
            List<TeamUserVO> list = teamUserService.selectTeamUserListByTeamId(teamId);
            for (TeamUserVO vo : list) {
                vo.setStatus(UserStatus.EXITED.getCode());
            }
            i =  teamUserMapper.batchUpdate(list);
            ServiceUtil.assertion(i<=0,"解散拼桌失败");
            return i;
        });
        return result;
    }

    @Override
    public TeamVO selectOne(TeamQuery query) {
            PageHelper.startPage(1, 1);
            List<TeamVO> list = this.selectTeamList(query);
            return CollectionUtils.firstElement(list);
    }

    @Override
    public List<TeamUserVO> getTeammate(Long teamId) {
        TeamQuery query = new TeamQuery();
        query.setId(teamId);
        query.setStatus(TeamStatus.NORMAL.getCode());
        TeamVO vo = teamService.selectOne(query);
        ServiceUtil.assertion(vo== null,"id为%s的拼桌不存在或已解散", teamId);
        List<TeamUserVO> list = teamUserService.selectTeamUserListByTeamId(teamId);
        ArrayList<TeamUserVO> userList = new ArrayList<>();
        for (TeamUserVO teamUserVO : list) {
            if(teamUserVO.getStatus().equals(UserStatus.JOINED.getCode())){
                userList.add(teamUserVO);
            }
        }
        return userList;
    }

    @Override
    public int createTeam(Team team, Long userId) {
        BoothVO booth = boothService.selectBoothByBoothId(team.getBoothId());
        ServiceUtil.assertion(booth == null,"id为%s的卡座不存在",team.getBoothId());
        ServiceUtil.assertion(!booth.getStoreId().equals(team.getStoreId()),"id为%s的卡座不属于id为%s的店铺,发起拼桌失败",booth.getBoothId(),team.getStoreId());
        Integer result = transactionTemplate.execute(status -> {
            int rows = teamMapper.insertTeam(team);
            ServiceUtil.assertion(rows <= 0, "发起拼桌失败");
            TeamUser teamUser = new TeamUser();
            rows = insertTeamUser(team.getId(),teamUser,userId, RoleType.CREATOR.getCode(), JoinType.CREATE.getCode(),UserStatus.JOINED.getCode());
            ServiceUtil.assertion(rows <= 0, "发起拼桌失败");
            return rows;
        });
        return result;
    }

    public int insertTeamUser(Long teamId,TeamUser teamUser , Long userId, String role, String JoinType, String userStatus) {
        TeamVO vo = teamService.selectTeamById(teamId);
        ServiceUtil.assertion(vo==null,"id为%s的拼桌信息不存在",teamId);
        teamUser.setTeamId(teamId);
        teamUser.setUserId(userId);
        teamUser.setRole(role);
        teamUser.setJoinType(JoinType);
        teamUser.setStatus(userStatus);
        int i = teamUserService.insertTeamUser(teamUser);
        ServiceUtil.assertion(i <= 0, "发起拼桌失败");
        return i;
    }


}
