package shop.alien.store.controller;

import com.alibaba.fastjson.JSONObject;
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.LifeDiscountCouponFriendRule;
import shop.alien.entity.store.UserLoginInfo;
import shop.alien.entity.store.dto.LifeDiscountCouponStoreFriendDto;
import shop.alien.entity.store.vo.LifeDiscountCouponFriendRuleDetailVo;
import shop.alien.entity.store.vo.LifeDiscountCouponFriendRuleVo;
import shop.alien.entity.store.vo.LifeDiscountCouponStoreFriendVo;
import shop.alien.store.annotation.TrackEvent;
import shop.alien.store.service.LifeDiscountCouponStoreFriendService;
import shop.alien.util.common.TokenInfo;
import springfox.documentation.annotations.ApiIgnore;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 商户间好友优惠券：设置可向好友发的券、赠券、以及赠券记录/规则等。
 *
 * @author ssk
 * @since 2025-02-19
 */
@Api(tags = {"二期-优惠券商户发放好友优惠券关系表"})
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/life-discount-coupon-store-friend")
@RequiredArgsConstructor
public class LifeDiscountCouponStoreFriendController {

    private final LifeDiscountCouponStoreFriendService lifeDiscountCouponStoreFriendService;

    @ApiOperation("获取该店铺的好友及其可用优惠券列表")
    @ApiOperationSupport(order = 1)
    @GetMapping("/getFriendCouponList")
    public R<List<LifeDiscountCouponStoreFriendVo>> getFriendCouponList(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo, @RequestParam(value = "friendUserId", required = false) String friendUserId) {
        log.info("LifeDiscountCouponStoreFriendController.getFriendCouponList");
        try {
            return R.data(lifeDiscountCouponStoreFriendService.getFriendCouponList(userLoginInfo, friendUserId));
        } catch (Exception e) {
            log.error("LifeDiscountCouponStoreFriendController.getFriendCouponList ERROR Msg={}", e.getMessage());
            return R.fail("查询失败");
        }
    }

    @TrackEvent(
            eventType = "COUPON_GIVE",
            eventCategory = "COUPON",
            storeId = "#{#lifeDiscountCouponStoreFriendDto.storeId}",
            targetType = "COUPON"
    )
    @ApiOperation(value = "向好友店铺赠送优惠券", notes = "校验库存后扣减 life_discount_coupon；新增或合并 life_discount_coupon_store_friend。"
            + " 领取后有效天数、长期有效、活动起止等均以服务端按 couponId 查询模板为准，请求中勿传有效期字段（传入也会被忽略）。")
    @ApiOperationSupport(order = 2)
    @PostMapping("/setFriendCoupon")
    public R<Boolean> setFriendCoupon(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo, @RequestBody LifeDiscountCouponStoreFriendDto lifeDiscountCouponStoreFriendDto) {
        log.info("LifeDiscountCouponStoreFriendController.setFriendCoupon?lifeDiscountCouponStoreFriendDto={}", lifeDiscountCouponStoreFriendDto.toString());
        try {
            boolean save = lifeDiscountCouponStoreFriendService.setFriendCoupon(userLoginInfo, lifeDiscountCouponStoreFriendDto);
            if (!save) {
                return R.fail("设置失败");
            }
        } catch (Exception e) {
            log.error("LifeDiscountCouponStoreFriendController.setFriendCoupon ERROR Msg={}", e.getMessage());
            return R.fail("设置失败");
        }
        return R.success("设置成功");
    }

    @ApiOperation("消费后发放好友优惠券并返回列表")
    @ApiOperationSupport(order = 2)
    @PostMapping("/issueFriendCoupon")
    public R<List<LifeDiscountCouponStoreFriendVo>> issueFriendCoupon(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo, @RequestBody LifeDiscountCouponStoreFriendDto lifeDiscountCouponStoreFriendDto) {
        log.info("LifeDiscountCouponStoreFriendController.issueFriendCoupon?lifeDiscountCoupon={}", lifeDiscountCouponStoreFriendDto.toString());
        try {
            List<LifeDiscountCouponStoreFriendVo> lifeDiscountCouponStoreFriendVos =
                    lifeDiscountCouponStoreFriendService.issueFriendCoupon(lifeDiscountCouponStoreFriendDto);
            return R.data(lifeDiscountCouponStoreFriendVos);
        } catch (Exception e) {
            log.error("LifeDiscountCouponStoreFriendController.issueFriendCoupon ERROR Msg={}", e.getMessage());
            return R.fail("发放失败");
        }
    }

