package com.gxwebsoft.bszx.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.bszx.entity.BszxClass;
import com.gxwebsoft.bszx.entity.BszxPay;
import com.gxwebsoft.bszx.param.BszxClassParam;
import com.gxwebsoft.bszx.service.BszxClassService;
import com.gxwebsoft.bszx.service.BszxPayService;
import com.gxwebsoft.cms.entity.CmsArticle;
import com.gxwebsoft.cms.service.CmsArticleService;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.bszx.service.BszxPayRankingService;
import com.gxwebsoft.bszx.entity.BszxPayRanking;
import com.gxwebsoft.bszx.param.BszxPayRankingParam;
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 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.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 百色中学-捐款排行控制器
 *
 * @author 科技小王子
 * @since 2025-03-25 08:54:09
 */
@Tag(name = "百色中学-捐款排行管理")
@RestController
@RequestMapping("/api/bszx/bszx-pay-ranking")
public class BszxPayRankingController extends BaseController {
    @Resource
    private BszxPayRankingService bszxPayRankingService;
    @Resource
    private CmsArticleService cmsArticleService;
    @Resource
    private BszxPayService bszxPayService;
    @Resource
    private BszxClassService bszxClassService;
    @Resource
    private RedisUtil redisUtil;

    @PreAuthorize("hasAuthority('bszx:bszxPayRanking:list')")
    @Operation(summary = "分页查询百色中学-捐款排行")
    @GetMapping("/page")
    public ApiResult<PageResult<BszxPayRanking>> page(BszxPayRankingParam param) {
        // 使用关联查询
        return success(bszxPayRankingService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('bszx:bszxPayRanking:list')")
    @Operation(summary = "查询全部百色中学-捐款排行")
    @GetMapping()
    public ApiResult<List<BszxPayRanking>> list(BszxPayRankingParam param) {
        // 使用关联查询
        return success(bszxPayRankingService.listRel(param));
    }

    @Operation(summary = "查询全部百色中学-捐款排行榜")
    @GetMapping("/ranking")
    public ApiResult<List<BszxPayRanking>> ranking(BszxPayRankingParam param) {
      final ArrayList<BszxPayRanking> rankings = new ArrayList<>();
      final LambdaQueryWrapper<BszxPay> wrapper = new LambdaQueryWrapper<>();
      final List<CmsArticle> list = cmsArticleService.list(new LambdaQueryWrapper<CmsArticle>().eq(CmsArticle::getCategoryId, 2444));

      list.forEach(item -> {
        final BszxPayRanking ranking = new BszxPayRanking();
        wrapper.clear();
        // 按时间段查询
        if(param.getCreateTimeStart() != null && param.getCreateTimeEnd() != null){
          final String timeStart = param.getCreateTimeStart();
          final String timeEnd = param.getCreateTimeEnd();
          wrapper.ge(BszxPay::getCreateTime, timeStart);
          wrapper.le(BszxPay::getCreateTime, timeEnd);
        }
        wrapper.eq(BszxPay::getFormId, item.getArticleId());
        ranking.setFormId(item.getArticleId());
        ranking.setFormName(item.getTitle());
        ranking.setNumber((long) bszxPayService.count(wrapper));
        ranking.setTotalPrice(bszxPayService.sumMoney(wrapper));
        rankings.add(ranking);
      });
      // totalPrice按大到小排序
      rankings.sort((o1, o2) -> o2.getTotalPrice().compareTo(o1.getTotalPrice()));
      return success(rankings);
    }


  @Operation(summary = "查询全部百色中学-千班万元")
  @GetMapping("/ranking2")
  public ApiResult<List<BszxClass>> ranking2(BszxClassParam param) {
    final LambdaQueryWrapper<BszxPay> wrapper = new LambdaQueryWrapper<>();
    final List<BszxClass> list = bszxClassService.listRel(param);

    String key = "BSZX:UpdateRanking2";
    final String isTimeOut = redisUtil.get(key);
    if(StrUtil.isNotBlank(isTimeOut)){
      list.sort((o1, o2) -> o2.getTotalMoney().compareTo(o1.getTotalMoney()));
      return success(list);
    }
    list.forEach(item -> {
      wrapper.clear();
      wrapper.eq(BszxPay::getGradeName,item.getGradeName());
      wrapper.eq(BszxPay::getClassName, item.getName());
      item.setTotalMoney(bszxPayService.sumMoney(wrapper));
      bszxClassService.updateById(item);
    });
    // totalPrice按大到小排序
    list.sort((o1, o2) -> o2.getTotalMoney().compareTo(o1.getTotalMoney()));
    redisUtil.set(key, 1,1L, TimeUnit.DAYS);
    return success(list);
  }


  @PreAuthorize("hasAuthority('bszx:bszxPayRanking:list')")
    @Operation(summary = "根据id查询百色中学-捐款排行")
    @GetMapping("/{id}")
    public ApiResult<BszxPayRanking> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(bszxPayRankingService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('bszx:bszxPayRanking:save')")
    @OperationLog
    @Operation(summary = "添加百色中学-捐款排行")
    @PostMapping()
    public ApiResult<?> save(@RequestBody BszxPayRanking bszxPayRanking) {
        if (bszxPayRankingService.save(bszxPayRanking)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('bszx:bszxPayRanking:update')")
    @OperationLog
    @Operation(summary = "修改百色中学-捐款排行")
    @PutMapping()
    public ApiResult<?> update(@RequestBody BszxPayRanking bszxPayRanking) {
        if (bszxPayRankingService.updateById(bszxPayRanking)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('bszx:bszxPayRanking:remove')")
    @OperationLog
    @Operation(summary = "删除百色中学-捐款排行")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (bszxPayRankingService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('bszx:bszxPayRanking:save')")
    @OperationLog
    @Operation(summary = "批量添加百色中学-捐款排行")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<BszxPayRanking> list) {
        if (bszxPayRankingService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('bszx:bszxPayRanking:update')")
    @OperationLog
    @Operation(summary = "批量修改百色中学-捐款排行")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<BszxPayRanking> batchParam) {
        if (batchParam.update(bszxPayRankingService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('bszx:bszxPayRanking:remove')")
    @OperationLog
    @Operation(summary = "批量删除百色中学-捐款排行")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (bszxPayRankingService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
