package shop.alien.storeplatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.EssentialHolidayComparison;
import shop.alien.entity.store.LifeCoupon;
import shop.alien.entity.store.UserLoginInfo;
import shop.alien.entity.storePlatform.vo.LifeCouponPlatformVo;
import shop.alien.entity.storePlatform.vo.DiscountCouponPlatformVo;
import shop.alien.storeplatform.service.LifeCouponPlatformService;
import shop.alien.storeplatform.service.LifeDiscountCouponPlatformService;
import shop.alien.util.common.TokenInfo;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 优惠券管理控制器（平台端）
 * 提供优惠券相关的管理接口，包括优惠券的创建、更新、删除、查询、核销等功能
 * 支持优惠券库存管理、状态管理、节假日配置等操作
 *
 * @author alien-cloud
 * @date 2025-11-18
 */
@Api(tags = {"商家端-代金券"})
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/couponPlatform")
@RequiredArgsConstructor
public class LifeCouponPlatformController {

    private final LifeCouponPlatformService lifeCouponService;

    private final LifeDiscountCouponPlatformService lifeDiscountCouponPlatformService;

    /**
     * 新建或更新代金券
     * 根据代金券是否存在ID判断是新增还是更新操作
     *
     * @param lifeCoupon 代金券对象
     * @return R<LifeCoupon> 保存后的代金券信息
     * @author alien-cloud
     * @date 2025-11-18
     */
    @ApiOperation("新建代金券")
    @PostMapping("/addOrUpdateCoupon")
    public R<LifeCoupon> addOrUpdateCoupon(@RequestBody LifeCoupon lifeCoupon) {
        log.info("LifeCouponController.addOrUpdateCoupon?lifeCoupon={}", lifeCoupon.toString());
        return R.data(lifeCouponService.addOrUpdateCoupon(lifeCoupon));
    }

    /**
     * 修改库存数量
     * 更新指定优惠券的库存数量
     *
     * @param id 优惠券ID
     * @param singleQty 库存数量
     * @return R<Boolean> 操作结果
     * @author alien-cloud
     * @date 2025-11-18
     */
    @ApiOperation("修改库存数量")
    @GetMapping("/updateCouponSingleQty")
    public R<Boolean> updateCouponSingleQty(@RequestParam("id") Integer id, @RequestParam("singleQty") Integer singleQty) {
        log.info("LifeCouponController.updateCouponSingleQty?id={}&singleQty={}", id, singleQty);
        if (lifeCouponService.updateCouponSingleQty(id, singleQty)) {
            return R.success("成功");
        }
        return R.fail("失败");
    }

    /**
     * 删除代金券
     * 根据优惠券ID删除代金券信息
     *
     * @param id 优惠券ID
     * @return R<Boolean> 操作结果
     * @author alien-cloud
     * @date 2025-11-18
     */
    @ApiOperation("删除代金券")
    @GetMapping("/deleteCoupon")
    public R<Boolean> deleteCoupon(@RequestParam("id") Integer id) {
        log.info("LifeCouponController.updateCouponSingleQty?id={}", id);
        if (lifeCouponService.deleteCoupon(id)) {
            return R.success("成功");
        }
        return R.fail("失败");
    }

    /**
     * 暂停或恢复优惠券
     * 修改优惠券的状态，实现上架、下架等操作
     *
     * @param id 优惠券ID
     * @param status 状态值
     * @return R<Boolean> 操作结果
     * @author alien-cloud
     * @date 2025-11-18
     */
    @ApiOperation("暂停恢复优惠券")
    @GetMapping("/updateCoupon")
    public R<Boolean> updateCoupon(@RequestParam("id") String id, @RequestParam("status") Integer status) {
        log.info("LifeCouponController.updateCoupon?id={}&status={}", id, status);
        if (lifeCouponService.updateCoupon(id, status) > 0) {
            return R.success("成功");
        }
        return R.fail("失败");
    }

    /**
     * 查询优惠券详情
     * 根据优惠券ID获取优惠券的详细信息
     *
     * @param id 优惠券ID
     * @return R<LifeCoupon> 优惠券详情
     * @author alien-cloud
     * @date 2025-11-18
     */
    @ApiOperation("优惠券详情")
    @GetMapping("/getCouponDetail")
    private R<LifeCoupon> getCouponDetail(@RequestParam("id") String id) {
        log.info("LifeCouponController.getCouponDetail?id={}", id);
        LambdaQueryWrapper<LifeCoupon> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(LifeCoupon::getId, id);
        LifeCoupon coupon = lifeCouponService.getOne(objectLambdaQueryWrapper);
        if (coupon.getSingleQty() == null || coupon.getSingleQty() == 0) {
            coupon.setSingleQty(null);
        }

        if ("0".equals(coupon.getSingleCanUse())) {
            coupon.setSingleCanUse(null);
        }

        if ("0".equals(coupon.getPurchaseLimitCode())) {
            coupon.setPurchaseLimitCode(null);
        }

        return R.data(coupon);
    }


