package com.red.circle.console.adapter.app.team;

import com.red.circle.console.app.dto.clienobject.team.TeamPolicyManagerCO;
import com.red.circle.console.app.service.app.team.TeamPolicyManagerBackService;
import com.red.circle.framework.web.controller.BaseController;
import com.red.circle.other.inner.endpoint.team.target.TeamBillCycleClient;
import com.red.circle.other.inner.model.cmd.team.TeamBillCycleBackQryCmd;
import com.red.circle.other.inner.model.cmd.team.TeamPolicyManagerBackQryCmd;
import com.red.circle.other.inner.model.cmd.team.TeamPolicyManagerCmd;
import com.red.circle.tool.core.date.TimestampUtils;
import java.util.List;
import java.util.Objects;

import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 团队策略.
 *
 * @author pengshigang on 2022/12/12
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/team/policy/manager")
public class TeamPolicyManagerRestController extends BaseController {

  private final TeamPolicyManagerBackService teamPolicyManagerBackService;
  private final TeamBillCycleClient teamBillCycleClient;

  /**
   * 获得当前对外发布策略.
   */
  @GetMapping("/releases")
  public TeamPolicyManagerCO releases(TeamPolicyManagerBackQryCmd query) {
    return teamPolicyManagerBackService.getByRegionByType(query);
  }

  /**
   * 策略历史列表.
   */
  @GetMapping("/history/releases")
  public List<TeamPolicyManagerCO> historyReleases(TeamPolicyManagerBackQryCmd query) {
    return teamPolicyManagerBackService. historyReleases(query);
  }

  /**
   * 添加策略.
   */
  @PostMapping("/add")
  public void add(@RequestBody @Validated TeamPolicyManagerCmd param) {
    param.setCreateUser(param.getReqUserId());
    param.setCreateTime(TimestampUtils.now());
    teamPolicyManagerBackService.add(param);

    // 发布完政策如果有团队是其他政策需要替换最新的政策，可能出现的情况：钻石->美元;美元->钻石;美元->美元;钻石->钻石
    if (Objects.equals(param.getRelease(), Boolean.TRUE)) {
      // 如果政策是发布的状态，查询该区域所有的团队并改变团队政策。
      teamBillCycleClient.listBillTable(new TeamBillCycleBackQryCmd().setRegion(param.getRegion()));
    }
  }

  /**
   * 根据id删除策略.
   */
  @GetMapping("/delete/{id}")
  public void deleteById(@PathVariable("id") Long id) {
    teamPolicyManagerBackService.deleteById(id);
  }

  /**
   * 获得当前对外发布策略.
   */
  @GetMapping("/sys-region")
  public List<TeamPolicyManagerCO> listTeamPolicy(@RequestParam String sysOrigin,
      @RequestParam String region) {
    return teamPolicyManagerBackService.listTeamPolicy(sysOrigin, region);
  }

}
