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

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.PutMapping;
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.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.category.support.SellerShopContext;
import com.ruoyi.web.modules.pay.dto.ShopWechatPaySaveDTO;
import com.ruoyi.web.modules.pay.service.IShopWechatPayService;
import com.ruoyi.web.modules.store.constant.ShopConstants;
import com.ruoyi.web.modules.store.domain.BizShop;
import com.ruoyi.web.modules.store.mapper.BizShopMapper;

/**
 * 商家端 · 微信支付入驻
 */
@RestController
@RequestMapping("/agri/seller/wechat-pay")
public class SellerShopWechatPayController extends BaseController
{
    @Autowired
    private IShopWechatPayService shopWechatPayService;

    @Autowired
    private BizShopMapper shopMapper;

    @PreAuthorize("@ss.hasPermi('agri:seller:wechatPay:query')")
    @GetMapping
    public AjaxResult getApply()
    {
        return success(shopWechatPayService.getByShopId(requireShopId()));
    }

    @PreAuthorize("@ss.hasPermi('agri:seller:wechatPay:edit')")
    @Log(title = "微信支付入驻", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult submitApply(@RequestBody ShopWechatPaySaveDTO dto)
    {
        Long shopId = requireShopId();
        BizShop shop = shopMapper.selectById(shopId);
        if (shop == null)
        {
            throw new ServiceException("店铺不存在");
        }
        shopWechatPayService.submitApply(shopId, shop.getMerchantId(), dto, getUsername());
        return success();
    }

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