package shop.alien.store.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.UserLoginInfo;
import shop.alien.entity.store.dto.LifeDiscountCouponDto;
import shop.alien.entity.store.dto.LifeDiscountCouponUserDto;
import shop.alien.entity.store.vo.LifeCouponStatusVo;
import shop.alien.entity.store.vo.LifeDiscountCouponVo;
import shop.alien.store.service.LifeDiscountCouponService;
import shop.alien.store.service.LifeDiscountCouponUserService;
import shop.alien.util.common.TokenInfo;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 优惠券表 前端控制器
 * </p>
 *
 * @author ssk
 * @since 2025-02-07
 */
@Api(tags = {"二期-优惠券"})
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/life-discount-coupon")
@RequiredArgsConstructor
public class LifeDiscountCouponController {

    private final LifeDiscountCouponService lifeDiscountCouponService;

    private final LifeDiscountCouponUserService lifeDiscountCouponUserService;

    @ApiOperation("发布优惠券")
    @ApiOperationSupport(order = 2)
    @PostMapping("/addDiscountCoupon")
    public R<Boolean> addDiscountCoupon(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo, @RequestBody LifeDiscountCouponDto lifeDiscountCouponDto) {
        log.info("LifeDiscountCouponController.addDiscountCoupon?lifeDiscountCoupon={}", lifeDiscountCouponDto.toString());
        try {
            boolean save = lifeDiscountCouponService.addDiscountCoupon(lifeDiscountCouponDto);
            if (!save) {
                return R.fail("发布失败");
            }
        } catch (Exception e) {
            log.error("LifeDiscountCouponController.addDiscountCoupon ERROR Msg={}", e.getMessage());
            return R.fail("发布失败");
        }
        return R.success("发布成功");
    }

    @ApiOperation("修改优惠券信息")
    @ApiOperationSupport(order = 2)
    @PutMapping("/editDiscountCoupon")
    public R<Boolean> editDiscountCoupon(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo, @RequestBody LifeDiscountCouponDto lifeDiscountCouponDto) {
        log.info("LifeDiscountCouponController.editDiscountCoupon?lifeDiscountCoupon={}", lifeDiscountCouponDto.toString());
        try {
            boolean edited = lifeDiscountCouponService.editDiscountCoupon(lifeDiscountCouponDto);
            if (!edited) {
                return R.fail("修改失败");
            }
        } catch (Exception e) {
            log.error("LifeDiscountCouponController.editDiscountCoupon ERROR Msg={}", e.getMessage());
            return R.fail("修改失败");
        }
        return R.success("修改成功");
    }

