package com.neusoft.smart.pos.payorder.service;

import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.payorder.constants.PayErrorCode;
import com.neusoft.smart.pos.payorder.persistent.domain.PayTypeDict;
import com.neusoft.smart.pos.payorder.persistent.domain.TradeSettlementInfo;
import com.neusoft.smart.pos.payorder.repository.PayChannelRepository;
import com.neusoft.smart.pos.payorder.repository.PayTypeDictRepository;
import com.neusoft.smart.pos.payorder.repository.TradeSettlementRepository;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("tradeSettlementQueryService")
public class TradeSettlementQueryService {
    @Autowired
    private TradeSettlementRepository tradeSettlementRepository;

    @Autowired
    private PayChannelRepository payChannelRepository;

    @Autowired
    private PayTypeDictRepository payTypeDictRepository;

    public TradeSettlementInfo queryTradeSettlementInfo(Integer orgId, Integer shopId) {
        TradeSettlementInfo resultTradeSettlementInfo = tradeSettlementRepository.queryTradeSettlementInfo(orgId,shopId);
        Integer shopIdTemp = 0;
        if (DictionaryConstant.SETTLEMENT_TYPE_JT.getCode().equals(resultTradeSettlementInfo.getSettlementType())) {
            resultTradeSettlementInfo = tradeSettlementRepository.queryTradeSettlementInfo(orgId, shopIdTemp);
        }
        return resultTradeSettlementInfo;
    }

    public void verifyShopPayChannelByPayType(Integer orgId, Integer shopId, String payType) {
        TradeSettlementInfo resultTradeSettlementInfo = tradeSettlementRepository.queryTradeSettlementInfo(orgId,shopId);
        if (DictionaryConstant.SETTLEMENT_TYPE_JT.getCode().equals(resultTradeSettlementInfo.getSettlementType())) {
            shopId = 0;
        }

        val tradeMchPayChannel = payChannelRepository.queryShopPayChannelByPayType(orgId, shopId, payType);
        if (null == tradeMchPayChannel) {
            throw new BusinessCommonException(PayErrorCode.PAY_CHANNEL_IS_NOT_OPEN);
        }
    }

    public PayTypeDict queryEnablePayTypeDict(String payType) {
        val payTypeDict = payTypeDictRepository.queryEnablePayTypeDict(payType);
        if (null == payTypeDict) {
            throw new BusinessCommonException(PayErrorCode.DICT_PAY_TYPE_NOT_EXIST);
        }
        return payTypeDict;
    }
}
