package com.gxwebsoft.project.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.project.entity.Project;
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.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.project.service.ProjectService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 续费管理控制器
 *
 * @author 科技小王子
 * @since 2025-03-14 16:21:11
 */
@Tag(name = "续费管理管理")
@RestController
@RequestMapping("/api/project/project-renew")
public class ProjectRenewController extends BaseController {
  @Resource
  private ProjectRenewService projectRenewService;
  @Resource
  private ProjectService projectService;

  @PreAuthorize("hasAuthority('project:projectRenew:list')")
  @Operation(summary = "分页查询续费管理")
  @GetMapping("/page")
  public ApiResult<PageResult<ProjectRenew>> page(ProjectRenewParam param) {
    return success(projectRenewService.pageRel(param));
  }

  @PreAuthorize("hasAuthority('project:projectRenew:list')")
  @Operation(summary = "查询全部续费管理")
  @GetMapping()
  public ApiResult<List<ProjectRenew>> list(ProjectRenewParam param) {
    // 使用关联查询
    return success(projectRenewService.listRel(param));
  }

  @PreAuthorize("hasAuthority('project:projectRenew:list')")
  @Operation(summary = "根据id查询续费管理")
  @GetMapping("/{id}")
  public ApiResult<ProjectRenew> get(@PathVariable("id") Integer id) {
    // 使用关联查询
    return success(projectRenewService.getByIdRel(id));
  }

  @PreAuthorize("hasAuthority('project:projectRenew:save')")
  @OperationLog
  @Operation(summary = "添加续费管理")
  @PostMapping()
  public ApiResult<?> save(@RequestBody ProjectRenew projectRenew) {
    // 记录当前登录用户id
    User loginUser = getLoginUser();
    if (loginUser != null) {
      projectRenew.setUserId(loginUser.getUserId());
    }
    // 更新项目状态
    if (projectRenewService.save(projectRenew)) {
      projectService.updateByRenew(projectRenew);
      return success("操作成功");
    }
    return fail("操作失败");
  }

  @PreAuthorize("hasAuthority('project:projectRenew:update')")
  @OperationLog
  @Operation(summary = "修改续费管理")
  @PutMapping()
  public ApiResult<?> update(@RequestBody ProjectRenew projectRenew) {
    if (projectRenewService.updateById(projectRenew)) {
      return success("修改成功");
    }
    return fail("修改失败");
  }

  @PreAuthorize("hasAuthority('project:projectRenew:remove')")
  @OperationLog
  @Operation(summary = "删除续费管理")
  @DeleteMapping("/{id}")
  public ApiResult<?> remove(@PathVariable("id") Integer id) {
    // 撤销操作
    final ProjectRenew renew = projectRenewService.getByIdRel(id);
    if (ObjectUtil.isNotEmpty(renew)) {
      final Project project = projectService.getOne(new LambdaQueryWrapper<Project>().eq(Project::getAppId, renew.getAppId()));
      if (renew.getDays() > 0) {
        // 按天续费
        project.setExpirationTime(project.getExpirationTime().minusDays(renew.getDays()));
      } else {
        // 按年续费
        project.setExpirationTime(project.getExpirationTime().minusMonths(12 * renew.getDuration()));
        // 回退上一年的续费金额
        final List<ProjectRenew> renews = projectRenewService.list(new LambdaQueryWrapper<ProjectRenew>().eq(ProjectRenew::getAppId, renew.getAppId()).orderByDesc(ProjectRenew::getAppRenewId).last("limit 2"));
        if(renews.size() > 1){
          final ProjectRenew projectRenew = renews.get(1);
          project.setRenewMoney(projectRenew.getPayPrice());
        }
        projectService.updateById(project);
      }
      // 保存到期时间所在的年月日
      final LocalDateTime expirationTime = project.getExpirationTime();
      LocalDate localDate = expirationTime.toLocalDate();
      int year = localDate.getYear();
      int month = localDate.getMonthValue(); // 获取月份，范围是1到12
      int day = localDate.getDayOfMonth(); // 获取日，范围是1到31
      project.setYear(year);
      project.setMonth(month);
      project.setDay(day);
    }

    if (projectRenewService.removeById(id)) {
      return success("该笔续费操作已撤销");
    }
    return fail("删除失败");
  }

  @PreAuthorize("hasAuthority('project:projectRenew:save')")
  @OperationLog
  @Operation(summary = "批量添加续费管理")
  @PostMapping("/batch")
  public ApiResult<?> saveBatch(@RequestBody List<ProjectRenew> list) {
    if (projectRenewService.saveBatch(list)) {
      return success("添加成功");
    }
    return fail("添加失败");
  }

