package com.seer.teach.mall.good.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.ResultBean;
import com.seer.teach.common.annotation.LogPrint;
import com.seer.teach.common.enums.EntityDeleteFlagEnums;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.mall.convert.GoodConverter;
import com.seer.teach.mall.entity.GoodsEntity;
import com.seer.teach.mall.good.service.IAdminGoodsService;
import com.seer.teach.mall.request.GoodsReq;
import com.seer.teach.mall.response.GoodsResp;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  商家商品管理控制器
 * </p>
 *
 * @author 
 * @since 2025-06-12
 */
@RestController
@RequestMapping("/mall/merchant/goods")
@Tag(name = "商家端 - 商品管理")
@Validated
@RequiredArgsConstructor
@SaCheckLogin(type = StpUtil.TYPE)
public class MerchantGoodsController {

    private final IAdminGoodsService goodsService;

    /**
     * 商家商品分页列表
     */
    @Operation(summary = "商家商品分页查询")
    @GetMapping("/{size}/{current}")
    @SaCheckPermission("merchant:goods:page")
    public ResultBean<PageListBean<GoodsResp>> queryPageList(
            @Parameter(description = "每页数量") @PathVariable("size") Integer size,
            @Parameter(description = "第几页") @PathVariable("current") Integer current,
            @Parameter(description = "商品名称") @RequestParam(name="goodName", required = false) String goodName,
            @Parameter(description = "商品状态") @RequestParam(name="status", required = false) Integer status,
            @Parameter(description = "是否上架") @RequestParam(name="isOnSale", required = false) Integer isOnSale) {

        GoodsEntity goods = new GoodsEntity();
        goods.setName(goodName);
        goods.setStatus(status);
        goods.setIsOnSale(isOnSale);
        // 设置当前商户ID过滤条件
        goods.setMerchantUserId(StpUtil.getLoginIdAsLong());

        IPage<GoodsEntity> iPage = goodsService.queryPageList(size, current, goods);
        PageListBean<GoodsResp> result = PageConverterUtils.convertPageListBean(iPage, GoodConverter.INSTANCE::list);
        return ResultBean.success(result);
    }

    /**
     * 查看商品详情
     */
    @Operation(summary = "查看商品详情")
    @GetMapping("/{id}")
    @SaCheckPermission("merchant:goods:detail")
    public ResultBean<GoodsResp> detail(@Parameter(description = "商品id") @PathVariable("id") Integer id) {
        // 需要验证该商品属于当前商户
        GoodsResp goodsResp = goodsService.queryDetail(id);
        if (goodsResp != null && !goodsResp.getMerchantUserId().equals(StpUtil.getLoginIdAsLong())) {
            return ResultBean.error(ResultCodeEnum.MERCHANT_GOODS_PERMISSION_DENIED);
        }
        return ResultBean.success(goodsResp);
    }

    /**
     * 新增商品信息
     */
    @Operation(summary = "新增商品信息")
    @PostMapping("/save")
    @LogPrint
    @SaCheckPermission("merchant:goods:save")
    public ResultBean<Boolean> saveGoods(@RequestBody @Validated GoodsReq params) {
        params.setMerchantId(StpUtil.getLoginIdAsLong());
        return ResultBean.success(goodsService.saveGoods(params));
    }

    /**
     * 修改商品信息
     */
    @Operation(summary = "修改商品信息")
    @PutMapping("/{id}")
    @SaCheckPermission("merchant:goods:update")
    public ResultBean<Boolean> update(@Parameter(description = "商品id") @PathVariable("id") Integer id, @RequestBody GoodsReq goods) {
        // 验证商品权限
        GoodsResp goodsResp = goodsService.queryDetail(id);
        if (goodsResp != null && !goodsResp.getMerchantUserId().equals(StpUtil.getLoginIdAsInt())) {
            return ResultBean.error(ResultCodeEnum.MERCHANT_GOODS_UPDATE_DENIED);
        }
        return ResultBean.success(goodsService.update(id, goods));
    }

