package com.yami.shop.platform.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.FreightFeeReduction;
import com.yami.shop.bean.param.FreightFeeReductionParam;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.service.FreightFeeReductionService;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

import com.yami.shop.common.util.R;

/**
 * 运费减免管理实现
 *
 * @author wy
 * @version 1.0.0
 * @since 2025-01-01
 */
@RestController
@RequestMapping("/freightFee")
public class FreightFeeReductionController {

    @Resource
    private FreightFeeReductionService freightFeeReductionService;

    @ApiOperation("添加/编辑")
    @PostMapping("/addOrUpdate")
    public R<Void> addOrUpdate(@RequestBody FreightFeeReductionParam param) {
        freightFeeReductionService.addOrUpdate(param);
        return R.SUCCESS();
    }

    @ApiOperation("查看")
    @GetMapping("/get/{id}")
    public R<FreightFeeReduction> get(@PathVariable("id") Integer id) {
        freightFeeReductionService.get(id);
        return R.SUCCESS();
    }

    @ApiOperation("列表")
    @GetMapping("/search")
    public R<IPage<FreightFeeReduction>> search(PageParam<FreightFeeReduction> page) {
        IPage<FreightFeeReduction> result = freightFeeReductionService.page(page, new LambdaQueryWrapper<FreightFeeReduction>()
                .orderByAsc(FreightFeeReduction::getStatus)
                .orderByDesc(FreightFeeReduction::getId));
        return R.SUCCESS(result);
    }

    @ApiOperation("删除")
    @GetMapping("/remove/{id}")
    public R<Void> remove(@PathVariable("id") Integer id) {
        freightFeeReductionService.removeById(id);
        return R.SUCCESS();
    }

    @ApiOperation("获取减免")
    @GetMapping("/fee")
    public R<BigDecimal> fee() {
        BigDecimal fee = BigDecimal.ZERO;
        List<FreightFeeReduction> feeReductions = freightFeeReductionService.list(new LambdaQueryWrapper<FreightFeeReduction>()
                .eq(FreightFeeReduction::getStatus, 1)
                .ge(FreightFeeReduction::getEndTime, LocalDateTime.now())
                .orderByAsc(FreightFeeReduction::getEndTime));
        if (CollectionUtil.isNotEmpty(feeReductions)) {
            fee = feeReductions.get(0).getMoney();
        }
        return R.SUCCESS(fee);
    }
}
