package com.gxwebsoft.shop.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.shop.entity.ShopCouponApplyCate;
import com.gxwebsoft.shop.entity.ShopCouponApplyItem;
import com.gxwebsoft.shop.entity.ShopUserCoupon;
import com.gxwebsoft.shop.service.ShopCouponApplyCateService;
import com.gxwebsoft.shop.service.ShopCouponApplyItemService;
import com.gxwebsoft.shop.service.ShopCouponService;
import com.gxwebsoft.shop.entity.ShopCoupon;
import com.gxwebsoft.shop.param.ShopCouponParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.service.ShopUserCouponService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 优惠券控制器
 *
 * @author 科技小王子
 * @since 2025-08-11 23:51:24
 */
@Tag(name = "优惠券管理")
@RestController
@RequestMapping("/api/shop/shop-coupon")
public class ShopCouponController extends BaseController {
    @Resource
    private ShopCouponService shopCouponService;
    @Resource
    private ShopUserCouponService userCouponService;
    @Resource
    private ShopCouponService couponService;
    @Resource
    private ShopCouponApplyItemService couponApplyItemService;
    @Resource
    private ShopCouponApplyCateService couponApplyCateService;

    @Operation(summary = "可领取优惠券列表")
    @PostMapping("/list")
    public ApiResult<List<ShopCoupon>> page() {
        Integer uid = getLoginUserId();
        // 用户已经领取的优惠券
        List<ShopUserCoupon> userCouponList = userCouponService.userList(uid);
        List<Integer> hasTakeCouponIdList = new ArrayList<>();
        for (ShopUserCoupon userCoupon : userCouponList) {
            hasTakeCouponIdList.add(userCoupon.getCouponId());
        }
        LambdaQueryWrapper<ShopCoupon> queryWrapper = new LambdaQueryWrapper<>();
//        if (!hasTakeCouponIdList.isEmpty()) queryWrapper.notIn(Coupon::getCouponId, hasTakeCouponIdList);
        queryWrapper.eq(ShopCoupon::getStatus, 0);
        queryWrapper.apply("(expire_type = 0 OR (expire_type = 1 AND end_time > '"
                + DateUtil.date() + "'))");
        queryWrapper.orderByAsc(ShopCoupon::getSortNumber);
        List<ShopCoupon> couponList = couponService.list(queryWrapper);
        for (ShopCoupon coupon : couponList) {
            coupon.setCouponApplyItemList(couponApplyItemService.list(
                    new LambdaQueryWrapper<ShopCouponApplyItem>().eq(ShopCouponApplyItem::getCouponId, coupon.getId())
            ));
            coupon.setCouponApplyCateList(couponApplyCateService.list(
                    new LambdaQueryWrapper<ShopCouponApplyCate>().eq(ShopCouponApplyCate::getCouponId, coupon.getId())
            ));
            boolean hasTake = hasTakeCouponIdList.contains(coupon.getId());
            coupon.setHasTake(hasTake);
            if (hasTake) {
                int userUseNum = 0;
                List<ShopUserCoupon> userCouponList1 = userCouponService.list(
                        new LambdaQueryWrapper<ShopUserCoupon>()
                                .eq(ShopUserCoupon::getCouponId, coupon.getId())
                );
                coupon.setUserTakeNum(userCouponList1.size());
                for (ShopUserCoupon userCoupon : userCouponList1) {
                    if (userCoupon.getIsUse().equals(1)) userUseNum++;
                }
                coupon.setUserUseNum(userUseNum);
            }
        }
        return success(couponList);
    }


    @Operation(summary = "分页查询优惠券")
    @GetMapping("/page")
    public ApiResult<PageResult<ShopCoupon>> page(ShopCouponParam param) {
        // 使用关联查询
        return success(shopCouponService.pageRel(param));
    }

    @Operation(summary = "查询全部优惠券")
    @GetMapping()
    public ApiResult<List<ShopCoupon>> list(ShopCouponParam param) {
        // 使用关联查询
        return success(shopCouponService.listRel(param));
    }

    @Operation(summary = "根据id查询优惠券")
    @GetMapping("/{id}")
    public ApiResult<ShopCoupon> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(shopCouponService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('shop:shopCoupon:save')")
    @OperationLog
    @Operation(summary = "添加优惠券")
    @PostMapping()
    public ApiResult<?> save(@RequestBody ShopCoupon shopCoupon) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
            shopCoupon.setUserId(loginUser.getUserId());
        }
        if (shopCouponService.save(shopCoupon)) {
            if (shopCoupon.getCouponApplyCateList() != null && !shopCoupon.getCouponApplyCateList().isEmpty()) {
                for (ShopCouponApplyCate couponApplyCate : shopCoupon.getCouponApplyCateList()) {
                    couponApplyCate.setCouponId(shopCoupon.getId());
                }
                couponApplyCateService.saveBatch(shopCoupon.getCouponApplyCateList());
            }

            if (shopCoupon.getCouponApplyItemList() != null && !shopCoupon.getCouponApplyItemList().isEmpty()) {
                for (ShopCouponApplyItem couponApplyItem : shopCoupon.getCouponApplyItemList()) {
                    couponApplyItem.setCouponId(shopCoupon.getId());
                }
                couponApplyItemService.saveBatch(shopCoupon.getCouponApplyItemList());
            }
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:shopCoupon:update')")
    @OperationLog
    @Operation(summary = "修改优惠券")
    @PutMapping()
    public ApiResult<?> update(@RequestBody ShopCoupon shopCoupon) {
        if (shopCouponService.updateById(shopCoupon)) {
            couponApplyCateService.removeByCouponId(shopCoupon.getId());
            if (shopCoupon.getCouponApplyCateList() != null && !shopCoupon.getCouponApplyCateList().isEmpty()) {
                for (ShopCouponApplyCate couponApplyCate : shopCoupon.getCouponApplyCateList()) {
                    couponApplyCate.setCouponId(shopCoupon.getId());
                }
                couponApplyCateService.saveBatch(shopCoupon.getCouponApplyCateList());
            }

            couponApplyItemService.removeByCouponId(shopCoupon.getId());
            if (shopCoupon.getCouponApplyItemList() != null && !shopCoupon.getCouponApplyItemList().isEmpty()) {
                for (ShopCouponApplyItem couponApplyItem : shopCoupon.getCouponApplyItemList()) {
                    couponApplyItem.setCouponId(shopCoupon.getId());
                }
                couponApplyItemService.saveBatch(shopCoupon.getCouponApplyItemList());
            }
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:shopCoupon:remove')")
    @OperationLog
    @Operation(summary = "删除优惠券")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (shopCouponService.removeById(id)) {
            couponApplyCateService.removeByCouponId(id);
            couponApplyItemService.removeByCouponId(id);
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:shopCoupon:save')")
    @OperationLog
    @Operation(summary = "批量添加优惠券")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<ShopCoupon> list) {
        if (shopCouponService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:shopCoupon:update')")
    @OperationLog
    @Operation(summary = "批量修改优惠券")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<ShopCoupon> batchParam) {
        if (batchParam.update(shopCouponService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:shopCoupon:remove')")
    @OperationLog
    @Operation(summary = "批量删除优惠券")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (shopCouponService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
