package org.springblade.modules.martial.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.martial.pojo.dto.TeamSubmitDTO;
import org.springblade.modules.martial.pojo.entity.MartialTeam;
import org.springblade.modules.martial.pojo.vo.MartialTeamVO;
import org.springblade.modules.martial.service.IMartialTeamService;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/martial/team")
@Tag(name = "集体管理", description = "集体/团队接口")
public class MartialTeamController extends BladeController {

	private final IMartialTeamService teamService;

	@GetMapping("/list")
	@Operation(summary = "分页列表", description = "获取当前用户的集体列表")
	public R<IPage<MartialTeamVO>> list(Query query) {
		Long userId = AuthUtil.getUserId();
		IPage<MartialTeamVO> pages = teamService.getTeamList(userId, query.getCurrent(), query.getSize());
		return R.data(pages);
	}

	@GetMapping("/detail")
	@Operation(summary = "详情", description = "获取集体详情")
	public R<MartialTeamVO> detail(@RequestParam Long id) {
		return R.data(teamService.getTeamDetail(id));
	}

	@PostMapping("/submit")
	@Operation(summary = "保存", description = "新增或修改集体")
	public R<Boolean> submit(@RequestBody TeamSubmitDTO dto) {
		log.info("Team submit - teamId: {}, teamName: {}, memberIds: {}", dto.getTeamId(), dto.getTeamName(), dto.getMemberIds());
		
		MartialTeam team = new MartialTeam();
		team.setTeamName(dto.getTeamName());
		team.setRemark(dto.getRemark());
		
		boolean result;
		if (StringUtil.isNotBlank(dto.getTeamId())) {
			Long teamId = Long.parseLong(dto.getTeamId());
			team.setId(teamId);
			log.info("Updating team with id: {}", teamId);
			result = teamService.updateTeamWithMembers(team, dto.getMemberIds());
		} else {
			log.info("Creating new team");
			result = teamService.saveTeamWithMembers(team, dto.getMemberIds());
		}
		return R.data(result);
	}

	@PostMapping("/remove")
	@Operation(summary = "删除", description = "删除集体")
	public R<Boolean> remove(@RequestParam Long id) {
		return R.data(teamService.removeTeamWithMembers(id));
	}

}
