package shop.alien.dining.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiSort;
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.vo.LifeDiscountCouponVo;
import shop.alien.dining.service.DiningCouponService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 点餐模块-优惠券控制器（Feign 调 store，供小程序：我的优惠券/详情/选券）
 *
 * @author ssk
 * @version 1.0
 * @date 2025/1/29
 */
@Slf4j
@Api(tags = {"微信点餐-优惠券(用户端)"})
@ApiSort(3)
@CrossOrigin
@RestController
@RequestMapping({"/dining/coupon"})
@RequiredArgsConstructor
public class DiningCouponController {

    private final DiningCouponService diningCouponService;

    /**
     * 获取该用户所有的优惠券列表
     */
    @ApiOperation("获取该用户所有的优惠券列表。couponType=1仅满减券，couponType=2仅折扣券，不传返回全部优惠券；storeKeyword 非空时仅返回门店名称包含关键字的优惠券")
    @ApiOperationSupport(order = 9)
    @GetMapping("/getUserCouponList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页页数", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "size", value = "分页条数", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "tabType", value = "分页类型（0：全部（未使用），1：即将过期，2：已使用，3：已过期/已失效）", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "type", value = "券类型（不传或1：优惠券；代金券 type=4 已下线）", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "couponType", value = "优惠券类型：1=仅满减券，2=仅折扣券，不传=全部优惠券（可选）", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "storeId", value = "商铺ID，可为空，传则仅返回该商铺的优惠券", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "storeKeyword", value = "店铺名称关键字，非空则只展示门店名称含关键字的优惠券（可选，最长100字符）", dataType = "String", paramType = "query", required = false)
    })
    public R<List<LifeDiscountCouponVo>> getUserCouponList(
            HttpServletRequest request,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam("tabType") String tabType,
            @RequestParam(value = "type", required = false) Integer type,
            @RequestParam(value = "couponType", required = false) Integer couponType,
            @RequestParam(value = "storeId", required = false) String storeId,
            @RequestParam(value = "storeKeyword", required = false) String storeKeyword) {
        String keywordParam = null;
        if (storeKeyword != null) {
            String t = storeKeyword.trim();
            if (!t.isEmpty()) {
                keywordParam = t.length() > 100 ? t.substring(0, 100) : t;
            }
        }
        log.info("DiningCouponController.getUserCouponList?page={}, size={}, tabType={}, type={}, couponType={}, storeId={}, storeKeyword={}", page, size, tabType, type, couponType, storeId, keywordParam);
        String authorization = request.getHeader("Authorization");
        return diningCouponService.getUserCouponList(authorization, page, size, tabType, type, couponType, storeId, keywordParam);
    }

    /**
     * 根据优惠券 id 获取优惠券详情（规则、门槛等）
     */
    @ApiOperation(value = "获取优惠券详情", notes = "需登录，请求头带 Authorization。counponId 与 store 接口拼写一致")
    @GetMapping("/detail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "counponId", value = "优惠券id", dataType = "String", paramType = "query", required = true)
    })
    public R<LifeDiscountCouponVo> getCounponDetailById(
            HttpServletRequest request,
            @RequestParam("counponId") String counponId) {
        log.info("DiningCouponController.getCounponDetailById?counponId={}", counponId);
        String authorization = request.getHeader("Authorization");
        return diningCouponService.getCounponDetailById(authorization, counponId);
    }

    /**
     * 获取该门店下用户可用/不可用优惠券列表（用于购物车/下单选券，按金额区分）
     */
    @ApiOperation(value = "获取门店可用优惠券列表", notes = "需登录。按 storeId+amount 返回可用券与不可用券及原因（满减门槛等）。couponType=1仅满减券，couponType=2仅折扣券，不传返回全部优惠券")
    @GetMapping("/storeUsableList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "amount", value = "当前消费金额（满减门槛）", dataType = "BigDecimal", paramType = "query", required = true),
            @ApiImplicitParam(name = "couponType", value = "优惠券类型：1=仅满减券，2=仅折扣券，不传=全部优惠券（可选）", dataType = "Integer", paramType = "query", required = false)
    })
    public R<Map<String, Object>> getStoreUserUsableCouponList(
            HttpServletRequest request,
            @RequestParam("storeId") String storeId,
            @RequestParam("amount") BigDecimal amount,
            @ApiParam(value = "优惠券类型：1=仅满减券，2=仅折扣券，不传=全部优惠券") @RequestParam(value = "couponType", required = false) Integer couponType) {
        log.info("DiningCouponController.getStoreUserUsableCouponList?storeId={}, amount={}, couponType={}", storeId, amount, couponType);
        String authorization = request.getHeader("Authorization");
        return diningCouponService.getStoreUserUsableCouponList(authorization, storeId, amount, couponType);
    }

    /**
     * 查询用户拥有的优惠券（按符合支付条件优先，其次优惠力度大的优先）
     */
    @ApiOperation(value = "查询用户拥有的优惠券", notes = "需登录。含商家逻辑删除模板（仍展示券属性）；每张用户券一行。可选 storeId。金额 amount 仅影响排序不参与过滤（建议传订单应付金额）；未传金额时按面值等规则排序。")
    @GetMapping("/userOwned")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店ID（可选，如果提供则只查询该门店的优惠券）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "amount", value = "当前消费金额（用于判断是否符合支付条件）", dataType = "BigDecimal", paramType = "query", required = false)
    })
    public R<List<LifeDiscountCouponVo>> getUserOwnedCoupons(
            @ApiParam(value = "门店ID（可选）") @RequestParam(required = false) String storeId,
            @ApiParam(value = "当前消费金额（可选，用于判断是否符合支付条件）") @RequestParam(required = false) BigDecimal amount) {
        log.info("DiningCouponController.getUserOwnedCoupons?storeId={}, amount={}", storeId, amount);
        return diningCouponService.getUserOwnedCoupons(storeId, amount);
    }

    /**
     * 获取该用户该店铺优惠券列表
     */
    @ApiOperation(value = "获取该用户该店铺优惠券列表", notes = "需登录，请求头带 Authorization。couponType=1仅满减券，couponType=2仅折扣券，不传返回全部优惠券")
    @ApiOperationSupport(order = 7)
    @GetMapping("/getStoreUserCouponList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "商户id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "couponType", value = "优惠券类型：1=仅满减券，2=仅折扣券，不传=全部优惠券（可选）", dataType = "Integer", paramType = "query", required = false)
    })
    public R<List<LifeDiscountCouponVo>> getStoreUserCouponList(
            HttpServletRequest request,
            @ApiParam(value = "商户id", required = true) @RequestParam("storeId") String storeId,
            @ApiParam(value = "优惠券类型：1=仅满减券，2=仅折扣券，不传=全部优惠券") @RequestParam(value = "couponType", required = false) Integer couponType) {
        log.info("DiningCouponController.getStoreUserCouponList?storeId={}, couponType={}", storeId, couponType);
        String authorization = request.getHeader("Authorization");
        return diningCouponService.getStoreUserCouponList(authorization, storeId, couponType);
    }

    /**
     * 查询用户目前所拥有的优惠券（可通过商铺ID进行查询）
     */
    @ApiOperation(value = "查询用户目前所拥有的优惠券", notes = "需登录。查询用户目前所拥有的优惠券（未使用且未过期），可通过商铺ID进行筛选。couponType=1仅满减券，couponType=2仅折扣券，不传返回全部优惠券")
    @ApiOperationSupport(order = 8)
    @GetMapping("/userOwnedByStore")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "商铺ID（可选，如果提供则只查询该商铺的优惠券）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "couponType", value = "优惠券类型：1=仅满减券，2=仅折扣券，不传=全部优惠券（可选）", dataType = "Integer", paramType = "query", required = false)
    })
    public R<List<LifeDiscountCouponVo>> getUserOwnedCouponsByStore(
            @ApiParam(value = "商铺ID（可选）") @RequestParam(required = false) String storeId,
            @ApiParam(value = "优惠券类型：1=仅满减券，2=仅折扣券，不传=全部优惠券") @RequestParam(value = "couponType", required = false) Integer couponType) {
        log.info("DiningCouponController.getUserOwnedCouponsByStore?storeId={}, couponType={}", storeId, couponType);
        return diningCouponService.getUserOwnedCouponsByStore(storeId, couponType);
    }

    /**
     * 获取该店铺所有优惠券（分页）, 好友优惠券
     */
    @ApiOperation(value = "获取该店铺所有优惠券（分页）", notes = "需登录，请求头带 Authorization。couponType=1仅满减券，couponType=2仅折扣券，不传返回全部优惠券。tab: 0:全部，1:进行中，2:已结束，3:草稿，4:未开始，5:已下架，6:已清库")
    @ApiOperationSupport(order = 10)
    @GetMapping("/getStoreAllCouponList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", dataType = "int", paramType = "query", required = false),
            @ApiImplicitParam(name = "size", value = "每页条数", dataType = "int", paramType = "query", required = false),
            @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:已结束，3:草稿，4:未开始，5:已下架，6:已清库)", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "couponsFromType", value = "查询类型(1:我的优惠券，2:好友的优惠券)", dataType = "int", paramType = "query", required = false),
            @ApiImplicitParam(name = "couponStatus", value = "优惠券状态(0:草稿，1:正式)", dataType = "int", paramType = "query", required = false),
            @ApiImplicitParam(name = "couponType", value = "优惠券类型：1=仅满减券，2=仅折扣券，不传=全部优惠券（可选）", dataType = "Integer", paramType = "query", required = false)
    })
    public R<IPage<LifeDiscountCouponVo>> getStoreAllCouponList(
            HttpServletRequest request,
            @ApiParam(value = "页码", defaultValue = "1") @RequestParam(value = "page", defaultValue = "1") int page,
            @ApiParam(value = "每页条数", defaultValue = "10") @RequestParam(value = "size", defaultValue = "10") int size,
            @ApiParam(value = "商户id", required = true) @RequestParam("storeId") String storeId,
            @ApiParam(value = "优惠券名称") @RequestParam(value = "couponName", required = false) String couponName,
            @ApiParam(value = "分页类型(0:全部，1:进行中，2:已结束，3:草稿，4:未开始，5:已下架，6:已清库)", required = true) @RequestParam("tab") String tab,
            @ApiParam(value = "查询类型(1:我的优惠券，2:好友的优惠券)", defaultValue = "1") @RequestParam(value = "couponsFromType", defaultValue = "1") int couponsFromType,
            @ApiParam(value = "优惠券状态(0:草稿，1:正式)", defaultValue = "1") @RequestParam(value = "couponStatus", defaultValue = "1", required = false) int couponStatus,
            @ApiParam(value = "优惠券类型：1=仅满减券，2=仅折扣券，不传=全部优惠券") @RequestParam(value = "couponType", required = false) Integer couponType) {
        log.info("DiningCouponController.getStoreAllCouponList?page={}, size={}, storeId={}, couponName={}, tab={}, couponsFromType={}, couponStatus={}, couponType={}", page, size, storeId, couponName, tab, couponsFromType, couponStatus, couponType);
        String authorization = request.getHeader("Authorization");
        return diningCouponService.getStoreAllCouponList(authorization, page, size, storeId, couponName, tab, couponsFromType, couponStatus, couponType);
    }
}
