package com.ssj.framework.cmb.service.impl;

import com.ssj.framework.cmb.service.CmbService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.ssj.framework.cmb.util.XmlPacket;
import com.ssj.framework.core.security.exception.ConchException;
import com.ssj.framework.core.util.Constant;
import com.ssj.framework.core.util.HttpClientUtil;
import com.ssj.framework.core.util.PropertiesUtil;
import com.ssj.framework.core.util.StringUtil;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 类CmbServiceImpl.java的实现描述：
 */
@Service("cmbService")
public class CmbServiceImpl implements CmbService {

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

	@Override
    public String df( String account, String userName, BigDecimal amount, String code,
                     String eacbnk, String eaccty, String remark) throws Exception {

        // 生成请求报文
        String data = this.getRequestDfStr(account, userName, amount.toString(), code,  eacbnk, eaccty, remark);
        logger.info(data);

        // 连接前置机，发送请求报文，获得返回报文
        String result = HttpClientUtil.sendBankPostRequest(PropertiesUtil.getValue("qzjServerUrl"),data);
        // 处理返回的结果
        return this.processResult4df(result);
    }
	@Override
	public String df(String requestParameter) throws Exception {
		
		// 生成请求报文
		logger.info(requestParameter);
		
		// 连接前置机，发送请求报文，获得返回报文
		String result = HttpClientUtil.sendBankPostRequest(PropertiesUtil.getValue("qzjServerUrl"),requestParameter);
		// 处理返回的结果
		return result;
	}
	

    @Override
    public String dfcx(String tranCode) {
        // 生成请求报文
        String data = this.getRequestDfcxStr(tranCode);
        String result = HttpClientUtil.sendBankPostRequest(PropertiesUtil.getValue("qzjServerUrl"),data);
        // 处理返回的结果
        return result;

    }


    /**
     * 处理返回的结果
     *
     * @param result
     */
    private String processResult4df(String result) {
    	 logger.info("请求返回"+result);
        if (result != null && result.length() > 0) {
                XmlPacket pktRsp = XmlPacket.valueOf(result);
                logger.info("XmlPacket请求返回"+pktRsp);
                if (pktRsp != null) {
                    String sRetCod = pktRsp.getRETCOD();
                    if (sRetCod.equals("0")) {
                        Map propPayResult = pktRsp.getProperty("NTREQNBRY", 0);
                        String REQNBR = (String) propPayResult.get("REQNBR");
                        logger.info("请求已被银行受理,message:{}", result);
                        return REQNBR;
                    }
                    else {
                        logger.info("请求处理失败,message:{}", result);
                        throw new ConchException("error");
                    }
            } else {
                logger.info("校验签名失败,message:{}", result);
                throw new ConchException("SIGN_ERROR");
            }
        } else {
            logger.info("返回结果异常，消息为空，{}", result);
            throw new ConchException("error");
        }
    }

    /**
     * 处理返回的结果
     *
     * @param result
     */
    private Map<String, String> processResult4dfcx(String result) {
        logger.info("返回结果为:{}", result);
        Map<String, String> map = new HashMap<String, String>();

        if (result != null && result.length() > 0) {
            XmlPacket pktRsp = XmlPacket.valueOf(result);
            if (pktRsp != null) {
                String sRetCod = pktRsp.getRETCOD();
                if (sRetCod.equals("0")) {

                    Map propPayResult = pktRsp.getProperty("NTQATDQYZ", 0);
                    String STSCOD = propPayResult.get("STSCOD").toString();
                    if (Constant.CMB_DF_STATUS_S.equals(STSCOD)) {
                        map.put("status", Constant.WITHDRAWAL_STATUS_SUCCESS);
                        return map;
                    }
                    if (Constant.CMB_DF_STATUS_I.equals(STSCOD)) {
                        map.put("status", Constant.WITHDRAWAL_STATUS_INIT);
                        return map;
                    }
                    if (Constant.CMB_DF_STATUS_F.equals(STSCOD)) {
                        map.put("status", Constant.WITHDRAWAL_STATUS_FAIL);
                        String ERRDSP = propPayResult.get("ERRDSP").toString();
                        map.put("failMessage", ERRDSP);
                        return map;
                    }
                }
            }
        }
        logger.warn("获取代发状态异常", result);
        map.put("status", Constant.WITHDRAWAL_STATUS_ERROR);
        return map;
    }

    /**
     * 生成请求报文
     *
     * @return
     */
    @Override
    public String getRequestDfStr(String account, String userName, String amount, String code, 
                                  String eacbnk, String eaccty, String remark) {
        // 构造代付的请求报文
        XmlPacket xmlPkt = new XmlPacket("AgentRequest", PropertiesUtil.getValue("entUserName"));
        Map mpPayInfo = new Properties();
        mpPayInfo.put("BUSCOD", "N03020");// 代发
        mpPayInfo.put("BUSMOD", "00001");// 代发
        mpPayInfo.put("TRSTYP", "BYBK"); // 代发其他
        mpPayInfo.put("DBTACC", PropertiesUtil.getValue("DBTACC"));
        mpPayInfo.put("BBKNBR", PropertiesUtil.getValue("BBKNBR"));
        mpPayInfo.put("SUM", amount.toString());
        mpPayInfo.put("TOTAL", "1");
        mpPayInfo.put("CCYNBR", "10");
        mpPayInfo.put("YURREF", code);
        if (StringUtil.isNotEmpty(remark)) {
            mpPayInfo.put("MEMO", remark);
        } else {
            mpPayInfo.put("MEMO", "分成");
        }
        xmlPkt.putProperty("SDKATSRQX", mpPayInfo);
        Map mpPodInfo = new Properties();
        mpPodInfo.put("ACCNBR", account);
        mpPodInfo.put("CLTNAM", userName);
        mpPodInfo.put("TRSAMT", amount.toString());
        if ("招商银行".equals(eacbnk)) {
            mpPodInfo.put("BNKFLG", "Y");
        } else {
            mpPodInfo.put("BNKFLG", "N");
            mpPodInfo.put("EACBNK", eacbnk);
            mpPodInfo.put("EACCTY", eaccty);
        }
        if (StringUtil.isNotEmpty(remark)) {
            mpPodInfo.put("TRSDSP", remark);
        } else {
            mpPodInfo.put("TRSDSP", "分成");
        }
        xmlPkt.putProperty("SDKATDRQX", mpPodInfo);
        return xmlPkt.toXmlString();
    }

    /**
     * 生成请求报文
     *
     * @return
     */
    public String getRequestDfcxStr(String tranCode) {
        // 构造代付的请求报文
        XmlPacket xmlPkt = new XmlPacket("GetAgentDetail",  PropertiesUtil.getValue("entUserName"));
        Map mpPayInfo = new Properties();
        mpPayInfo.put("REQNBR", tranCode);// 代发
        xmlPkt.putProperty("SDKATDQYX", mpPayInfo);
        return xmlPkt.toXmlString();
    }

}
