
package com.tmerclub.cloud.coupon.controller.admin;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.coupon.constant.PutOnStatus;
import com.tmerclub.cloud.api.platform.dto.OfflineHandleEventDTO;
import com.tmerclub.cloud.api.platform.vo.OfflineHandleEventVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.constant.StatusEnum;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.coupon.constant.CouponStatus;
import com.tmerclub.cloud.coupon.constant.GetWay;
import com.tmerclub.cloud.coupon.dto.CouponDTO;
import com.tmerclub.cloud.coupon.dto.CouponUserDTO;
import com.tmerclub.cloud.coupon.dto.UserCouponsDTO;
import com.tmerclub.cloud.coupon.manager.CouponStockManager;
import com.tmerclub.cloud.coupon.model.Coupon;
import com.tmerclub.cloud.coupon.service.CouponService;
import com.tmerclub.cloud.coupon.service.CouponUserService;
import com.tmerclub.cloud.coupon.vo.CouponVO;
import com.tmerclub.cloud.coupon.vo.mongo.MongoCouponUserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 优惠券
 * @author YXF
 */
@RestController("adminCouponController")
@RequestMapping("/mp/coupon")
@Tag(name = "admin-优惠券")
public class CouponController {

    @Autowired
    private CouponService couponService;
    @Autowired
    private CouponUserService couponUserService;
    @Autowired
    private CouponStockManager couponStockManager;

    @GetMapping("/platformPage")
    @Operation(summary = "店铺优惠券管理列表", description = "店铺优惠券管理列表")
    public ServerResponseEntity<PageVO<CouponVO>> platformPage(@Valid PageDTO pageDTO, CouponDTO couponDTO) {
        PageVO<CouponVO> couponPage = couponService.adminPage(pageDTO, couponDTO);
        return ServerResponseEntity.success(couponPage);
    }

    @GetMapping("/page")
    @Operation(summary = "获取优惠券列表", description = "分页获取优惠券列表")
    public ServerResponseEntity<PageVO<CouponVO>> page(@Valid PageDTO pageDTO, CouponDTO couponDTO) {
        couponDTO.setShopId(AuthUserContext.get().getTenantId());
        PageVO<CouponVO> couponPage = couponService.page(pageDTO, couponDTO);
        return ServerResponseEntity.success(couponPage);
    }


    @GetMapping("/shopCouponUserPage")
    @Operation(summary = "获取某个用户的优惠券明细", description = "获取某个用户的优惠券明细")
    public ServerResponseEntity<PageVO<MongoCouponUserVO>> shopCouponUserPage(@Valid PageDTO pageDTO, CouponUserDTO couponUserDTO) {
        couponUserDTO.setShopId(AuthUserContext.get().getTenantId());
        PageVO<MongoCouponUserVO> couponPage = couponUserService.getPageByUserId(pageDTO, couponUserDTO);
        return ServerResponseEntity.success(couponPage);
    }

    @GetMapping
    @Operation(summary = "获取优惠券", description = "根据couponId获取优惠券")
    public ServerResponseEntity<CouponVO> getByCouponId(@RequestParam Long couponId) {
        CouponVO coupon = couponService.getCouponAndCouponProdsByCouponId(couponId);
        if (Objects.equals(coupon.getStatus(), CouponStatus.NO_OVERDUE.value()) && Objects.equals(coupon.getPutonStatus(), PutOnStatus.PUT_ON.value())) {
            // 正在投放的优惠券的库存
            Integer stock = couponStockManager.getStockByCouponId(coupon.getCouponId());
            coupon.setStocks(stock);
        }
        return ServerResponseEntity.success(coupon);
    }

