package com.bcxin.ins.supply.owner.impl;

import com.bcxin.ins.core.entity.R;
import com.bcxin.ins.supply.SupplyType;
import com.bcxin.ins.supply.owner.SupplyStrategy;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.utils.FreemarkerUtil;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 太平洋保险
 * @author hzp
 * @date 2018/06/12
 */
@SupplyType(type = SupplyType.SupplyTypeEnum.TAI_BAO)
public class SupplyStrategyTaiBao implements SupplyStrategy {

    // 版本标识，固定值 3
    private static final String MESSAGEROUTER = "3";
    // 合作伙伴编码，由太保指定，每个商户不一样
    private static final String PARTNERCODE = "XMBCX";
    // 业务协议，固定值 CPIC_ECOM
    private static final String DOCUMENTPROTOCOL = "CPIC_ECOM";

    @Override
    public R uniformInterface(String productSign, Map<String, Object> map) {
        try {
            String templateName = SupplyType.SupplyTypeEnum.TAI_BAO.getKey()+"_"+productSign + ".ftl";
            String requestXML = FreemarkerUtil.getInstance().transferMapToString(templateName,map);
        }catch (Exception e){
            return new R("请求报文解析错误！" + e.getMessage(),false);
        }

        if(StringUtils.isNotEmpty(productSign) && map != null){
            String resultXML = ConstProp.BLANK_CHAR;
            String returnXML = ConstProp.BLANK_CHAR;
            String url = ConstProp.BLANK_CHAR;
            if("XWCK".equals(productSign)){
                url = String.valueOf(GlobalResources.map.get("CPIC_XYX_INS_URL"));
                //resultXML = new Depacketize().retrieval(map);
            }
            if(StringUtils.isNotEmpty(resultXML)){
                for(int i=0;i<3;i++){
                    returnXML = syncTB(resultXML, url);
                    if(StringUtils.isNotEmpty(returnXML)){
                        break;
                    }
                }
            }else{
                return new R("请求报文组装失败！",false);
            }
            if(StringUtils.isNotEmpty(returnXML)){
                if("XWCK".equals(productSign)){
                    //return new Depacketize().analysis(map);
                }
            }else{
                return new R("未返回报文！",false);
            }
        }
        return new R("参数缺失，接口业务中断！",false);
    }

    private String syncTB(String requestMeg, String url){
        String result = ConstProp.BLANK_CHAR;
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // 版本标识
            params.add(new BasicNameValuePair("messageRouter", MESSAGEROUTER));
            // 业务伙伴代码
            params.add(new BasicNameValuePair("tradingPartner", PARTNERCODE));
            // 业务协议
            params.add(new BasicNameValuePair("documentProtocol", DOCUMENTPROTOCOL));
            // xml请求报文
            params.add(new BasicNameValuePair("requestMessage", requestMeg));

            HttpClient client = new DefaultHttpClient();
            registerSSLSocketFactory(client);
            // 注意：必须以post方式发送请求
            HttpPost post = new HttpPost(url);
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);

        } catch(Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private void registerSSLSocketFactory(HttpClient httpclient) throws Exception {
        KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
        String fileUrl = "";
        if(System.getProperty("os.name").contains("indows")){
            fileUrl = "F:\\D_pan\\test\\upload\\cpic_jttp.keystore";
        }else{
            fileUrl = "/data/upload/blb/cpic/cpic_jttp.keystore";
        }
        try (FileInputStream instream = new FileInputStream(new File(fileUrl))) {
            trustStore.load(instream, "cpicJttp".toCharArray());
            System.out.println("instream:"+instream);
        }
        SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
        Scheme sch = new Scheme("https", socketFactory, 443);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);

    }
}