    @ApiOperation("删除优惠券信息")
    @ApiOperationSupport(order = 2)
    @DeleteMapping("/deleteDiscountCoupon/{id}")
    public R<Boolean> deleteDiscountCoupon(@PathVariable("id") Integer id) {
        log.info("LifeDiscountCouponController.deleteDiscountCoupon?id={}", id);
        try {
            boolean deleted = lifeDiscountCouponService.deleteDiscountCoupon(id);
            if (!deleted) {
                return R.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("LifeDiscountCouponController.deleteDiscountCoupon ERROR Msg={}", e.getMessage());
            return R.fail("删除失败");
        }
        return R.success("删除成功");
    }

    @ApiOperation("切换优惠券进行状态")
    @ApiOperationSupport(order = 2)
    @PutMapping("/cutDiscountCouponStatus")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "counponId", value = "优惠券id", dataType = "String", paramType = "query", required = true)
    })
    public R<Boolean> cutDiscountCouponStatus(@RequestParam(value = "counponId") String counponId) {
        log.info("LifeDiscountCouponController.cutDiscountCouponStatus?counponId={}", counponId);
        try {
            boolean save = lifeDiscountCouponService.cutDiscountCouponStatus(counponId);
            if (!save) {
                return R.fail("切换失败");
            }
        } catch (Exception e) {
            log.error("LifeDiscountCouponController.cutDiscountCouponStatus ERROR Msg={}", e.getMessage());
            return R.fail("切换失败");
        }
        return R.success("切换成功");
    }

    @ApiOperation("获取该优惠券的明细信息")
    @ApiOperationSupport(order = 2)
    @GetMapping("/getCounponDetailById")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "counponId", value = "优惠券id", dataType = "String", paramType = "query", required = true)
    })
    public R<LifeDiscountCouponVo> getCounponDetailById(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo,
                                                        @RequestParam(value = "counponId") String counponId) {
        log.info("LifeDiscountCouponController.getCounponDetailById?counponId={}", counponId);
        try {
            LifeDiscountCouponVo counponDetail = lifeDiscountCouponService.getCounponDetailById(counponId, userLoginInfo);
            return R.data(counponDetail);
        } catch (Exception e) {
            log.error("LifeDiscountCouponController.getCounponDetailById ERROR Msg={}", e.getMessage());
            return R.fail("查询失败");
        }
    }

    @ApiOperation("领取优惠券")
    @ApiOperationSupport(order = 2)
    @PostMapping("/receiveCoupon")
    public R<Boolean> receiveCoupon(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo, @RequestBody LifeDiscountCouponUserDto lifeDiscountCouponUserDto) {
        log.info("LifeDiscountCouponController.receiveCoupon?lifeDiscountCouponUserDto={}", lifeDiscountCouponUserDto.toString());
        return lifeDiscountCouponUserService.receiveCoupon(lifeDiscountCouponUserDto);
    }

    @ApiOperation("获取该用户该店铺优惠券列表")
    @ApiOperationSupport(order = 2)
    @GetMapping("/getStoreUserCouponList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "商户id", dataType = "String", paramType = "query", required = true)
    })
    public R<List<LifeDiscountCouponVo>> getStoreUserCouponList(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo,
                                                                @RequestParam(value = "storeId") String storeId) {
        log.info("LifeDiscountCouponController.getStoreUserCouponList?storeId={}", storeId);
        try {
            List<LifeDiscountCouponVo> storeCouponList = lifeDiscountCouponService.getStoreUserCouponList(storeId, userLoginInfo);
            return R.data(storeCouponList);
        } catch (Exception e) {
            log.error("LifeDiscountCouponController.getStoreUserCouponList ERROR Msg={}", e.getMessage());
            return R.fail("查询失败");
        }
    }

    @ApiOperation("获取该用户该店铺优惠券已领可用不可用列表")
    @ApiOperationSupport(order = 2)
    @GetMapping("/getStoreUserUsableCouponList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "商户id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "amount", value = "消费金额", dataType = "String", paramType = "query", required = true)
    })
    public R<Map> getStoreUserUsableCouponList(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo,
                                               @RequestParam(value = "storeId") String storeId,
                                               @RequestParam(value = "amount") BigDecimal amount
    ) {
        log.info("LifeDiscountCouponController.getStoreUserUsableCouponList?storeId={}", storeId);
        try {
            return R.data(lifeDiscountCouponService.getStoreUserUsableCouponList(storeId, userLoginInfo, amount));
        } catch (Exception e) {
            log.error("LifeDiscountCouponController.getStoreUserUsableCouponList ERROR Msg={}", e.getMessage());
            return R.fail("查询失败");
        }
    }


    @ApiOperation("获取该用户所有的优惠券列表")
    @ApiOperationSupport(order = 2)
    @GetMapping("/getUserCouponList")
    @ApiImplicitParams({@ApiImplicitParam(name = "page", value = "分页页数", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "分页条数", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "tabType", value = "分页类型（0：全部（未使用），1：即将过期，2：已使用，3：已过期）", dataType = "String", paramType = "query", required = true)
    })
    public R<List<LifeDiscountCouponVo>> getUserCouponList(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo,
                                                           @RequestParam(value = "tabType") String tabType,
                                                           @RequestParam(defaultValue = "1") int page,
                                                           @RequestParam(defaultValue = "10") int size) {
        log.info("LifeDiscountCouponController.getUserCouponList");
        try {
            List<LifeDiscountCouponVo> storeCouponList = lifeDiscountCouponService.getUserCouponList(userLoginInfo, page, size, tabType);
            return R.data(storeCouponList);
        } catch (Exception e) {
            log.error("LifeDiscountCouponController.getUserCouponList ERROR Msg={}", e.getMessage());
            return R.fail("查询失败");
        }
    }

    @ApiOperation("获取该店铺所有优惠券（分页）, 好友优惠券")
    @ApiOperationSupport(order = 2)
    @GetMapping("/getStoreAllCouponList")
    @ApiImplicitParams({@ApiImplicitParam(name = "page", value = "分页页数", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "分页条数", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "商户id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "couponName", value = "优惠券名称", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "tab", value = "分页类型(0:全部(传其他也查全部)，1：进行中，2：已结束)", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "couponsFromType", required = false, value = "查询类型(1:我的优惠券，2:好友的优惠券)"),
            @ApiImplicitParam(name = "couponStatus", required = false, value = "优惠券状态(0:草稿，1:正式)"),
    })
    public R<IPage<LifeDiscountCouponVo>> getStoreAllCouponList(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo,
                                                                @RequestParam(defaultValue = "1") int page,
                                                                @RequestParam(defaultValue = "10") int size,
                                                                @RequestParam(value = "storeId") String storeId,
                                                                @RequestParam(value = "couponName", required = false) String couponName,
                                                                @RequestParam(value = "tab") String tab,
                                                                @RequestParam(value = "couponsFromType", defaultValue = "1") int couponsFromType,
                                                                @RequestParam(value = "couponStatus", defaultValue = "1",required = false) int couponStatus
    ) {
        log.info("LifeDiscountCouponController.getStoreAllCouponList?storeId={}, couponName={}, tab={}, page={}, size={}, couponStatus={}", storeId, couponName, tab, page, size, couponStatus);
        try {
            IPage<LifeDiscountCouponVo> storeCouponList = lifeDiscountCouponService.getStoreAllCouponList(storeId, userLoginInfo, page, size, couponName, tab, couponsFromType, couponStatus);
            return R.data(storeCouponList);
        } catch (Exception e) {
            log.error("LifeDiscountCouponController.getStoreCouponList ERROR Msg={}", e.getMessage());
            return R.fail("查询失败");
        }
    }

    @ApiOperation("获取该店铺所有优惠券（不分页）")
    @ApiOperationSupport(order = 2)
    @GetMapping("/getStoreAllCouponListPaginateNot")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "商户id", dataType = "String", paramType = "query", required = true)
    })
    public R<List<LifeDiscountCouponVo>> getStoreAllCouponListPaginateNot(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo,
                                                                          @RequestParam(value = "storeId") String storeId,
                                                                          @RequestParam(value = "status", required = false) String status,
                                                                          @RequestParam(value = "couponStatus", defaultValue = "1",required = false) int couponStatus
    ) {
        log.info("LifeDiscountCouponController.getStoreAllCouponListPaginateNot?storeId={}，status={}, couponStatus={}", storeId, status, couponStatus);
        try {
            List<LifeDiscountCouponVo> storeCouponList = lifeDiscountCouponService.getStoreAllCouponListPaginateNot(status, storeId, userLoginInfo, couponStatus);
            return R.data(storeCouponList);
        } catch (Exception e) {
            log.error("LifeDiscountCouponController.getStoreAllCouponListPaginateNot ERROR Msg={}", e.getMessage());
            return R.fail("查询失败");
        }
    }

    @ApiOperation("获取该优惠券使用规则")
    @ApiOperationSupport(order = 2)
    @GetMapping("/getCouponRule")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "couponId", value = "优惠券id", dataType = "String", paramType = "query", required = true),
    })
    public R<List<LifeDiscountCouponVo>> getCouponRule(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo,
                                                       @RequestParam(value = "couponId") String couponId) {
        log.info("LifeDiscountCouponController.getCouponRule?couponId={}", couponId);
        try {
            String couponRule = lifeDiscountCouponService.getCouponRule(couponId, userLoginInfo);
            return R.success(couponRule);
        } catch (Exception e) {
            log.error("LifeDiscountCouponController.getCouponRule ERROR Msg={}", e.getMessage());
            return R.fail("查询失败");
        }
    }

    @ApiOperation("获取优惠券状态")
    @ApiOperationSupport(order = 1)
    @GetMapping("/getCouponStatus")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "couponId", value = "优惠券id", dataType = "String", paramType = "query", required = true),
    })
    public R<LifeCouponStatusVo> getCouponStatus(@RequestParam(value = "couponId") String couponId) {
        log.info("LifeDiscountCouponController.getCouponStatus?couponId={}", couponId);
        try {
            LifeCouponStatusVo lifeCouponStatusVo = lifeDiscountCouponService.getCouponStatus(couponId);
            return R.data(lifeCouponStatusVo);
        } catch (Exception e) {
            log.error("LifeDiscountCouponController.getCouponStatus ERROR Msg={}", e.getMessage());
            return R.fail("查询失败");
        }
    }

}