    /**
     * 修改商品基本信息
     */
    @Operation(summary = "修改商品基本信息")
    @PutMapping("/{id}/update-base-info")
    @SaCheckPermission("merchant:goods:update-base-info")
    public ResultBean<Boolean> updateBaseInfo(@Parameter(description = "商品id") @PathVariable("id") Integer id, @RequestBody GoodsReq goods) {
        // 验证商品权限
        GoodsResp goodsResp = goodsService.queryDetail(id);
        if (goodsResp != null && !goodsResp.getMerchantUserId().equals(StpUtil.getLoginIdAsInt())) {
            return ResultBean.error(ResultCodeEnum.MERCHANT_GOODS_UPDATE_DENIED);
        }
        return ResultBean.success(goodsService.updateBaseInfo(id, goods));
    }

    /**
     * 删除商品（逻辑删除）
     */
    @Operation(summary = "删除商品")
    @DeleteMapping
    @SaCheckPermission("merchant:goods:delete")
    public ResultBean<Integer> delete(@RequestBody List<Integer> ids) {
        // 验证商品权限
        if (!checkGoodsOwnership(ids)) {
            return ResultBean.error(ResultCodeEnum.MERCHANT_GOODS_DELETE_DENIED);
        }
        return ResultBean.success(goodsService.updateDeleteBatchByIds(EntityDeleteFlagEnums.DELETE_FLAG, ids));
    }

    /**
     * 商品回收站列表查询
     */
    @Operation(summary = "商品回收站列表查询")
    @GetMapping("/history/{size}/{current}")
    @SaCheckPermission("merchant:goods:history")
    public ResultBean<PageListBean<GoodsResp>> historyList(
            @Parameter(description = "每页数量") @PathVariable("size") Integer size,
            @Parameter(description = "第几页") @PathVariable("current") Integer current,
            @Parameter(description = "商品名称") @RequestParam("goodName") String goodName) {

        GoodsEntity goods = new GoodsEntity();
        goods.setDeleted(EntityDeleteFlagEnums.DELETE_FLAG.getCode());
        goods.setName(goodName);
        // 只查询当前商户的商品
        goods.setMerchantUserId(StpUtil.getLoginIdAsLong());

        IPage<GoodsEntity> iPage = goodsService.queryPageList(size, current, goods);
        PageListBean<GoodsResp> result = PageConverterUtils.convertPageListBean(iPage, GoodConverter.INSTANCE::list);
        return ResultBean.success(result);
    }

    /**
     * 商品从回收站恢复
     */
    @Operation(summary = "商品从回收站恢复")
    @PutMapping("/back")
    @SaCheckPermission("merchant:goods:back")
    public ResultBean<Boolean> back(@RequestBody List<Integer> ids) {
        // 验证商品权限
        if (!checkGoodsOwnership(ids)) {
            return ResultBean.error(ResultCodeEnum.MERCHANT_GOODS_RESTORE_DENIED);
        }
        return ResultBean.success(goodsService.back(ids));
    }

    /**
     * 上架商品
     */
    @Operation(summary = "上架商品")
    @PutMapping("/en-sale")
    @SaCheckPermission("merchant:goods:en-sale")
    public ResultBean<Boolean> enSale(@RequestBody List<Integer> ids) {
        // 验证商品权限
        if (!checkGoodsOwnership(ids)) {
            return ResultBean.error(ResultCodeEnum.MERCHANT_GOODS_EN_SALE_DENIED);
        }
        return ResultBean.success(goodsService.enSale(ids));
    }

    /**
     * 下架商品
     */
    @Operation(summary = "下架商品")
    @PutMapping("/un-sale")
    @SaCheckPermission("merchant:goods:un-sale")
    public ResultBean<Boolean> unSale(@RequestBody List<Integer> ids) {
        // 验证商品权限
        if (!checkGoodsOwnership(ids)) {
            return ResultBean.error(ResultCodeEnum.MERCHANT_GOODS_UN_SALE_DENIED);
        }
        return ResultBean.success(goodsService.unSale(ids));
    }

    /**
     * 检查商品是否属于当前商户
     */
    private boolean checkGoodsOwnership(List<Integer> goodsIds) {
        if (goodsIds == null || goodsIds.isEmpty()) {
            return true;
        }

        int merchantUserId = StpUtil.getLoginIdAsInt();
        List<GoodsEntity> goodsList = goodsService.listByIds(goodsIds);

        return goodsList.stream()
                .allMatch(goods -> goods.getMerchantUserId().equals(merchantUserId));
    }
}