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

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.neusoft.smart.pos.dto.fumao.bean.MemberDiscount;
import com.neusoft.smart.pos.dto.payment.response.*;
import com.neusoft.smart.pos.dto.trade.request.GetPosPayChannelsRequest;
import com.neusoft.smart.pos.dto.trade.response.GetPayChannelsResponse;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.fumao.utils.HttpClientUtils;
import lombok.val;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.fumao.request.PostFumaoTradeOrderRequest;
import com.neusoft.smart.pos.fumao.persistent.domain.FumaoTenantInfo;
import com.neusoft.smart.pos.fumao.persistent.ext.domain.FumaoMerchantQueryRequest;
import com.neusoft.smart.pos.fumao.persistent.repository.FumaoBusinessActionRepository;
import com.neusoft.smart.pos.fumao.constants.FumaoConstants;

@Service("FumaoBusinessService")
public class FumaoBusinessService implements IBusinessService<PostFumaoTradeOrderRequest, FumaoParameterforNextStep>{
    private final static Logger logger = LoggerFactory.getLogger(FumaoBusinessService.class);

	@Autowired
	private FumaoBusinessActionRepository fumaoBusinessActionRepository;
	
	@Override
	public FumaoParameterforNextStep environmentPrepare() {
		return new FumaoParameterforNextStep();
	}
	
	@Override
	public FumaoParameterforNextStep executePrepare(PostFumaoTradeOrderRequest postFumaoTradeOrderRequest) {
        FumaoMemberInfoRes memberInfo = fumaoBusinessActionRepository.queryAndCalc(postFumaoTradeOrderRequest);
        if(!memberInfo.getReturn_code().equals("0")) {
            throw new BusinessCommonException(memberInfo.getReturn_code(),memberInfo.getReturn_msg());
        }
		FumaoParameterforNextStep result = new FumaoParameterforNextStep();
		result.setActionName(FumaoConstants.ACTION_NAME_CONSUME_GENERATE);
		result.setTotalAmount(postFumaoTradeOrderRequest.getParameterforNextStep().getTotalAmount());
		// 构建predictionTotal
		FumaoPaymentPrediction predictionTotal = new FumaoPaymentPrediction();
		predictionTotal.setOrder_amount(Long.parseLong(memberInfo.getOrder_amount()));
		predictionTotal.setOrder_amount_left(Long.parseLong(memberInfo.getOrder_amount_left()));
        //解析第三方试算返回的结果
        FumaoPromotionData promotionData = memberInfo.getPromotionData();
        FumaoPromotionInfo promotionInfo = promotionData.getPromotion_info();
        FumaoPaymentPrediction paymentPrediction = promotionData.getPayment_prediction();
        MemberDiscount memberDiscount = promotionInfo.getMember_discount();
        FumaoCouponData coupon = promotionInfo.getCoupon() ;
        List<FumaoCouponInfo> couponList = coupon.getCoupon_list();

        //构建PaymentTypeList
        int sequence = 1;//TODO sequence 怎么赋值？？
        List<FumaoPaymentType> paymentTypeList = new ArrayList<FumaoPaymentType>();
        if(memberDiscount != null || (couponList != null && couponList.size() > 0)) { //富茂优惠
            FumaoPaymentType paymentType = new FumaoPaymentType();
            paymentType.setSequence(sequence++);
            paymentType.setPaymentTypeId(DictionaryConstant.PAY_TYPE_DISCOUNT.getCode());
            paymentType.setPaymentTypeName(DictionaryConstant.PAY_TYPE_DISCOUNT.getValue());
            paymentType.setSelectType("1");
            paymentType.setIsPaymentTypeSelected("1");
            paymentType.setActionName(FumaoConstants.ACTION_NAME_CONSUME_GENERATE);

            FumaoPaymentPrediction predictionType = new FumaoPaymentPrediction();
            predictionType.setOrder_amount(paymentPrediction.getOrder_amount());
            predictionType.setOrder_amount_left(paymentPrediction.getOrder_amount_left());
            predictionType.setPromotion_amount(paymentPrediction.getPromotion_amount());
            predictionType.setAmount_left_after_pay(paymentPrediction.getAmount_left_after_pay());
            paymentType.setPaymentPredictionbyType(predictionType);

            List<FumaoPaymentData> paymentDataList = new ArrayList<FumaoPaymentData>();
            //富茂会员折扣
            if (memberDiscount != null) {
                FumaoPaymentData paymentData = new FumaoPaymentData();
                paymentData.setMerchantID(memberInfo.getMerchant_id());
                paymentData.setMemberID(memberInfo.getMem_id());
                paymentData.setL1Title(memberDiscount.getDiscount_description());
                paymentData.setIsSelected("1");
                FumaoPaymentPrediction prediction = new FumaoPaymentPrediction();
                prediction.setOrder_amount(memberDiscount.getOrder_amount());
                prediction.setOrder_amount_left(memberDiscount.getOrder_amount_left());
                prediction.setPromotion_amount(memberDiscount.getDiscount_amount());
                prediction.setAmount_left_after_pay(Long.parseLong(memberDiscount.getRemain_amount()));
                paymentData.setPaymentPrediction(prediction);
                paymentDataList.add(paymentData);
            }
            //富茂优惠券
            if (couponList != null && couponList.size() > 0) {
                for (int i = 0; i < couponList.size(); i++) {
                    FumaoCouponInfo couponInfo = couponList.get(i);
                    FumaoPaymentData paymentData = new FumaoPaymentData();
                    paymentData.setCuponID(couponInfo.getCoupon_id());
                    paymentData.setCuponDescription(couponInfo.getCoupon_description());
                    paymentData.setIsSelected(couponInfo.getIs_selected()+"");
//                    FumaoPaymentPrediction prediction = new FumaoPaymentPrediction();
//                    prediction.setOrder_amount(orderAmount);
//                    prediction.setOrder_amount_left(orderAmount - memberDiscount.getRemain_amount());
//                    prediction.setPayment_amount(couponInfo.get);
//                    prediction.setAmount_left_after_pay(couponInfo.get);
//                    paymentData.setPaymentPrediction(prediction);
                    paymentDataList.add(paymentData);
                }
            }
            paymentType.setPaymentData(paymentDataList);
            paymentTypeList.add(paymentType);
        }
		predictionTotal.setPromotion_amount(paymentPrediction.getPromotion_amount());
		predictionTotal.setAmount_left_after_pay(Long.parseLong(coupon.getRemain_amount()));
        result.setPaymentPredictionofTotal(predictionTotal);

        //获取支付渠道
        GetPosPayChannelsRequest payChannelsRequest = new GetPosPayChannelsRequest();
        payChannelsRequest.setSerialNo(postFumaoTradeOrderRequest.getNeuInfo().getSn());
        val resultData = HttpClientUtils.getData("http://localhost:2008/payChannel/posPayChannels?serialNo=" + postFumaoTradeOrderRequest.getNeuInfo().getSn());//TODO url???
        logger.info("payChannel resultData:"+resultData);
        Map resultMap = (Map)JSON.parse(resultData);

        GetPayChannelsResponse payChannelsResponseResponse = null;
        if(("200").equals(resultMap.get("code").toString())){
            JSONObject jsonObject  = JSONObject.fromObject(resultMap.get("result"));
            Map<String, Class> classMap = new HashMap<String, Class>();
            classMap.put("payChannels", GetPayChannelsResponse.PayChannel.class);
            payChannelsResponseResponse = (GetPayChannelsResponse) JSONObject.toBean(jsonObject, GetPayChannelsResponse.class, classMap);
        }else{
            logger.error( "payChannels error:" + resultData);
            throw new BusinessCommonException(resultMap.get("code").toString(),resultMap.get("message").toString());
        }
        List<GetPayChannelsResponse.PayChannel> payChannelList = payChannelsResponseResponse.getPayChannels();
        for(int i = 0; i < payChannelList.size(); i++) {
            if(payChannelList.get(i).getPayType().equals(DictionaryConstant.PAY_TYPE_DISCOUNT.getCode())) {
                continue;
            }
            FumaoPaymentType paymentType = new FumaoPaymentType();
            paymentType.setSequence(sequence);
            paymentType.setPaymentTypeId(payChannelList.get(i).getPayType());
            paymentType.setPaymentTypeName(payChannelList.get(i).getName());
            paymentType.setSelectType("0");
            paymentType.setIsPaymentTypeSelected("0");
            paymentTypeList.add(paymentType);
        }
        result.setPaymentTypeList(paymentTypeList);
        result.setNextStep("Next");

		return result;
	}
	