    @PostMapping
    @Operation(summary = "保存优惠券", description = "保存优惠券")
    public ServerResponseEntity<Void> save(@Valid @RequestBody CouponDTO couponDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        couponDTO.setShopId(shopId);
        couponService.save(couponDTO);
        couponService.removeCacheByShopId(AuthUserContext.get().getTenantId(), null);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "更新优惠券", description = "更新优惠券")
    public ServerResponseEntity<Void> update(@Valid @RequestBody CouponDTO couponDTO) {
        couponService.update(couponDTO);
        couponService.removeCacheByShopId(AuthUserContext.get().getTenantId(), couponDTO.getCouponId());
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除优惠券", description = "根据优惠券id删除优惠券")
    public ServerResponseEntity<Void> delete(@RequestParam Long couponId) {
        // 删除前先校验优惠券是否被用户领取但未使用
        long couponCount = couponUserService.countUnUseCoupon(couponId);
        if (couponCount != 0L) {
            throw new LuckException("该优惠券存在暂未使用的用户，禁止删除");
        }
        couponService.deleteById(couponId);
        couponService.removeCacheByShopId(AuthUserContext.get().getTenantId(), couponId);
        return ServerResponseEntity.success();
    }


    @GetMapping("/platformCouponsPage")
    @Operation(summary = "分页获取平台优惠券列表", description = "分页获取平台优惠券列表")
    public ServerResponseEntity<PageVO<CouponVO>> platformCouponsPage(@Valid PageDTO pageDTO, CouponDTO couponDTO) {
        couponDTO.setShopId(Constant.PLATFORM_SHOP_ID);
        couponDTO.setStatus(StatusEnum.ENABLE.value());
        couponDTO.setPutonStatus(StatusEnum.ENABLE.value());
        couponDTO.setGetWay(GetWay.PLATFORM.value());
        PageVO<CouponVO> couponPage = couponService.page(pageDTO, couponDTO);
        return ServerResponseEntity.success(couponPage);
    }

    @PutMapping("/sendUserCoupon")
    @Operation(summary = "批量发放优惠券", description = "平台批量发放优惠券给用户")
    public ServerResponseEntity<Boolean> sendUserCoupon(@RequestBody UserCouponsDTO userCouponsDTO) {
        List<Long> userIds = userCouponsDTO.getUserIds();
        if (CollUtil.isEmpty(userIds)) {
            return ServerResponseEntity.success();
        }
        List<UserCouponsDTO.SendCoupon> coupons = userCouponsDTO.getSendCoupons();
        if (CollUtil.isEmpty(coupons)) {
            return ServerResponseEntity.success();
        }
        for (Long userId : userIds) {
            for (UserCouponsDTO.SendCoupon coupon : coupons) {
                Long couponId = coupon.getCouponId();
                Integer nums = coupon.getNums();
                if (Objects.equals(0, nums)) {
                    continue;
                }
                for (int i = 0; i < nums; i++) {
                    couponService.batchBindCouponByCouponIds(Collections.singletonList(couponId), userId);
                }
            }
        }
        return ServerResponseEntity.success();
    }


    @PostMapping("/offline")
    @Operation(summary = "下线优惠券", description = "下线优惠券")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEventDTO offlineHandleEventDto) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        Coupon coupon = couponService.getByCouponId(offlineHandleEventDto.getHandleId());
        if (Objects.isNull(coupon)) {
            throw new LuckException(ResponseEnum.DATA_ERROR);
        }
        offlineHandleEventDto.setShopId(coupon.getShopId());
        couponService.offline(offlineHandleEventDto);
        // 清除缓存
        couponService.removeCacheByShopId(coupon.getShopId(), coupon.getCouponId());
        return ServerResponseEntity.success();
    }

    @GetMapping("/getOfflineHandleEvent/{couponId}")
    @Operation(summary = "获取最新下线的事件", description = "获取最新下线的事件")
    public ServerResponseEntity<OfflineHandleEventVO> getOfflineHandleEvent(@PathVariable Long couponId) {
        return ServerResponseEntity.success(couponService.getOfflineHandleEvent(couponId));
    }

    @PostMapping("/audit")
    @Operation(summary = "审核活动", description = "审核活动")
    public ServerResponseEntity<Void> audit(@RequestBody OfflineHandleEventDTO offlineHandleEventDto) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        Coupon coupon = couponService.getByCouponId(offlineHandleEventDto.getHandleId());
        couponService.audit(offlineHandleEventDto, coupon);
        // 清除缓存
        couponService.removeCacheByShopId(coupon.getShopId(), coupon.getCouponId());
        return ServerResponseEntity.success();
    }

    @PostMapping("/auditApply")
    @Operation(summary = "违规活动提交审核", description = "违规活动提交审核")
    public ServerResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventDTO offlineHandleEventDto) {
        couponService.auditApply(offlineHandleEventDto);
        return ServerResponseEntity.success();
    }

}
