package com.tax.token.thirdService.impl;

import com.alibaba.fastjson.JSON;
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.HttpHelper;
import com.yxcheng.token.utils.JSONHelper;
import com.yxcheng.token.utils.ObjectUtil;
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 GetTokenFromDx implements TokenThirdServiceI {

    private static final Logger logger = LoggerFactory.getLogger(GetTokenFromDx.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 url = tkServer.getReqUrl() + "?taxno="+taxno;

        Map<String, Object> paramsMap = new HashMap<String, Object>();
        String resultStr = HttpHelper.postWithJson(url, JSON.toJSONString(paramsMap));
        logger.info("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("msg")));
            if("0".equals(resultStrMap.get("code"))){
                resultMap.put("token",resultStrMap.get("token"));
            } else {
                String code = ObjectUtil.fixNull(resultStrMap.get("code"));
                if(code.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("911303217825884778");

        tkServer.setReqUrl("http://jxseapi.ele-cloud.com/token/getToken");
        tkServer.setUserName("daxiang");

        GetTokenFromDx local = new GetTokenFromDx();
        System.out.println(local.invoke("aaa", tokenEntity,zoneInfo,tkServer,isFirst));

    }
}