  @PreAuthorize("hasAuthority('project:projectRenew:update')")
  @OperationLog
  @Operation(summary = "批量修改续费管理")
  @PutMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody BatchParam<ProjectRenew> batchParam) {
    if (batchParam.update(projectRenewService, "app_renew_id")) {
      return success("修改成功");
    }
    return fail("修改失败");
  }

  @PreAuthorize("hasAuthority('project:projectRenew:remove')")
  @OperationLog
  @Operation(summary = "批量删除续费管理")
  @DeleteMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
    if (projectRenewService.removeByIds(ids)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }


  @Operation(summary = "统计信息")
  @GetMapping("/data")
  public ApiResult<Map<String, BigDecimal>> data(ProjectParam param) {
    Map<String, BigDecimal> data = new HashMap<>();
    final User loginUser = getLoginUser();
    if (loginUser == null) {
      return fail("请先登录", null);
    }

    // 今天日期
    DateTime date = DateUtil.date();
    // 获取当前年份的起止时间
    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);


    // TODO 近30天可催收的续费总额
    // 下个月的今天
    final DateTime nextMonth = DateUtil.nextMonth();
    BigDecimal totalPrice30 = projectService.sumMoney(new LambdaQueryWrapper<Project>()
      .lt(Project::getExpirationTime, nextMonth)
      .gt(Project::getExpirationTime, date)
      .lt(Project::getCreateTime, date)
      .eq(Project::getShowExpiration, true)
      .eq(Project::getAppStatus, "已上架")
      .eq(Project::getDeleted, 0)
    );
    data.put("totalPrice30", totalPrice30);

    // TODO 按所属月份查询续费总金额
    if(param.getMonth() != null){
      BigDecimal currentQueryTotalPrice = projectService.sumMoney(new LambdaQueryWrapper<Project>()
        .eq(Project::getMonth, param.getMonth())
        .eq(Project::getShowExpiration, true)
        .eq(Project::getAppStatus, "已上架")
        .eq(Project::getDeleted, 0)
      );
      data.put("currentQueryTotalPrice", currentQueryTotalPrice);
    }

    // TODO 有效的续费总金额
    final BigDecimal effectiveTotalPrice = projectService.sumMoney(new LambdaQueryWrapper<Project>()
      .eq(Project::getDeleted, 0)
      .eq(Project::getShowExpiration, true)
      .eq(Project::getAppStatus, "已上架")
      .gt(Project::getExpirationTime, date));
    data.put("effectiveTotalPrice", effectiveTotalPrice);

    // TODO 已超过催收时间的续费总额
    final BigDecimal expiredPrice = projectService.sumMoney(new LambdaQueryWrapper<Project>()
      .eq(Project::getDeleted, 0)
      .eq(Project::getShowExpiration, true)
      .eq(Project::getAppStatus, "已上架")
      .lt(Project::getExpirationTime, date));
    data.put("expiredPrice", expiredPrice);

    // TODO 计算每年可收续费总额
    final BigDecimal totalRenewPrice = projectService.sumMoney(new LambdaQueryWrapper<Project>()
      .eq(Project::getDeleted, 0)
      .eq(Project::getShowExpiration, true)
      .eq(Project::getAppStatus, "已上架")
    );

    // TODO 本月已收续费总额
    final BigDecimal monthTotalPrice = projectRenewService.sumMoney(new LambdaQueryWrapper<ProjectRenew>()
      .between(ProjectRenew::getCreateTime, startOfMonth, endOfMonth)
      .eq(ProjectRenew::getDeleted, 0)
    );
    data.put("monthTotalPrice", monthTotalPrice);

    // TODO 今年已收续费总额
    BigDecimal yearTotalPrice = projectRenewService.sumMoney(new LambdaQueryWrapper<ProjectRenew>()
      .between(ProjectRenew::getCreateTime, startOfYear, endOfYear)
      .eq(ProjectRenew::getDeleted, 0)
    );
    data.put("yearTotalPrice", yearTotalPrice);

    // TODO 去年已收续费总额
    BigDecimal lastTotalPrice = projectRenewService.sumMoney(new LambdaQueryWrapper<ProjectRenew>()
      .eq(ProjectRenew::getDeleted, 0)
      .between(ProjectRenew::getEndTime, startOfLastYear, endOfLastYear));
    // 去年已收续费总额
    data.put("lastTotalPrice", lastTotalPrice);

    data.put("totalRenewPrice", totalRenewPrice);

    return success(data);
  }

  @Operation(summary = "统计每个月的续费总金额")
  @GetMapping("/listMonthRenewPrice")
  public ApiResult<List<BigDecimal>> listMonthRenewPrice() {
    final User loginUser = getLoginUser();
    if (loginUser != null) {
      final LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
      List<BigDecimal> monthPrice = new ArrayList<>();
      for (int i = 1; i < 13; i++) {
        wrapper.clear();
        wrapper.eq(Project::getDeleted, 0)
          .eq(Project::getShowExpiration, true)
          .eq(Project::getAppStatus, "已上架");
        monthPrice.add(projectService.sumMoney(wrapper.eq(Project::getMonth,i)));
      }
      return success(monthPrice);
    }
    return fail("请先登录", null);
  }

}
