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

import java.util.HashMap;
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.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.finance.dto.SellerWithdrawQuery;
import com.ruoyi.web.modules.finance.dto.SellerWithdrawSubmitDTO;
import com.ruoyi.web.modules.finance.service.IShopFundService;
import com.ruoyi.web.modules.store.constant.ShopConstants;

/**
 * 商家端提现管理
 */
@RestController
@RequestMapping("/agri/seller/finance/withdraw")
public class SellerWithdrawController extends BaseController
{
    @Autowired
    private IShopFundService shopFundService;

    @PreAuthorize("@ss.hasPermi('agri:seller:finance:withdraw:list')")
    @GetMapping("/list")
    public TableDataInfo list(SellerWithdrawQuery query)
    {
        startPage();
        return getDataTable(shopFundService.listSellerWithdraws(requireShopId(), query));
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:finance:withdraw:list')")
    @GetMapping("/balance")
    public AjaxResult balance()
    {
        Map<String, Object> data = new HashMap<>();
        data.put("availableBalance", shopFundService.getAvailableBalance(requireShopId()));
        return success(data);
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:finance:withdraw:submit')")
    @Log(title = "提现申请", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody SellerWithdrawSubmitDTO dto)
    {
        return success(shopFundService.submitWithdraw(requireShopId(), dto, getUsername()));
    }

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