package com.gxwebsoft.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.ShopSeckill;
import com.gxwebsoft.shop.entity.ShopSeckillOrder;
import com.gxwebsoft.shop.param.ShopSeckillParam;
import com.gxwebsoft.shop.service.ShopSeckillService;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.BatchParam;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 秒杀活动控制器
 *
 * @author 科技小王子
 * @since 2026-06-25
 */
@Tag(name = "秒杀管理")
@RestController
@RequestMapping("/api/shop/shopSeckill")
public class ShopSeckillController extends BaseController {

    @Resource
    private ShopSeckillService shopSeckillService;

    // ========== 管理端接口 ==========

    @Operation(summary = "分页查询秒杀活动")
    @GetMapping("/page")
    public ApiResult<PageResult<ShopSeckill>> page(ShopSeckillParam param) {
        return success(shopSeckillService.pageRel(param));
    }

    @Operation(summary = "查询全部秒杀活动")
    @GetMapping()
    public ApiResult<List<ShopSeckill>> list(ShopSeckillParam param) {
        return success(shopSeckillService.listRel(param));
    }

    @Operation(summary = "根据id查询秒杀活动")
    @GetMapping("/{id}")
    public ApiResult<ShopSeckill> get(@PathVariable("id") Integer id) {
        return success(shopSeckillService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('shop:shopSeckill:save')")
    @OperationLog
    @Operation(summary = "添加秒杀活动")
    @PostMapping()
    public ApiResult<?> save(@RequestBody @Valid ShopSeckill shopSeckill) {
        User loginUser = getLoginUser();
        if (loginUser != null) {
            shopSeckill.setUserId(loginUser.getUserId());
            shopSeckill.setTenantId(getTenantId());
        }
        // 新增时默认已售0
        shopSeckill.setSoldCount(0);
        if (shopSeckillService.save(shopSeckill)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:shopSeckill:update')")
    @OperationLog
    @Operation(summary = "修改秒杀活动")
    @PutMapping()
    public ApiResult<?> update(@RequestBody ShopSeckill shopSeckill) {
        if (shopSeckillService.updateById(shopSeckill)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:shopSeckill:remove')")
    @OperationLog
    @Operation(summary = "删除秒杀活动")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (shopSeckillService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:shopSeckill:save')")
    @OperationLog
    @Operation(summary = "批量添加秒杀活动")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<ShopSeckill> list) {
        if (shopSeckillService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

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

    // ========== 用户端接口（小程序调用）==========

    @Operation(summary = "创建秒杀订单")
    @PostMapping("/createOrder")
    public ApiResult<ShopSeckillOrder> createOrder(@RequestBody Map<String, Object> params) {
        User loginUser = getLoginUser();
        if (loginUser == null) {
            return fail("请先登录", null);
        }

        Integer seckillId = (Integer) params.get("seckillId");
        Integer goodsId = (Integer) params.get("goodsId");
        Integer skuId = params.get("skuId") != null ? (Integer) params.get("skuId") : 0;
        Integer quantity = params.get("quantity") != null ? (Integer) params.get("quantity") : 1;

        try {
            ShopSeckillOrder order = shopSeckillService.createSeckillOrder(
                    seckillId, goodsId, skuId, quantity,
                    loginUser.getUserId(), getTenantId()
            );
            return success(order);
        } catch (Exception e) {
            return fail(e.getMessage(), null);
        }
    }

    @Operation(summary = "我的秒杀订单")
    @PostMapping("/myOrders")
    public ApiResult<PageResult<ShopSeckillOrder>> myOrders(@RequestBody Map<String, Object> params) {
        User loginUser = getLoginUser();
        if (loginUser == null) {
            return fail("请先登录", null);
        }

        Integer page = params.get("page") != null ? (Integer) params.get("page") : 1;
        Integer pageSize = params.get("pageSize") != null ? (Integer) params.get("pageSize") : 10;

        return success(shopSeckillService.mySeckillOrders(loginUser.getUserId(), page, pageSize));
    }

    @Operation(summary = "获取秒杀时间段（场次）")
    @PostMapping("/timeSlots")
    public ApiResult<List<Map<String, Object>>> timeSlots() {
        return success(shopSeckillService.getSeckillTimeSlots());
    }

}
