package com.ym.mec.web.controller;

import com.ym.mec.biz.dal.entity.SysCoupon;
import com.ym.mec.biz.dal.page.SysCouponQueryInfo;
import com.ym.mec.biz.service.SysCouponService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Objects;

@RequestMapping("sysCoupon")
@Api(tags = "优惠券")
@RestController
public class SysCouponController extends BaseController {

    @Autowired
    private SysCouponService sysCouponService;

    @ApiOperation("新增")
    @PostMapping(value = "add")
    @PreAuthorize("@pcs.hasPermissions('sysCoupon/add')")
    public HttpResponseResult add(@Valid SysCoupon sysCoupon) {
        try {
            return succeed(sysCouponService.add(sysCoupon));
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }

    @ApiOperation("修改")
    @PostMapping(value = "updateCoupon")
    @PreAuthorize("@pcs.hasPermissions('sysCoupon/updateCoupon')")
    public HttpResponseResult updateCoupon(SysCoupon sysCoupon) {
        sysCouponService.updateCoupon(sysCoupon);
        return succeed();
    }

    @ApiOperation("删除")
    @PostMapping(value = "delete")
    @PreAuthorize("@pcs.hasPermissions('sysCoupon/delete')")
    public HttpResponseResult del(Integer id) {
        SysCoupon sysCoupon = sysCouponService.get(id);
        if (Objects.isNull(sysCoupon)) {
            return failed("优惠券信息不存在");
        }
        if (sysCoupon.getConsumeNum() > 0) {
            return failed("此优惠券已消耗，暂不可删除");
        }
        return succeed(sysCouponService.delete(id));
    }

    @ApiOperation("分页查询")
    @RequestMapping(value = "queryPage")
//    @PreAuthorize("@pcs.hasPermissions('sysCoupon/queryPage')")
    public HttpResponseResult queryPage(SysCouponQueryInfo queryInfo) {
        return succeed(sysCouponService.queryPage(queryInfo));
    }
}
