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.yonyou.einvoice.common.client.DefaultClient;
import com.yonyou.einvoice.common.client.EinvoiceGlobalParam;
import com.yonyou.einvoice.vatcheck.dto.requestdto.VatTokenReqDto;
import com.yonyou.einvoice.vatcheck.dto.responsetdto.VatTokenRespDto;
import com.yonyou.einvoice.vatcheck.request.VatTokenRequest;
import org.apache.http.HttpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

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

public class GetTokenFromYongyou implements TokenThirdServiceI {
    private static final Logger logger = LoggerFactory.getLogger(GetTokenFromYongyou.class);


    @Override
    public Map<String, Object> invoke(String uuIdFlag, TkToken tkToken, TkZoneInfo tkZoneInfo, TkServer tkServer, boolean isFirst) throws IOException, HttpException {
        InputStream is = new ClassPathResource("certificate/vatcheck.p12").getInputStream();
        EinvoiceGlobalParam globalparam = new EinvoiceGlobalParam(tkServer.getUserName(), tkServer.getPassword(), is, tkServer.getReqUrl());
        VatTokenReqDto reqDto = new VatTokenReqDto();
        reqDto.setNsrsbh(tkToken.getTaxno());
        VatTokenRequest request = new VatTokenRequest(globalparam, reqDto);
        VatTokenRespDto respDto = null;
        Map<String, Object> retMap = new HashMap<>();
        try {
            logger.info("yongyouyou "+globalparam.getAppid() +","+ globalparam.getPassword() + "," + globalparam.getUrl() + "," + globalparam.getFile());
            respDto = new DefaultClient().execute(request);
            logger.info("yongyouyou token:" + JSON.toJSONString(respDto));
            retMap.put("code",respDto.getCode());
            retMap.put("message",respDto.getMsg());
            if("0000".equals(respDto.getCode())){
                retMap.put("code","0");
                retMap.put("token",respDto.getToken());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return retMap;
    }


    public static void main(String[] args) throws IOException, HttpException {
        GetTokenFromYongyou utils = new GetTokenFromYongyou();
        TkToken tkToken = new TkToken();
        tkToken.setTaxno("91211100279309506B");

        TkServer server = new TkServer();
        server.setUserName("757f103c-52ca-4985-b8d0-050e486a88e6");
        server.setPassword("123456");
        server.setReqUrl("https://fapiao.yonyoucloud.com");

        utils.invoke("aaa",tkToken,null,server,true);

    }
}
