package com.tax.token.thirdService.impl;

import com.tax.token.model.TkServer;
import com.tax.token.model.TkToken;
import com.tax.token.model.TkZoneInfo;
import com.tax.token.thirdService.TokenThirdServiceI;
import com.yxcheng.token.utils.*;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class GetTokenFromLocal implements TokenThirdServiceI {

    private static final Logger logger = LoggerFactory.getLogger(GetTokenFromLocal.class);
    @Override
    public Map<String, Object> invoke(String uuIdFlag, TkToken tokenEntity, TkZoneInfo zoneInfo, TkServer tkServer,boolean isFirst) throws IOException, HttpException {
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        String taxno = tokenEntity.getTaxno();
        String dqbm = tokenEntity.getZoneCode();
        String keyCode = tokenEntity.getKeyCode();

        String ymbb = zoneInfo.getYmbb();
        String timeStamp = String.valueOf(new Date().getTime());
        String secert = tokenEntity.getSecert();
        String username = tkServer.getUserName();
        String password = tkServer.getPassword();

        paramsMap.put("dqdm", dqbm);
        paramsMap.put("cert", taxno);
        paramsMap.put("ymbb", ymbb);
        paramsMap.put("index", keyCode);
        paramsMap.put("time", timeStamp);
        paramsMap.put("user", username);
        paramsMap.put("secert", secert);
        paramsMap.put("serNo", tokenEntity.getIpServerNo());
        String sign = MD5Util.MD5Encode(dqbm + taxno + ymbb + keyCode + timeStamp + username + password);
        String url = tkServer.getReqUrl() + "?dqdm="+dqbm+ "&cert=" + taxno +"&ymbb="+ymbb +
                "&index=" + keyCode + "&time=" +timeStamp+"&user=" + username + "&sign=" +sign+ "&secert=" +secert + "&serNo=" + tokenEntity.getIpServerNo();
        System.out.println("url=" + url);
        ResponseContent ret  = null;
        if(isFirst){
            ret = HttpHelper.getUrlRespContent(url,30000);
        }else{
            ret = HttpHelper.getUrlRespContent(url);
        }
        String resultStr = ret.getContent();
        logger.info(taxno + " url is " + url + ",result is " + resultStr);
        Map<String, Object> resultMap =  new HashMap<>();
        if(StringUtils.isNotEmpty(resultStr)) {
            if(resultStr.startsWith("<html>")){
                return resultMap;
            }
            Map<String, Object> resultStrMap = JSONHelper.parserToMap(resultStr);
            resultMap.put("code", ObjectUtil.fixNull(resultStrMap.get("code")));

            String tokenMessage = ObjectUtil.fixNull(resultStrMap.get("message"));
            resultMap.put("message", tokenMessage);
            if("0".equals(resultStrMap.get("code"))){
                resultMap.put("token",resultStrMap.get("token"));
            } else {
                String key1 = ObjectUtil.fixNull(resultStrMap.get("key1"));
                if(tokenMessage.contains("\"key1\":\"110\"") || key1.equals("110")) {
                    resultMap.put("code", "4007");
                    resultMap.put("message","您当前为全电发票用票试点纳税人，请登录电子税务局，在【我要办税-税务数字账户】功能进行用票业务操作，感谢您的理解和支持！");
                }
            }
        }
        return resultMap;
    }


    public static void main(String[] args) throws IOException, HttpException {
//        TkToken tokenEntity = new TkToken();
//        TkZoneInfo zoneInfo=new TkZoneInfo(); TkServer tkServer=new TkServer();boolean isFirst = true;
//        tokenEntity.setTaxno("91445302708192853");
//        tokenEntity.setZoneCode("6100");
//        tokenEntity.setKeyCode("19");
//        tokenEntity.setSecert("");
//        tokenEntity.setIpServerNo("T00001");
//        zoneInfo.setYmbb("4.0.09");
//        tkServer.setReqUrl("http://tool.taxservices.cn:8010/token/token");
//        tkServer.setUserName("dx");
//        tkServer.setPassword("Dx@Pa33&*)o");

//        GetTokenFromLocal local = new GetTokenFromLocal();
//        System.out.println(local.invoke(tokenEntity,zoneInfo,tkServer,isFirst));
        String tokenMessage = "第二次 登录失败 91445302708192853Wcontent：{\"key5\":\"false\",\"key2\":\"91445302708192853W\",\"key1\":\"110\"}";
        System.out.println(tokenMessage.contains("登录失败") && tokenMessage.contains("false") && tokenMessage.contains("\"key1\":\"110\""));

    }
}