    /**
     * 分页查询节假日列表
     * 支持按年份、开关状态、节假日名称筛选
     *
     * @param page 页码
     * @param size 每页数量
     * @param year 年份
     * @param openFlag 是否启用(0:未启用,1:已启用)
     * @param holidayName 节假日名称
     * @return R<IPage<EssentialHolidayComparison>> 分页节假日列表
     * @author alien-cloud
     * @date 2025-11-18
     */
    @ApiOperation("节假日列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "page", value = "页数", dataType = "Integer", paramType = "query", required = true), @ApiImplicitParam(name = "size", value = "页容", dataType = "Integer", paramType = "query", required = true), @ApiImplicitParam(name = "year", value = "年份", dataType = "String", paramType = "query", required = false), @ApiImplicitParam(name = "openFlag", value = "是否启用(0:未启用,1:已启用)", dataType = "String", paramType = "query", required = false), @ApiImplicitParam(name = "holidayName", value = "节假日名称", dataType = "String", paramType = "query", required = false)})
    @GetMapping("/getHolidayList")
    private R<IPage<EssentialHolidayComparison>> getHolidayList(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "size", defaultValue = "10") int size, @RequestParam("year") String year, @RequestParam("openFlag") String openFlag, @RequestParam("holidayName") String holidayName) {
        log.info("LifeCouponController.getHolidayList?page={},size={},year={},openFlag={},holidayName={}", page, size, year, openFlag, holidayName);
        return R.data(lifeCouponService.getHolidayList(page, size, year, openFlag, holidayName));
    }

    /**
     * 保存节假日信息
     * 新增或更新节假日配置
     *
     * @param essentialHolidayComparison 节假日对象
     * @return R<Boolean> 操作结果
     * @author alien-cloud
     * @date 2025-11-18
     */
    @ApiOperation("保存节假日")
    @PostMapping("/saveHoliday")
    public R<Boolean> saveHoliday(@RequestBody EssentialHolidayComparison essentialHolidayComparison) {
        log.info("LifeCouponController.saveHoliday?essentialHolidayComparison={}", essentialHolidayComparison.toString());
        if (lifeCouponService.saveHoliday(essentialHolidayComparison)) {
            return R.success("成功");
        }
        return R.fail("失败");
    }

    /**
     * 删除节假日
     * 根据ID删除指定的节假日配置
     *
     * @param id 节假日ID
     * @return R 操作结果
     * @author alien-cloud
     * @date 2025-11-18
     */
    @ApiOperation("删除节假日")
    @GetMapping("/delHoliday")
    private R delHoliday(@RequestParam("id") String id) {
        log.info("LifeCouponController.delHoliday?id={}", id);
        if (lifeCouponService.delHoliday(id)) {
            return R.success("成功");
        }
        return R.fail("失败");
    }

    /**
     * 启用或禁用节假日
     * 切换指定节假日的开关状态
     *
     * @param id 节假日ID
     * @return R 操作结果
     * @author alien-cloud
     * @date 2025-11-18
     */
    @ApiOperation("启用禁用节假日")
    @GetMapping("/openCloseHoliday")
    private R openCloseHoliday(@RequestParam("id") String id) {
        log.info("LifeCouponController.openCloseHoliday?id={}", id);
        if (lifeCouponService.openCloseHoliday(id)) {
            return R.success("成功");
        }
        return R.fail("失败");
    }

    /**
     * 按年份删除节假日
     * 删除指定年份的所有节假日配置
     *
     * @param year 年份
     * @return R 操作结果
     * @author alien-cloud
     * @date 2025-11-18
     */
    @ApiOperation("按年份删除节假日")
    @GetMapping("/delHolidayByYear")
    private R delHolidayByYear(@RequestParam("year") String year) {
        log.info("LifeCouponController.delHolidayByYear?year={}", year);
        if (lifeCouponService.delHolidayByYear(year)) {
            return R.success("成功");
        }
        return R.fail("失败");
    }

    /**
     * 查询代金券、优惠券列表
     * 根据条件查询列表
     *
     * @param lifeCouponPlatformVo 查询条件
     * @return R 操作结果
     * @author alien-cloud
     * @date 2025-11-18
     */
    @ApiOperation("代金劵/优惠券列表。discountCouponType=1仅满减券，discountCouponType=2仅折扣券，不传返回全部优惠券")
    @PostMapping("/getCouponList")
    private R<DiscountCouponPlatformVo> getCouponList(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo,
                                                      @RequestBody LifeCouponPlatformVo lifeCouponPlatformVo) {
        log.info("LifeCouponController.getCouponList?lifeCouponPlatformVo={}", lifeCouponPlatformVo);
        if (StringUtils.isBlank(lifeCouponPlatformVo.getStoreId())) {
            return R.data(null, "当前用户未入驻！！！");
        }
        DiscountCouponPlatformVo vo = new DiscountCouponPlatformVo();
        // couponType: 1=代金券，2=优惠券，null或其他=优惠券（默认）
        if (lifeCouponPlatformVo.getCouponType() != null && lifeCouponPlatformVo.getCouponType() == 1) {
            vo.setCouponList(lifeCouponService.getCouponListAsDiscountVo(lifeCouponPlatformVo.getPageNum(), lifeCouponPlatformVo.getPageSize(), lifeCouponPlatformVo.getStoreId(),
                    lifeCouponPlatformVo.getStatus(), lifeCouponPlatformVo.getName()));
        } else {
            vo.setDiscountList(lifeDiscountCouponPlatformService.getStoreAllCouponList(lifeCouponPlatformVo.getStoreId(), userLoginInfo,
                    lifeCouponPlatformVo.getPageNum(), lifeCouponPlatformVo.getPageSize(), lifeCouponPlatformVo.getName(), lifeCouponPlatformVo.getCouponsFromType(), lifeCouponPlatformVo.getCouponStatus(), lifeCouponPlatformVo.getDiscountCouponType()));
        }

        return R.data(vo);
    }

}