    @ApiOperation("查询该订单发放优惠券列表")
    @ApiOperationSupport(order = 2)
    @PostMapping("/getSendCoupons")
    public R<List<LifeDiscountCouponStoreFriendVo>> getSendCoupons(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo, @RequestBody LifeDiscountCouponStoreFriendDto lifeDiscountCouponStoreFriendDto) {
        log.info("LifeDiscountCouponStoreFriendController.getSendCoupons?lifeDiscountCouponStoreFriendDto={}", lifeDiscountCouponStoreFriendDto.toString());
        try {
            List<LifeDiscountCouponStoreFriendVo> lifeDiscountCouponStoreFriendVos =
                    lifeDiscountCouponStoreFriendService.getSendCoupons(lifeDiscountCouponStoreFriendDto);
            return R.data(lifeDiscountCouponStoreFriendVos);
        } catch (Exception e) {
            log.error("LifeDiscountCouponStoreFriendController.getSendCoupons ERROR Msg={}", e.getMessage());
            return R.fail("发放失败");
        }
    }

    @ApiOperation("发布/取消发布好友商家优惠券")
    @ApiOperationSupport(order = 2)
    @PostMapping("/releaseAndCancelFriendStoreCoupon")
    public R<Boolean> publish(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo, @RequestBody Map<String, String> friendStoreMap) {
        log.info("LifeDiscountCouponStoreFriendController.publish?friendStoreMap={}", JSONObject.toJSONString(friendStoreMap));
        int num = lifeDiscountCouponStoreFriendService.releaseAndCancelFriendStoreCoupon(friendStoreMap.get("giveCouponId"), friendStoreMap.get("releaseType"));
        if (num == 0) {
            return R.fail("操作失败");
        }
        return R.success("操作成功");
    }

