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.TenantEnum;
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.GoodsAuditReq;
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

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


    private final IAdminGoodsService goodsService;

    /**
     * 分页列表
     */
    @Operation(summary = "分页查询")
    @GetMapping("/{size}/{current}")
    @SaCheckPermission("admin: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,
            @Parameter(description = "租户Id") @RequestParam(name="tenantId",required = false) String tenantId) {
        GoodsEntity goods = new GoodsEntity();
        goods.setName(goodName);
        goods.setStatus(status);
        goods.setIsOnSale(isOnSale);
        goods.setTenantId(tenantId);
        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("admin:goods:detail")
    public ResultBean<GoodsResp> detail(@Parameter(description = "商品id") @PathVariable("id") Integer id) {
        return ResultBean.success(goodsService.queryDetail(id));
    }

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

    /**
     * 修改
     */
    @Operation(summary = "修改")
    @PutMapping("/{id}")
    @SaCheckPermission("admin:goods:update")
    public ResultBean<Boolean> update(@Parameter(description = "商品id") @PathVariable("id") Integer id,@RequestBody GoodsReq goods) {
        return ResultBean.success(goodsService.update(id,goods));
    }

    /**
     * 修改基本信息
     */
    @Operation(summary = "修改基本信息")
    @PutMapping("/{id}/update-base-info")
    @SaCheckPermission("admin:goods:update-base-info")
    public ResultBean<Boolean> updateBaseInfo(@Parameter(description = "商品id") @PathVariable("id") Integer id,@RequestBody GoodsReq goods) {
        return ResultBean.success(goodsService.updateBaseInfo(id,goods));
    }

    /**
     * 删除，逻辑删除，删除后可以通过商品回收站恢复
     */
    @Operation(summary = "删除")
    @DeleteMapping
    @SaCheckPermission("admin:goods:delete")
    public ResultBean<Integer> delete(@RequestBody List<Integer> ids) {
        return ResultBean.success(goodsService.updateDeleteBatchByIds(EntityDeleteFlagEnums.DELETE_FLAG,ids));
    }

    /**
     * 商品回收站列表查询
     *
     * @param size
     * @return
     */
    @Operation(summary = "商品回收站列表查询")
    @GetMapping("/history/{size}/{current}")
    @SaCheckPermission("admin: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);
        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("admin:goods:back")
    public ResultBean<Boolean> back(@RequestBody List<Integer> ids) {
        return ResultBean.success(goodsService.back(ids));
    }

    /**
     * 上架
     */
    @Operation(summary = "上架")
    @PutMapping("/en-sale")
    @SaCheckPermission("admin:goods:en-sale")
    public ResultBean<Boolean> enSale(@RequestBody List<Integer> ids) {
        return ResultBean.success(goodsService.enSale(ids));
    }

    /**
     * 下架
     */
    @Operation(summary = "下架")
    @PutMapping("/un-sale")
    @SaCheckPermission("admin:goods:un-sale")
    public ResultBean<Boolean> unSale(@RequestBody List<Integer> ids) {
        return ResultBean.success(goodsService.unSale(ids));
    }

    /**
     * 审核商品
     */
    @Operation(summary = "审核商品")
    @PutMapping("/audit")
    @SaCheckPermission("admin:goods:audit")
    @LogPrint
    public ResultBean<Boolean> audit(@RequestBody @Validated GoodsAuditReq goodsAuditReq) {
        return ResultBean.success(goodsService.auditGoods(goodsAuditReq));
    }

    /**
     * 审核并上架商品
     */
    @Operation(summary = "审核并上架商品")
    @PutMapping("/audit-and-en-sale")
    @SaCheckPermission("admin:goods:audit:en-sale")
    @LogPrint
    public ResultBean<Boolean> auditAndEnSale(@RequestBody  @Validated GoodsAuditReq goodsAuditReq) {
        // 先执行审核操作
        boolean auditResult = goodsService.auditGoods(goodsAuditReq);
        if (auditResult && goodsAuditReq.getStatus() == 1) {
            // 如果审核通过，则自动上架商品
            return ResultBean.success(goodsService.enSale(goodsAuditReq.getIds()));
        }
        return ResultBean.success(false);
    }
}