package com.ruoyi.web.modules.pay.service.impl;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.pay.config.WeChatPayProperties;
import com.ruoyi.web.modules.pay.constant.PayConstants;
import com.ruoyi.web.modules.pay.domain.BizShopWechatPay;
import com.ruoyi.web.modules.pay.dto.ShopWechatPayAuditRejectDTO;
import com.ruoyi.web.modules.pay.dto.ShopWechatPayPlatformQuery;
import com.ruoyi.web.modules.pay.dto.ShopWechatPaySaveDTO;
import com.ruoyi.web.modules.pay.mapper.BizShopWechatPayMapper;
import com.ruoyi.web.modules.pay.service.IShopWechatPayService;
import com.ruoyi.web.modules.pay.vo.ShopWechatPayPlatformVO;
import com.ruoyi.web.modules.pay.vo.ShopWechatPayVO;

@Service
public class ShopWechatPayServiceImpl implements IShopWechatPayService
{
    @Autowired
    private BizShopWechatPayMapper shopWechatPayMapper;

    @Autowired
    private WeChatPayProperties payProperties;

    @Override
    public ShopWechatPayVO getByShopId(Long shopId)
    {
        BizShopWechatPay row = shopWechatPayMapper.selectByShopId(shopId);
        if (row == null)
        {
            ShopWechatPayVO vo = new ShopWechatPayVO();
            vo.setShopId(shopId);
            vo.setApplyStatus(PayConstants.APPLY_NOT_SUBMITTED);
            vo.setApplyStatusLabel("未申请");
            vo.setPayMode(PayConstants.PAY_MODE_PLATFORM);
            vo.setPayModeLabel("平台代收");
            vo.setEnabled("0");
            return vo;
        }
        return toVo(row);
    }

    @Override
    public void submitApply(Long shopId, Long merchantId, ShopWechatPaySaveDTO dto, String operator)
    {
        validateApply(dto);
        Date now = new Date();
        BizShopWechatPay existing = shopWechatPayMapper.selectByShopId(shopId);
        BizShopWechatPay row = new BizShopWechatPay();
        row.setShopId(shopId);
        row.setMerchantId(merchantId);
        row.setApplyStatus(PayConstants.APPLY_PENDING);
        row.setPayMode(StringUtils.isEmpty(dto.getPayMode()) ? PayConstants.PAY_MODE_PLATFORM : dto.getPayMode());
        row.setMchId(dto.getMchId() == null ? "" : dto.getMchId().trim());
        row.setSubMchId(dto.getSubMchId() == null ? "" : dto.getSubMchId().trim());
        row.setCompanyName(StringUtils.trim(dto.getCompanyName()));
        row.setLegalPerson(StringUtils.trim(dto.getLegalPerson()));
        row.setLicenseNo(StringUtils.trim(dto.getLicenseNo()));
        row.setContactName(StringUtils.trim(dto.getContactName()));
        row.setContactMobile(StringUtils.trim(dto.getContactMobile()));
        row.setBankName(dto.getBankName() == null ? "" : dto.getBankName().trim());
        row.setBankAccountName(dto.getBankAccountName() == null ? "" : dto.getBankAccountName().trim());
        row.setBankAccountNo(dto.getBankAccountNo() == null ? "" : dto.getBankAccountNo().trim());
        row.setEnabled("0");
        row.setUpdateBy(operator);
        row.setUpdateTime(now);
        if (existing == null)
        {
            row.setCreateBy(operator);
            row.setCreateTime(now);
            shopWechatPayMapper.insert(row);
            return;
        }
        shopWechatPayMapper.updateByShopId(row);
    }