	@Override
	public FumaoParameterforNextStep execute(PostFumaoTradeOrderRequest postFumaoTradeOrderRequest) {
        String actionName = postFumaoTradeOrderRequest.getParameterforNextStep().getActionName();
        FumaoParameterforNextStep result = new FumaoParameterforNextStep();
        switch(actionName) {
            case FumaoConstants.ACTION_NAME_CONSUME_GENERATE:
                return fumaoBusinessActionRepository.consume(postFumaoTradeOrderRequest);
            case FumaoConstants.ACTION_NAME_CONSUME_SUCCESS:
                return fumaoBusinessActionRepository.paySuccess(postFumaoTradeOrderRequest);
            case FumaoConstants.ACTION_NAME_CONSUME_QUERY:
                return fumaoBusinessActionRepository.queryPayStatus(postFumaoTradeOrderRequest);
			case FumaoConstants.ACTION_NAME_REFUND:
			    return fumaoBusinessActionRepository.refund(postFumaoTradeOrderRequest);
        }
        return result;
	}
	
	@Override
	public FumaoParameterforNextStep complete(PostFumaoTradeOrderRequest postFumaoTradeOrderRequest) {
        return fumaoBusinessActionRepository.complete(postFumaoTradeOrderRequest);
	}
	
	private List<FumaoTenantInfo> getFumaoTenantInfo() {
		FumaoMerchantQueryRequest req = new FumaoMerchantQueryRequest();
		req.setShop_id(1);
		List<FumaoTenantInfo> result = fumaoBusinessActionRepository.getList(req);
		return result;
	}

}
