package com.ruoyi.web.modules.stock.controller;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.category.support.SellerShopContext;
import com.ruoyi.web.modules.stock.dto.StockAdjustCreateDTO;
import com.ruoyi.web.modules.stock.dto.StockAdjustQuery;
import com.ruoyi.web.modules.stock.dto.StockAdjustRecordQuery;
import com.ruoyi.web.modules.stock.service.IStockAdjustService;
import com.ruoyi.web.modules.stock.vo.StockAdjustRecordRowVO;
import com.ruoyi.web.modules.store.constant.ShopConstants;

/**
 * 商家端库存调整
 */
@RestController
@RequestMapping("/agri/seller/stock/adjust")
public class SellerStockAdjustController extends BaseController
{
    @Autowired
    private IStockAdjustService stockAdjustService;

    @PreAuthorize("@ss.hasPermi('agri:seller:stock:adjust:list')")
    @GetMapping("/list")
    public TableDataInfo list(StockAdjustQuery query)
    {
        startPage();
        return getDataTable(stockAdjustService.selectList(requireShopId(), query));
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:stock:adjust:edit')")
    @Log(title = "库存调整", businessType = BusinessType.UPDATE)
    @PostMapping("/{goodsId}")
    public AjaxResult adjust(@PathVariable("goodsId") Long goodsId, @RequestBody StockAdjustCreateDTO dto)
    {
        Map<String, Object> data = stockAdjustService.confirmAdjust(requireShopId(), goodsId, dto, getUserId(),
                getUsername());
        return success(data);
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:stock:adjust:list')")
    @GetMapping("/{goodsId}/records")
    public AjaxResult records(@PathVariable("goodsId") Long goodsId, StockAdjustRecordQuery query)
    {
        List<StockAdjustRecordRowVO> rows = stockAdjustService.listRecords(requireShopId(), goodsId, query);
        return success(rows);
    }

    private Long requireShopId()
    {
        Long shopId = SellerShopContext.getShopId();
        if (shopId == null || shopId <= 0)
        {
            throw new ServiceException(ShopConstants.MSG_SHOP_CONTEXT_REQUIRED);
        }
        return shopId;
    }
}
