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.HashMap;
import java.util.Map;

public class GetTokenFromEleTax implements TokenThirdServiceI {

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

    @Override
    public Map<String, Object> invoke(String uuIdFlag, TkToken tokenEntity, TkZoneInfo zoneInfo, TkServer tkServer, boolean isFirst) throws IOException, HttpException {
        Map<String,Object> resultMap = new HashMap<>();
        String taxno = tokenEntity.getTaxno();

        String zoneCode = tokenEntity.getZoneCode();
        String loginType = "";
        String secret = tokenEntity.getSecert();
        if(tokenEntity.getUserCode().startsWith("e")) {
            if(StringUtil.isNotEmpty(secret) && secret.startsWith("oldVersion=")) {
                secret = secret.replaceFirst("oldVersion=", "");
                loginType = "a";
                //不加0
            } else {
                loginType = "b";
            }
        }

        String type = "0";
        if(StringUtil.isNotEmpty(tokenEntity.getUserType()) && tokenEntity.getUserType().equals("2")) {
            type = "1";
            secret = "";
        }
        String url = tkServer.getReqUrl() + "?loginType="+StringUtil.transNullToEmpty(loginType)
                +"&userCode="+tokenEntity.getUserCode()+"&taxno="+taxno+"&type=" +type
                + "&dqdm="+zoneCode+"&loginInfo="+StringUtil.transNullToEmpty(secret)+"&loginInfoMd5="+StringUtil.transNullToEmpty(tokenEntity.getSecretMd5());

        ResponseContent ret = HttpHelper.getUrlRespContent(url);
        String resultStr = ret.getContent();
//        String resultStr = "{\"code\":\"2\",\"message\":\"33510000689904084E_13928467775账号密码输入不正确。\",\"otherinfo\":\"33510000689904084E_13928467775\"}";
        logger.info(uuIdFlag + " taxno " + taxno + " url is " + url + ",result is " + resultStr);
        if(StringUtils.isNotEmpty(resultStr)) {
            Map<String, Object> resultStrMap = JSONHelper.parserToMap(resultStr);
            resultMap.put("code", ObjectUtil.fixNull(resultStrMap.get("code")));
            resultMap.put("message", ObjectUtil.fixNull(resultStrMap.get("message")));
            resultMap.put("times", ObjectUtil.fixNull(resultStrMap.get("time")));
            if("0".equals(resultStrMap.get("code"))){
                resultMap.put("token",resultStrMap.get("token"));
            }
        }
        return resultMap;
    }


}