    @ApiOperation("删除好友优惠券")
    @ApiOperationSupport(order = 2)
    @DeleteMapping("/deleteLifeDiscountCouponStoreFriend/{id}")
    public R<Boolean> deleteDiscountCoupon(@PathVariable("id") Integer id) {
        log.info("LifeDiscountCouponStoreFriendController.deleteLifeDiscountCouponStoreFriend?id={}", id);
        if (lifeDiscountCouponStoreFriendService.removeById(id)) {
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }

    @ApiOperation("保存好友赠券规则")
    @PostMapping("/saveFriendCouponRule")
    public R<LifeDiscountCouponFriendRuleVo> saveFriendCouponRule(@RequestBody LifeDiscountCouponFriendRule lifeDiscountCouponFriendRule) {
        log.info("LifeDiscountCouponStoreFriendController.saveFriendCouponRule?lifeDiscountCouponFriendRule={}", lifeDiscountCouponFriendRule.toString());
        try {
            LifeDiscountCouponFriendRuleVo lifeDiscountCouponFriendRuleVo = lifeDiscountCouponStoreFriendService.saveFriendCouponRule(lifeDiscountCouponFriendRule);
            return R.data(lifeDiscountCouponFriendRuleVo, "保存成功");
        } catch (Exception e) {
            log.error("LifeDiscountCouponStoreFriendController.saveFriendCouponRule ERROR Msg={}", e.getMessage());
            return R.fail("保存失败");
        }
    }

    @ApiOperation("删除赠券规则")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "id", dataType = "String", paramType = "query", required = true)
    })
    @GetMapping("/delFriendCouponRule")
    public R delFriendCouponRule(@RequestParam(value = "id") String id) {
        log.info("LifeDiscountCouponStoreFriendController.delFriendCouponRule?id={}", id);
        lifeDiscountCouponStoreFriendService.delFriendCouponRule(id);
        return R.success("删除成功");
    }

    @ApiOperation("查询赠券规则明细")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "id", dataType = "String", paramType = "query", required = true)
    })
    @GetMapping("/getRuleById")
    public R<LifeDiscountCouponFriendRuleVo> getRuleById(@RequestParam(value = "id") String id) {
        log.info("LifeDiscountCouponStoreFriendController.getRuleById?id={}", id);
        return R.data(lifeDiscountCouponStoreFriendService.getRuleById(id));
    }

    @ApiOperation("获取收到的好友优惠券列表（仅优惠券模板）。条件对齐 receiver_store_id；按赠送方分组时依赖 sender_user_id。type=4 返回空；couponType 筛选满减/折扣。")
    @GetMapping("/getReceivedFriendCouponList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "当前接收方店铺 store_info.id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "friendStoreUserId", value = "可选，筛选指定赠送方商户 store_user.id", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "type", value = "传 4 返回空（历史参数）", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "couponType", value = "1=满减，2=折扣，不传=全部", dataType = "Integer", paramType = "query", required = false)
    })
    public R<List<LifeDiscountCouponFriendRuleDetailVo>> getReceivedFriendCouponList(@RequestParam(value = "storeId") String storeId,
                                                                                     @RequestParam(value = "friendStoreUserId", required = false) String friendStoreUserId,
                                                                                     @RequestParam(value = "type", required = false) Integer type,
                                                                                     @RequestParam(value = "couponType", required = false) Integer couponType) {
        log.info("LifeDiscountCouponStoreFriendController.getReceivedFriendCouponList?storeId={},friendStoreUserId={},type={},couponType={}", storeId, friendStoreUserId, type, couponType);
        return R.data(lifeDiscountCouponStoreFriendService.getReceivedFriendCouponList(storeId, friendStoreUserId, type, couponType));
    }

    @ApiOperation("查询赠券规则")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "当前登录店铺id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "acName", value = "活动名称（模糊查询，可选）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "status", value = "状态：0-启用，1-禁用（可选）", dataType = "String", paramType = "query", required = false)
    })
    @GetMapping("/getRuleList")
    public R<List<LifeDiscountCouponFriendRuleVo>> getRuleList(@RequestParam(value = "storeId") String storeId,
                                                                @RequestParam(value = "acName", required = false) String acName,
                                                                @RequestParam(value = "status", required = false) String status) {
        log.info("LifeDiscountCouponStoreFriendController.getRuleList?storeId={},acName={},status={}", storeId, acName, status);
        try {
            if (StringUtils.isEmpty(storeId)) {
                return R.fail("店铺ID不能为空");
            }
            return R.data(lifeDiscountCouponStoreFriendService.getRuleList(storeId, acName, status));
        } catch (Exception e) {
            log.error("LifeDiscountCouponStoreFriendController.getRuleList ERROR Msg={}", e.getMessage(), e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "赠券历史列表（商户↔商户）", notes = "按当前登录商户查询好友间赠送记录。"
            + " queryType=1：我收到的，展示对方赠送方店铺；queryType=2：我送出的，展示对方接收方店铺。"
            + " 返回含券名称、面额、expirationDate、longTermValid 等；模板已逻辑删除时仍补全展示。type=4 时返回空列表（兼容旧客户端）。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeUserId", value = "当前登录商户 store_user.id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "queryType", value = "1=我收到的，2=我送出的", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeName", value = "对方店铺名称模糊筛选（可选）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "type", value = "传 4 返回空（历史参数）", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "couponType", value = "1=仅满减，2=仅折扣，不传=全部", dataType = "Integer", paramType = "query", required = false)
    })
    @GetMapping("/getReceivedSendFriendCouponList")
    public R<List<LifeDiscountCouponFriendRuleVo>> getReceivedSendFriendCouponList(@RequestParam(value = "storeUserId") String storeUserId,
                                                                                   @RequestParam(value = "queryType") Integer queryType,
                                                                                   @RequestParam(value = "storeName", required = false) String storeName,
                                                                                   @RequestParam(value = "type", required = false) Integer type,
                                                                                   @RequestParam(value = "couponType", required = false) Integer couponType) {
        log.info("LifeDiscountCouponStoreFriendController.getReceivedSendFriendCouponList?storeUserId={},queryType={},storeName={},type={},couponType={}", storeUserId, queryType, storeName, type, couponType);
        return R.data(lifeDiscountCouponStoreFriendService.getReceivedSendFriendCouponList(storeUserId, queryType, storeName, type, couponType));
    }
}
