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


import com.neusoft.smart.pos.dto.member.request.MemberRefundRequest;
import com.neusoft.smart.pos.dto.trade.request.PostRefundRequest;
import com.neusoft.smart.pos.dto.trade.response.PostRefundResponse;
import com.neusoft.smart.pos.framework.constants.ApplicationConstants;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.gateway.constants.InventoryConstant;
import com.neusoft.smart.pos.gateway.service.feignService.RemoteMemberService;
import com.neusoft.smart.pos.gateway.service.feignService.RemoteOrderRefundService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service("orderRefundService")
public class OrderRefundService {


	@Autowired
	private RemoteOrderRefundService remoteOrderRefundService;

	@Autowired
	private RemoteMemberService remoteMemberService;
	
	@Autowired
	private InventoryService inventoryService;
	
	/**
	 * POS端支付订单退款申请方法
	 * @return
	 */
	public PostRefundResponse saveOrderRefund(PostRefundRequest refundRequest){
		//1.交易系统处理退款申请
		val refundResponseData = remoteOrderRefundService.saveOrderRefund(refundRequest);
		if (null == refundResponseData || !ApplicationConstants.SUCCESS_CODE.equals(refundResponseData.getCode())) {
			throw new BusinessCommonException(refundResponseData);
		}

		//2.交易系统处理退款申请成功,如果会员卡不为空,处理会员积分退还
        if(!StringUtils.isEmpty(refundResponseData.getResult().getMemberCardNo())){
			MemberRefundRequest memberRefundRequest = new MemberRefundRequest();
			val refundResponse = refundResponseData.getResult();
			memberRefundRequest.setCardNum(refundResponse.getMemberCardNo());
			memberRefundRequest.setRefundOrderNo(refundRequest.getOrderNumber());
			memberRefundRequest.setRefundAmount(refundResponse.getRefundAmount());
			memberRefundRequest.setTransactionMode(Integer.valueOf(refundResponse.getPayType()));
            memberRefundRequest.setRefundTime(refundResponse.getRefundTime());
			remoteMemberService.refund(memberRefundRequest);
        }
		inventoryService.lockInventoryByStatus(refundRequest.getSerialNo(),refundRequest.getOrderNumber(), InventoryConstant.LOCKER_RETURN);
		return refundResponseData.getResult();
	}
}
