package com.gxwebsoft.project.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.gxwebsoft.oa.entity.OaAppRenew;
import com.gxwebsoft.project.entity.Project;
import com.gxwebsoft.project.mapper.ProjectRenewMapper;
import com.gxwebsoft.project.param.ProjectParam;
import com.gxwebsoft.project.service.ProjectRenewService;
import com.gxwebsoft.project.entity.ProjectRenew;
import com.gxwebsoft.project.param.ProjectRenewParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.project.service.ProjectService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 续费管理Service实现
 *
 * @author 科技小王子
 * @since 2025-03-14 16:21:11
 */
@Service
public class ProjectRenewServiceImpl extends ServiceImpl<ProjectRenewMapper, ProjectRenew> implements ProjectRenewService {
  @Resource
  private ProjectService projectService;

  @Override
  public PageResult<ProjectRenew> pageRel(ProjectRenewParam param) {
    final String sceneType = param.getSceneType();
    PageParam<ProjectRenew, ProjectRenewParam> page = new PageParam<>(param);
    page.setDefaultOrder("create_time desc");

    // TODO 默认查询条件：读取符合续费条件的项目
    if (sceneType == null) {
      List<ProjectRenew> list = baseMapper.selectPageRel(page, param);
      return new PageResult<>(list, page.getTotal());
    }



    // 特殊场景查询
    List<ProjectRenew> list = null;
    DateTime date = DateUtil.date();
    final DateTime nextMonth = DateUtil.nextMonth();
    // 获取当前年份的起止时间
    LocalDateTime startOfYear = LocalDateTime.now().withMonth(1).withDayOfMonth(1)
      .withHour(0).withMinute(0).withSecond(0);
    LocalDateTime endOfYear = startOfYear.plusYears(1).minusNanos(1);
    // 去年的起止时间
    LocalDateTime startOfLastYear = LocalDateTime.now().minusYears(1).withMonth(1).withDayOfMonth(1)
      .withHour(0).withMinute(0).withSecond(0);
    LocalDateTime endOfLastYear = startOfLastYear.plusYears(1).minusNanos(1);
    // 本月起止时间
    LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1)
      .withHour(0).withMinute(0).withSecond(0);
    LocalDateTime endOfMonth = startOfMonth.plusMonths(1).minusNanos(1);

    if (StrUtil.isNotBlank(sceneType)) {
      // TODO 近30天可催收的续费总额
      if (sceneType.equals("totalPrice30")) {
        list = list(new LambdaQueryWrapper<ProjectRenew>()
          .lt(ProjectRenew::getEndTime, nextMonth)
          .gt(ProjectRenew::getEndTime, date)
          .lt(ProjectRenew::getCreateTime, date)
          .eq(ProjectRenew::getDeleted, 0)
          .orderByAsc(ProjectRenew::getEndTime)
        );
      }

      // TODO 本月已收续费总额
      if (sceneType.equals("monthTotalPrice")) {
        list = list(new LambdaQueryWrapper<ProjectRenew>()
          .between(ProjectRenew::getCreateTime, startOfYear, endOfMonth)
          .eq(ProjectRenew::getDeleted, 0)
          .orderByDesc(ProjectRenew::getEndTime)
        );
      }

      // TODO 今年已收续费总额
      if (sceneType.equals("yearTotalPrice")) {
        list = list(new LambdaQueryWrapper<ProjectRenew>()
          .between(ProjectRenew::getCreateTime, startOfMonth, endOfYear)
          .eq(ProjectRenew::getDeleted, 0)
          .orderByDesc(ProjectRenew::getEndTime)
        );
      }

      // TODO 去年已收续费列表
      if (sceneType.equals("lastTotalPrice")) {
        list = list(new LambdaQueryWrapper<ProjectRenew>()
          .between(ProjectRenew::getCreateTime, startOfLastYear, endOfLastYear)
          .eq(ProjectRenew::getDeleted, 0)
          .orderByDesc(ProjectRenew::getEndTime)
        );
      }
    }

    // TODO 获取项目名称
    assert list != null;
    final Set<Integer> collectByAppIds = list.stream().map(ProjectRenew::getAppId).collect(Collectors.toSet());
    final ProjectParam projectParam = new ProjectParam();
    projectParam.setAppIds(collectByAppIds);
    final List<Project> projects = projectService.listRel(projectParam);

    final Map<Integer, List<Project>> collect = projects.stream().collect(Collectors.groupingBy(Project::getAppId));
    list.forEach(d -> {
      final List<Project> projectsItem = collect.get(d.getAppId());
      if (!CollectionUtils.isEmpty(projectsItem)) {
        final Project project = projectsItem.get(0);
        d.setAppName(project.getAppName());
        d.setNickname(project.getNickname());
        d.setAvatar(project.getAvatar());
        d.setCustomerId(project.getCompanyId());
        d.setCustomerName(project.getCompanyName());
      }
    });
    return new PageResult<>(list, (long) list.size());
  }

  @Override
  public List<ProjectRenew> listRel(ProjectRenewParam param) {
    List<ProjectRenew> list = baseMapper.selectListRel(param);
    // 排序
    PageParam<ProjectRenew, ProjectRenewParam> page = new PageParam<>();
    page.setDefaultOrder("create_time desc");
    return page.sortRecords(list);
  }

  @Override
  public ProjectRenew getByIdRel(Integer appRenewId) {
    ProjectRenewParam param = new ProjectRenewParam();
    param.setAppRenewId(appRenewId);
    return param.getOne(baseMapper.selectListRel(param));
  }

  @Override
  public BigDecimal sumMoney(LambdaQueryWrapper<ProjectRenew> wrapper) {
    return baseMapper.selectSumMoney(wrapper);
  }

}
