package com.gxwebsoft.oa.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.oa.entity.OaApp;
import com.gxwebsoft.oa.service.OaAppRenewService;
import com.gxwebsoft.oa.entity.OaAppRenew;
import com.gxwebsoft.oa.param.OaAppRenewParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.oa.service.OaAppService;
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.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 续费管理控制器
 *
 * @author 科技小王子
 * @since 2024-09-10 20:57:41
 */
@Tag(name = "续费管理管理")
@RestController
@RequestMapping("/api/oa/oa-app-renew")
public class OaAppRenewController extends BaseController {
    @Resource
    private OaAppRenewService oaAppRenewService;
    @Resource
    private OaAppService oaAppService;

    @Operation(summary = "分页查询续费管理")
    @GetMapping("/page")
    public ApiResult<PageResult<OaAppRenew>> page(OaAppRenewParam param) {
        // 使用关联查询
        return success(oaAppRenewService.pageRel(param));
    }

    @Operation(summary = "查询全部续费管理")
    @GetMapping()
    public ApiResult<List<OaAppRenew>> list(OaAppRenewParam param) {
        PageParam<OaAppRenew, OaAppRenewParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(oaAppRenewService.list(page.getOrderWrapper()));
        // 使用关联查询
        //return success(oaAppRenewService.listRel(param));
    }

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

    @Operation(summary = "添加续费管理")
    @PostMapping()
    public ApiResult<?> save(@RequestBody OaAppRenew oaAppRenew) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          oaAppRenew.setUserId(loginUser.getUserId());
        }
        if (oaAppRenewService.save(oaAppRenew)) {
          oaAppService.update(new LambdaUpdateWrapper<OaApp>().eq(OaApp::getAppId, oaAppRenew.getAppId()).set(OaApp::getShowExpiration, true));
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @Operation(summary = "修改续费管理")
    @PutMapping()
    public ApiResult<?> update(@RequestBody OaAppRenew oaAppRenew) {
        if (oaAppRenewService.updateById(oaAppRenew)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @Operation(summary = "删除续费管理")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (oaAppRenewService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @Operation(summary = "批量添加续费管理")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<OaAppRenew> list) {
        if (oaAppRenewService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @Operation(summary = "批量修改续费管理")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<OaAppRenew> batchParam) {
        if (batchParam.update(oaAppRenewService, "app_renew_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

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


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

    // 获取当前年份的起止时间
    LocalDateTime startOfYear = LocalDateTime.now().withMonth(1).withDayOfMonth(1)
      .withHour(0).withMinute(0).withSecond(0);
    LocalDateTime endOfYear = startOfYear.plusYears(1).minusNanos(1);

    // 今年应收续费总金额（到期时间在今年的记录）
    BigDecimal totalNum1 = oaAppService.sumMoney(new LambdaQueryWrapper<OaApp>()
      .between(OaApp::getExpirationTime, startOfYear, endOfYear));
    // 今年已收续费总金额（到期时间在今年的记录）
    BigDecimal totalNum2 = oaAppRenewService.sumMoney(new LambdaQueryWrapper<OaAppRenew>()
      .between(OaAppRenew::getEndTime, startOfYear, endOfYear));

    // 今年已收续费总金额（创建时间在今年且已支付的记录）
    BigDecimal totalNum3 = oaAppRenewService.sumMoney(new LambdaQueryWrapper<OaAppRenew>()
      .between(OaAppRenew::getCreateTime, startOfYear, endOfYear)
      .isNotNull(OaAppRenew::getMoney));

    data.put("totalNum1", totalNum1 != null ? totalNum1 : BigDecimal.ZERO);
    data.put("totalNum2", totalNum2 != null ? totalNum2 : BigDecimal.ZERO);
    return success(data);
  }

}