    @Override
    public String resolvePayMchId(Long shopId)
    {
        if (!payProperties.isRealPayEnabled())
        {
            return payProperties.getMchId();
        }
        BizShopWechatPay row = shopWechatPayMapper.selectByShopId(shopId);
        if (row == null || !"1".equals(row.getEnabled()))
        {
            if (StringUtils.isNotEmpty(payProperties.getMchId()))
            {
                return payProperties.getMchId();
            }
            throw new ServiceException(PayConstants.MSG_SHOP_PAY_NOT_ENABLED);
        }
        if (PayConstants.PAY_MODE_SHOP.equals(row.getPayMode()))
        {
            if (StringUtils.isEmpty(row.getMchId()))
            {
                throw new ServiceException(PayConstants.MSG_SHOP_PAY_NOT_ENABLED);
            }
            return row.getMchId();
        }
        if (PayConstants.PAY_MODE_SUB.equals(row.getPayMode()))
        {
            if (StringUtils.isNotEmpty(row.getSubMchId()))
            {
                return row.getSubMchId();
            }
            throw new ServiceException(PayConstants.MSG_SHOP_PAY_NOT_ENABLED);
        }
        if (StringUtils.isEmpty(payProperties.getMchId()))
        {
            throw new ServiceException(PayConstants.MSG_PAY_CONFIG_MISSING);
        }
        return payProperties.getMchId();
    }

    @Override
    public List<ShopWechatPayPlatformVO> selectPlatformList(ShopWechatPayPlatformQuery query)
    {
        List<ShopWechatPayPlatformVO> list = shopWechatPayMapper.selectPlatformList(query);
        for (ShopWechatPayPlatformVO vo : list)
        {
            vo.setApplyStatusLabel(toApplyStatusLabel(vo.getApplyStatus()));
            vo.setPayModeLabel(toPayModeLabel(vo.getPayMode()));
        }
        return list;
    }

    @Override
    public int countPlatformPending()
    {
        return shopWechatPayMapper.countByApplyStatus(PayConstants.APPLY_PENDING);
    }

    @Override
    public ShopWechatPayPlatformVO selectPlatformDetail(Long id)
    {
        ShopWechatPayPlatformVO vo = shopWechatPayMapper.selectPlatformById(id);
        if (vo == null)
        {
            throw new ServiceException("入驻申请不存在");
        }
        vo.setApplyStatusLabel(toApplyStatusLabel(vo.getApplyStatus()));
        vo.setPayModeLabel(toPayModeLabel(vo.getPayMode()));
        return vo;
    }

    @Override
    public void auditApprove(Long shopId, String operator)
    {
        BizShopWechatPay existing = requirePendingApply(shopId);
        validatePayModeConfig(existing);
        Date now = new Date();
        BizShopWechatPay row = new BizShopWechatPay();
        row.setShopId(shopId);
        row.setApplyStatus(PayConstants.APPLY_APPROVED);
        row.setAuditRemark("");
        row.setEnabled("1");
        row.setUpdateBy(operator);
        row.setUpdateTime(now);
        if (shopWechatPayMapper.updateAuditStatus(row) == 0)
        {
            throw new ServiceException(PayConstants.MSG_APPLY_NOT_PENDING);
        }
    }

    @Override
    public void auditReject(ShopWechatPayAuditRejectDTO dto, String operator)
    {
        if (dto == null || dto.getShopId() == null)
        {
            throw new ServiceException(PayConstants.MSG_APPLY_NOT_PENDING);
        }
        if (StringUtils.isEmpty(StringUtils.trim(dto.getAuditRemark())))
        {
            throw new ServiceException(PayConstants.MSG_APPLY_REJECT_REMARK_REQUIRED);
        }
        requirePendingApply(dto.getShopId());
        Date now = new Date();
        BizShopWechatPay row = new BizShopWechatPay();
        row.setShopId(dto.getShopId());
        row.setApplyStatus(PayConstants.APPLY_REJECTED);
        row.setAuditRemark(StringUtils.trim(dto.getAuditRemark()));
        row.setEnabled("0");
        row.setUpdateBy(operator);
        row.setUpdateTime(now);
        if (shopWechatPayMapper.updateAuditStatus(row) == 0)
        {
            throw new ServiceException(PayConstants.MSG_APPLY_NOT_PENDING);
        }
    }

