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


import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.trade.request.PostSettlementRequest;
import com.neusoft.smart.pos.dto.trade.request.PutSettlementRequest;
import com.neusoft.smart.pos.dto.trade.response.GetSettlementResponse;
import com.neusoft.smart.pos.dto.trade.response.PostSettlementResponse;
import com.neusoft.smart.pos.dto.trade.response.PutSettlementResponse;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.order.constants.TradeErrorCode;
import com.neusoft.smart.pos.payorder.persistent.domain.TradeMchPayChannel;
import com.neusoft.smart.pos.payorder.persistent.domain.TradeSettlementInfo;
import com.neusoft.smart.pos.payorder.repository.PayChannelRepository;
import com.neusoft.smart.pos.payorder.repository.PayOrderRepository;
import com.neusoft.smart.pos.payorder.repository.TradeSettlementRepository;
import com.neusoft.smart.pos.trade.persistent.domain.BillShop;
import com.neusoft.smart.pos.trade.repository.BillShopRepository;
import com.neusoft.smart.pos.trade.repository.PayTypeRepository;
import com.neusoft.smart.pos.utils.PosDeviceRedisUtils;
import lombok.val;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("tradeSettlementService")
public class TradeSettlementService {

	private final static Logger logger = LoggerFactory.getLogger(TradeSettlementService.class);

	@Autowired
	private TradeSettlementRepository tradeSettlementRepository;

	@Autowired
	private PayOrderRepository payOrderRepository;

	@Autowired
	private PayChannelRepository payChannelRepository;

	@Autowired
	private PayTypeRepository payTypeRepository;
	
	@Autowired
	private BillShopRepository billShopRepository;
	
	/**
	 * 商户结算信息添加方法
	 * @return
	 */
	public PostSettlementResponse saveSettlement(PostSettlementRequest settlementRequest) {
		//1.查询业务系统结算信息，判断业务系统结算信息是否存在
        TradeSettlementInfo tradeSettlementInfo= tradeSettlementRepository.queryTradeSettlementInfo(settlementRequest.getOrgId(),settlementRequest.getShopId());
		if(null != tradeSettlementInfo){
			throw new BusinessCommonException(TradeErrorCode.SETTLEMENT_INFO_EXIST);
		}
		val tradePayTypeDict = payTypeRepository.queryEnabledPayType(DictionaryConstant.PAY_TYPE_WXEWM.getCode());

		//2.调用聚合支付平台申请商户信息
		val payApplyMchInfoResponse = payOrderRepository.applyMch(settlementRequest.getMchName(),tradePayTypeDict);
		if(null == payApplyMchInfoResponse){
			throw new BusinessCommonException(TradeErrorCode.SETTLEMENT_APPLY_MCH_ERROR);
		}
		//3.存储申请的商户信息至业务系统
        tradeSettlementInfo = new TradeSettlementInfo();
        tradeSettlementInfo.setMcode(payApplyMchInfoResponse.getMcode());
        tradeSettlementInfo.setOrgId(settlementRequest.getOrgId());
        tradeSettlementInfo.setShopId(settlementRequest.getShopId());
        tradeSettlementInfo.setSettlementType(settlementRequest.getSettlementType());
        tradeSettlementInfo.setMchName(payApplyMchInfoResponse.getMchName());
        tradeSettlementInfo.setSecretKey(payApplyMchInfoResponse.getSecretKey());
        val settlementSaveBool = tradeSettlementRepository.saveTradeSettlementInfo(tradeSettlementInfo);
        if(!settlementSaveBool){
            throw new BusinessCommonException(TradeErrorCode.SETTLEMENT_SAVE_ERROR);
        }
		
        //存储结算门店信息 start
		BillShop billShop = new BillShop();
		billShop.setOrgId(settlementRequest.getOrgId());
		billShop.setShopId(settlementRequest.getShopId());
		billShopRepository.saveBillShop(billShop);
        //存储结算门店信息 end
        
		//4.默认开通现金支付渠道(如果当前是门店且结算方式是集团结算，则无需开通默认支付信息)
		TradeMchPayChannel tradeMchPayChannel = new TradeMchPayChannel();
		tradeMchPayChannel.setOrgId(settlementRequest.getOrgId());
		tradeMchPayChannel.setShopId(settlementRequest.getShopId());
		tradeMchPayChannel.setPayType(DictionaryConstant.PAY_TYPE_XJ.getCode());
		val payChannelSaveBool = payChannelRepository.savePayChannel(tradeMchPayChannel);
		if(!payChannelSaveBool){
			throw new BusinessCommonException(TradeErrorCode.SETTLEMENT_DEFAULT_CHANNEL_SAVE_ERROR);
		}

		return new PostSettlementResponse(true);
	}

	/**
	 * 商户结算信息更新方法
	 * @return
	 */
	public PutSettlementResponse updateSettlement(PutSettlementRequest settlementRequest) {
		//1.更新商户结算信息至业务系统
		val tradeSettlementInfo = new TradeSettlementInfo();
		BeanUtils.copyProperties(settlementRequest,tradeSettlementInfo);
		val settlementSaveBool = tradeSettlementRepository.updateTradeSettlementInfo(tradeSettlementInfo);
		if(!settlementSaveBool){
			throw new BusinessCommonException(TradeErrorCode.SETTLEMENT_UPDATE_ERROR);
		}
		return new PutSettlementResponse(settlementSaveBool);
	}

	/**
	 * 商户结算信息查询方法
	 * @return
	 */
	public GetSettlementResponse querySettlement(String serialNo) {
		val deviceInfo = PosDeviceRedisUtils.getDeviceInfoBySerialNo(serialNo);
		if(null == deviceInfo){
			throw new BusinessCommonException(TradeErrorCode.DEVICE_ORG_EMPTY);
		}
		val orgId = deviceInfo.getOrganizationId();
		val shopId = deviceInfo.getStoreId();
		//1.更新商户结算信息至业务系统
		val tradeSettlementInfo = tradeSettlementRepository.queryTradeSettlementInfo(orgId,shopId);
		GetSettlementResponse settlementResponse = new GetSettlementResponse();
		settlementResponse.setSettlementType(tradeSettlementInfo.getSettlementType());
		return settlementResponse;
	}
	
	/**
	 *
	 * @param orgId
	 * @param shopId
	 * @return
	 */
	public GetSettlementResponse querySettlement(Integer orgId, Integer shopId) {
		val tradeSettlementInfo = tradeSettlementRepository.queryTradeSettlementInfo(orgId,shopId);
		GetSettlementResponse settlementResponse = new GetSettlementResponse();
		settlementResponse.setSettlementType(tradeSettlementInfo.getSettlementType());
		return settlementResponse;
	}

}
