package com.sqx.modules.member.controller;

import cn.hutool.core.util.ObjectUtil;
import com.sqx.common.exception.SqxException;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.member.dto.VipPromoCodeDTO;
import com.sqx.modules.member.query.VipPromoCodeQuery;
import com.sqx.modules.member.query.VipPromoRecordQuery;
import com.sqx.modules.member.service.VipPromoCodeService;
import com.sqx.modules.member.service.VipPromoRecordService;
import com.sqx.modules.utils.PromotionCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@Api(tags = "会员推广管理")
@RestController
@RequestMapping("admin/vip-promo")
@RequiredArgsConstructor
public class VipPromoCodeController{
    
    private final VipPromoCodeService vipPromoCodeService;
    private final VipPromoRecordService vipPromoRecordService;

    @GetMapping("pages")
    @ApiOperation("分页查询会员推广码")
    public Result pages(@Valid VipPromoCodeQuery query) {
        PageUtils page = vipPromoCodeService.pages(query);
        return Result.success().put("data", page);
    }

    @GetMapping("generate-promo-code")
    @ApiOperation("生成会员推广码")
    public Result generatePromoCode() {
        String promoCode = PromotionCodeUtil.generatePromotionCode();
        return Result.success().put("data", promoCode);
    }

    @PostMapping
    @ApiOperation("添加会员推广码")
    public Result add(@RequestBody @Valid VipPromoCodeDTO dto) {
        vipPromoCodeService.save(dto);
        return Result.success();
    }

    @PutMapping
    @ApiOperation("修改会员推广码")
    public Result update(@RequestBody @Valid VipPromoCodeDTO dto) {
        if (ObjectUtil.isNull(dto.getId())) {
            throw new SqxException("id不能为空");
        }
        vipPromoCodeService.update(dto);
        return Result.success();
    }

    @DeleteMapping
    @ApiOperation("删除会员推广码")
    public Result delete(@RequestBody @ApiParam("id的集合") Long[] ids) {
        vipPromoCodeService.removeByIds(Arrays.asList(ids));
        return Result.success();
    }

    @GetMapping("record/pages")
    @ApiOperation("分页查询会员推广记录")
    public Result recordPages(@Valid VipPromoRecordQuery query) {
        PageUtils page = vipPromoRecordService.pages(query);
        return Result.success().put("data", page);
    }
}