    private BizShopWechatPay requirePendingApply(Long shopId)
    {
        BizShopWechatPay existing = shopWechatPayMapper.selectByShopId(shopId);
        if (existing == null || !PayConstants.APPLY_PENDING.equals(existing.getApplyStatus()))
        {
            throw new ServiceException(PayConstants.MSG_APPLY_NOT_PENDING);
        }
        return existing;
    }

    private void validatePayModeConfig(BizShopWechatPay row)
    {
        if (PayConstants.PAY_MODE_SHOP.equals(row.getPayMode()) && StringUtils.isEmpty(row.getMchId()))
        {
            throw new ServiceException("请填写微信商户号");
        }
        if (PayConstants.PAY_MODE_SUB.equals(row.getPayMode()) && StringUtils.isEmpty(row.getSubMchId()))
        {
            throw new ServiceException("请填写服务商子商户号");
        }
    }

    private void validateApply(ShopWechatPaySaveDTO dto)
    {
        if (dto == null)
        {
            throw new ServiceException(PayConstants.MSG_APPLY_REQUIRED);
        }
        if (StringUtils.isEmpty(dto.getCompanyName())
                || StringUtils.isEmpty(dto.getLegalPerson())
                || StringUtils.isEmpty(dto.getLicenseNo())
                || StringUtils.isEmpty(dto.getContactName())
                || StringUtils.isEmpty(dto.getContactMobile()))
        {
            throw new ServiceException(PayConstants.MSG_APPLY_REQUIRED);
        }
        String payMode = dto.getPayMode();
        if (PayConstants.PAY_MODE_SHOP.equals(payMode) && StringUtils.isEmpty(dto.getMchId()))
        {
            throw new ServiceException("请填写微信商户号");
        }
        if (PayConstants.PAY_MODE_SUB.equals(payMode) && StringUtils.isEmpty(dto.getSubMchId()))
        {
            throw new ServiceException("请填写服务商子商户号");
        }
    }

    private ShopWechatPayVO toVo(BizShopWechatPay row)
    {
        ShopWechatPayVO vo = new ShopWechatPayVO();
        vo.setShopId(row.getShopId());
        vo.setApplyStatus(row.getApplyStatus());
        vo.setApplyStatusLabel(toApplyStatusLabel(row.getApplyStatus()));
        vo.setPayMode(row.getPayMode());
        vo.setPayModeLabel(toPayModeLabel(row.getPayMode()));
        vo.setMchId(row.getMchId());
        vo.setSubMchId(row.getSubMchId());
        vo.setCompanyName(row.getCompanyName());
        vo.setLegalPerson(row.getLegalPerson());
        vo.setLicenseNo(row.getLicenseNo());
        vo.setContactName(row.getContactName());
        vo.setContactMobile(row.getContactMobile());
        vo.setBankName(row.getBankName());
        vo.setBankAccountName(row.getBankAccountName());
        vo.setBankAccountNo(row.getBankAccountNo());
        vo.setAuditRemark(row.getAuditRemark());
        vo.setEnabled(row.getEnabled());
        vo.setUpdateTime(row.getUpdateTime());
        return vo;
    }

    private String toApplyStatusLabel(String status)
    {
        if (PayConstants.APPLY_PENDING.equals(status))
        {
            return "审核中";
        }
        if (PayConstants.APPLY_APPROVED.equals(status))
        {
            return "已通过";
        }
        if (PayConstants.APPLY_REJECTED.equals(status))
        {
            return "已驳回";
        }
        return "未申请";
    }

    private String toPayModeLabel(String payMode)
    {
        if (PayConstants.PAY_MODE_SHOP.equals(payMode))
        {
            return "店铺自有商户号";
        }
        if (PayConstants.PAY_MODE_SUB.equals(payMode))
        {
            return "服务商子商户";
        }
        return "平台代收";
    }
}
