package com.jeequan.jeepay.mch.ctrl.red;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.RedPacketAccount;
import com.jeequan.jeepay.db.entity.RedPacketRule;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.RedPacketAccountService;
import com.jeequan.jeepay.service.impl.RedPacketRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * TODO
 * @author crystal
 * @date 2023/12/6 15:11
 */
@RestController
@RequestMapping("/api/redPacketRule")
public class RedPacketRuleController extends CommonCtrl {

    @Autowired private RedPacketRuleService redPacketRuleService;

    @PreAuthorize("hasAuthority('ENT_REDPACKET_RULE_LIST')")
    @GetMapping
    public ApiRes list() {
        RedPacketRule info = getObject(RedPacketRule.class);
        LambdaQueryWrapper<RedPacketRule> wrapper = RedPacketRule.gw(info);
        wrapper.eq(RedPacketRule::getMchNo, getCurrentMchNo());
        Date[] dateRange = info.buildQueryDateRange();
        if (dateRange[0] != null) {
            wrapper.ge(RedPacketRule::getUpdatedAt, dateRange[0]);
        }
        if (dateRange[1] != null) {
            wrapper.le(RedPacketRule::getUpdatedAt, dateRange[1]);
        }
        wrapper.orderByDesc(RedPacketRule::getUpdatedAt);
        Page<RedPacketRule> pages = redPacketRuleService.page(getIPage(), wrapper);
        return ApiRes.page(pages);
    }

    /**
     * 新增规则
     * @return
     */
    @PreAuthorize("hasAuthority('ENT_REDPACKET_RULE_ADD')")
    @RequestMapping(method = RequestMethod.POST)
    public ApiRes add() {
        RedPacketRule info = getObject(RedPacketRule.class);
        info.setMchNo(getCurrentMchNo());
        redPacketRuleService.addSave(info);
        return ApiRes.ok();
    }

    /**
     * 查询信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public ApiRes get(@PathVariable("id") Integer id) {
        return ApiRes.ok(redPacketRuleService.getById(id));
    }

    /**
     * 修改
     * @param
     * @return
     */
    @PreAuthorize("hasAuthority('ENT_REDPACKET_RULE_EDIT')")
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public ApiRes edit() {
        RedPacketRule info = getObject(RedPacketRule.class);
        info.check();
        redPacketRuleService.updateById(info);
        return ApiRes.ok();
    }
}
