package com.red.circle.other.infra.database.mongo.service.team.team.impl;

import com.google.common.collect.Maps;
import com.red.circle.other.infra.database.mongo.dto.team.TeamPolicy;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamPolicyManager;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamPolicyManagerService;
import com.red.circle.other.inner.enums.team.TeamPolicyTypeEnum;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.text.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 团队策略.
 *
 * @author pengshigang on 2022/12/12
 */
@Service
@RequiredArgsConstructor
public class TeamPolicyManagerServiceImpl implements TeamPolicyManagerService {

  private final MongoTemplate mongoTemplate;

  @Override
  public List<TeamPolicyManager> listSysOriginRegion(String sysOrigin, String region) {
    return mongoTemplate
        .find(Query.query(Criteria.where("region").is(region)
                .and("sysOrigin").is(sysOrigin)).with(Sort.by(Sort.Order.desc("createTime"))),
            TeamPolicyManager.class);
  }

  @Override
  public List<TeamPolicyManager> listTeamPolicy(String sysOrigin, String region) {
    return mongoTemplate
        .find(Query.query(Criteria.where("region").is(region)
                    .and("sysOrigin").is(sysOrigin))
                .with(Sort.by(Sort.Order.desc("createTime"))),
            TeamPolicyManager.class);
  }

  @Override
  public List<TeamPolicyManager> listTeamPolicyAndTypePolicy(String sysOrigin, String region, String policyType) {
    Criteria criteria = new Criteria();
    criteria.and("region").is(region);
    criteria.and("sysOrigin").is(sysOrigin);
    if (StringUtils.isNotBlank(policyType) && Objects.equals(policyType, TeamPolicyTypeEnum.SALARY_DIAMOND.name())) {
      criteria.and("policyType").is(policyType);
    }else {
      criteria.and("policyType").ne(TeamPolicyTypeEnum.SALARY_DIAMOND.name());
    }

    return mongoTemplate.find( Query.query(criteria).with(Sort.by(Sort.Order.desc("createTime"))), TeamPolicyManager.class);
  }

  @Override
  public List<TeamPolicyManager> listReleaseTeamPolicy(String sysOrigin, String region) {
    return mongoTemplate
        .find(Query.query(Criteria.where("region").is(region)
                    .and("release").is(Boolean.TRUE)
                    .and("sysOrigin").is(sysOrigin))
                .with(Sort.by(Sort.Order.desc("createTime"))),
            TeamPolicyManager.class);
  }


  @Override
  public TeamPolicyManager getReleaseByRegionAndType(String sysOrigin, String region) {
    return mongoTemplate.findOne(Query.query(
        Criteria.where("region").is(region)
            .and("release").is(Boolean.TRUE)
            .and("sysOrigin").is(sysOrigin)
    ), TeamPolicyManager.class);
  }

  @Override
  public TeamPolicyManager getReleaseByRegionAndType(String sysOrigin, String region, String policyType) {

    Criteria criteria = new Criteria();
    criteria.and("region").is(region);
    criteria.and("release").is(Boolean.TRUE);
    criteria.and("sysOrigin").is(sysOrigin);
    if (StringUtils.isNotBlank(policyType) && Objects.equals(policyType, TeamPolicyTypeEnum.SALARY_DIAMOND.name())) {
      criteria.and("policyType").is(policyType);
    }else {
      criteria.and("policyType").ne(TeamPolicyTypeEnum.SALARY_DIAMOND.name());
    }

    return mongoTemplate.findOne(Query.query(criteria), TeamPolicyManager.class);
  }

  @Override
  public Map<String, TeamPolicyManager> mapRegionRelease(Set<String> regions) {

    if (CollectionUtils.isEmpty(regions)) {
      return Maps.newHashMap();
    }

    List<TeamPolicyManager> teamPolicyManagers = mongoTemplate.find(
        Query.query(Criteria.where("region").in(regions).and("release").is(Boolean.TRUE)),
        TeamPolicyManager.class);

    if (CollectionUtils.isEmpty(teamPolicyManagers)) {
      return Maps.newHashMap();
    }

    return teamPolicyManagers.stream()
        .collect(Collectors.toMap(TeamPolicyManager::getRegion, v -> v));
  }

  @Override
  public TeamPolicyManager getById(Long id) {
    return mongoTemplate.findOne(Query.query(Criteria.where("id").is(id)), TeamPolicyManager.class);
  }

  @Override
  public void add(TeamPolicyManager policyManager) {

    policyManager.setHistoryRelease(Boolean.FALSE);

    if (Boolean.TRUE.equals(policyManager.getRelease()) && StringUtils
        .isNotBlank(policyManager.getRegion())
        && StringUtils.isNotBlank(policyManager.getSysOrigin())) {

      mongoTemplate.updateMulti(Query.query(Criteria.where("release").is(Boolean.TRUE)
              .and("region").is(policyManager.getRegion())
              .and("sysOrigin").is(policyManager.getSysOrigin())),
          new Update()
              .set("release", Boolean.FALSE)
              .set("updateTime", policyManager.getUpdateTime())
              .set("updateUser", policyManager.getUpdateUser()),
          TeamPolicyManager.class);

      policyManager.setHistoryRelease(Boolean.TRUE);
    }

    policyManager.setPolicy(policyManager.getPolicy().stream()
        .sorted(Comparator.comparing(TeamPolicy::getLevel))
        .collect(Collectors.toList()));
    mongoTemplate.save(policyManager);
  }

  @Override
  public void deleteById(Long id) {

    mongoTemplate.remove(Query.query(Criteria.where("id").is(id)), TeamPolicyManager.class);
  }

}
