package com.tax.token.utils;

import com.alibaba.fastjson.JSONObject;
import com.tax.token.constants.TokenConstants;
import com.tax.token.model.TkServer;
import com.tax.token.model.TkToken;
import com.tax.token.model.TkZoneInfo;
import com.yxcheng.token.utils.HttpConnectionManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;


import java.util.ArrayList;
import java.util.List;


public class TokenUtil {
    private static Logger logger = Logger.getLogger(TokenUtil.class);
    /**
     * 登录国税网站，成功返回Token
     * String index,String dqdm,String cert,String ymbb
     */


    public static String getToken(TkToken tkToken, TkZoneInfo zoneInfo, TkServer tkServer) {
       return getToken(tkToken.getKeyCode(),tkToken.getTaxno(),tkToken.getZoneCode(),zoneInfo.getYmbb(),tkToken.getSecert(),tkServer.getReqUrl());
    }

    public static String getToken(String index,String taxno,String zone,String ymbb,String secret,String reqUrl){
        String token = null;
        int i=0;
       // while (token==null && i<5) {
            i++;
            logger.info("尝试登录次数："+i);
            token = firstLogin(index, zone, taxno, ymbb,secret,reqUrl);
       // }
        return token;
    }

    private static String firstLogin(String index,String dqdm,String cert,String ymbb,String secert,String reqUrl)
    {
        String url = TokenConstants.urlMap.get(dqdm)+"SbsqWW/login.do";
        String clientHello =AuthC.getClientHello(index,reqUrl) ;
        if (clientHello==null || "".equals(clientHello)) {
            return null;
        }

        HttpClient httpClient = HttpConnectionManager.httpsTrustClient();

        StringBuilder sb = new StringBuilder();
        sb.append("type=CLIENT-HELLO");
        sb.append("&");
        sb.append("clientHello="+clientHello);
        sb.append("&");
        sb.append("ymbb="+ymbb);


        HttpGet httpget = new HttpGet(url + "?" + sb.toString());

        logger.info("访问："+(url + "?" + sb.toString()));

        int times = 0;
//        while(times < 5)
//        {
            HttpResponse response = null;
            try
            {
                response = httpClient.execute(httpget);
                HttpEntity entity = response.getEntity();
                if (entity != null)
                {
                    String content = EntityUtils.toString(entity);
                    logger.info("firstLogin 返回结果："+ content);

                    content = content.substring(content.indexOf("{"),
                            content.lastIndexOf("}") + 1);

                    JSONObject json = JSONObject.parseObject(content);

                    String retCode = json.getString("key1");
                    String serverPacket = json.getString("key2");
                    String serverRandom = json.getString("key3");

                    if (!"01".equals(retCode))
                    {
                        System.out.println("error");
                        return null;
                    }

                    logger.info("开始第二次登陆 ");

//                    clientContext.get().clientAuth(serverPacket);
//
//                    String clientAuthCode = clientContext.get().strResult;

                    String clientAuthCode =AuthC.getClientAuth(serverPacket, index,reqUrl) ;
                    if (clientAuthCode==null || "".equals(clientAuthCode)) {
                        return null;
                    }

                    logger.info("clientAuthCode = "+ clientAuthCode);

                    String result = secondLogin(url, ymbb, clientAuthCode, serverRandom,cert,secert);
                    if (null != result)
                    {
                        return result;
                    }
                }
                else
                {
                    System.out.println("error2");
                    return null;
                }
            }
            catch(Exception e)
            {
//            	processException(e, times, MAX_LOGIN_TIMES);
                System.out.println("error3");
            }
            finally
            {
                if (null != httpget)
                {
                    httpget.releaseConnection();
                    httpget.abort();
                }
            }
            times++;
       // }

        return null;
    }
    private static String secondLogin(String url, String ymbb, String clientAuthCode, String serverRandom,String nsrsbh,String secert)
    {

        HttpClient httpClient = HttpConnectionManager.httpsTrustClient();

        HttpPost httpPost = new HttpPost(url);

        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("type", "CLIENT-AUTH"));
        params.add(new BasicNameValuePair("clientAuthCode", clientAuthCode));
        params.add(new BasicNameValuePair("serverRandom", serverRandom));
        if (secert!=null && !"".equals(secert)) {
            params.add(new BasicNameValuePair("password", secert));
        }

        params.add(new BasicNameValuePair("cert", nsrsbh));
        params.add(new BasicNameValuePair("ymbb", ymbb));

        logger.info(params.toString());

        int times = 0;
//        while(times < 5)
//        {
            HttpResponse response = null;
            try
            {
                httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

                logger.info("访问："+url);

                response = httpClient.execute(httpPost);
                HttpEntity entity = response.getEntity();
                if (entity != null)
                {
                    String content = EntityUtils.toString(entity);
                    logger.info("secondLogin "+ nsrsbh+" 返回结果："+ content);

                    content = content.substring(content.indexOf("{"),
                            content.lastIndexOf("}") + 1);

                    JSONObject json = JSONObject.parseObject(content);

                    String key1 = json.getString("key1");

                    if ("03".equals(key1))
                    {
                        logger.info("第二次 登录成功：token="+json.getString("key2"));

                        return json.getString("key2");
                    }else if ("08".equals(key1))
                    {
                        System.out.println("需要平台密码 "+ nsrsbh);
                    }

                    else
                    {
                        logger.error("第二次 登录失败 "+ nsrsbh);
                        System.out.println("第二次 登录失败 "+ nsrsbh+"json:"+json.toString());
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            catch(Exception e)
            {
                logger.error(e.getMessage());
                for(StackTraceElement ste : e.getStackTrace())
                {
                    logger.error("\tat "+ste);
                }
            }
            finally
            {
                if (null != httpPost)
                {
                    httpPost.releaseConnection();
                    httpPost.abort();
                }
            }
            times++;
       // }

        return null;
    }





    public static void main(String[] args) {
       // String token = TokenUtil.getToken("204","91110108553139977P","1100","4.0.10",null);
//        String token = TokenUtil.getToken("17","91460111767473743W","4600","4.0.10",null,"#rsa");
//       System.out.println("token"+token);

    }

}
