package com.tax.token.thirdService.impl;

import com.alibaba.fastjson.JSONObject;
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.tax.token.utils.NUONUOUtil;
import com.tax.token.utils.NationUtil;
import com.yxcheng.token.common.cache.RedisService;
import com.yxcheng.token.constants.RedisContants;
import com.yxcheng.token.utils.SpringUtil;
import com.yxcheng.token.utils.UUIDGenerator;
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 GetTokenFromNUONUO implements TokenThirdServiceI {

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

    @Override
    public Map<String, Object> invoke(String uuIdFlag, TkToken tkToken, TkZoneInfo tkZoneInfo, TkServer tkServer, boolean isFirst) throws IOException, HttpException {

        String uuidFlag = UUIDGenerator.generate();
        RedisService redisService = SpringUtil.getBean(RedisService.class);
        String taxNo = tkToken.getTaxno();
        String zoneCode = tkToken.getZoneCode();
        logger.info(uuidFlag + " taxno is " + taxNo + " is start...");
        JSONObject chJson = NUONUOUtil.getClientHello(uuidFlag, taxNo,tkServer);
        logger.info(uuidFlag + " taxno is " + taxNo + " , getClientHello result is " + chJson.toString());
        String helloStr =  chJson.getJSONObject("result").getString("helloStr");

        JSONObject serverAuthJson =  NationUtil.firstLogin(uuidFlag,taxNo,helloStr,zoneCode);
        logger.info(uuidFlag + " taxno is " + taxNo + " , firstLogin result is " + serverAuthJson.toString());

        JSONObject clientAuthJson = NUONUOUtil.getClientAuth(uuidFlag, taxNo, serverAuthJson.getString("key2"),tkServer);
        logger.info(uuidFlag + " taxno is " + taxNo + " , getClientAuth result is " + clientAuthJson.toString());

        String authStr = clientAuthJson.getJSONObject("result").getString("authStr");
        redisService.set(RedisContants.NUONUO_TOKEN_TYPE + tkToken.getTaxno(),clientAuthJson.getJSONObject("result").getString("type"));
        String token = NationUtil.secondLogin(uuidFlag, taxNo,authStr,zoneCode,serverAuthJson.getString("key3"),tkToken.getSecert());
        logger.info(uuidFlag + " taxno is " + taxNo + " , secondLogin result is " + token);

        Map<String,Object> resultMap = new HashMap<>();
        if(StringUtils.isNotBlank(token)){
            resultMap.put("token",token);
            resultMap.put("code","0");
        }
        return resultMap;
    }


}
