package com.tzy.s.wx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tzy.s.wx.common.Common;
import com.tzy.s.wx.dto.AppletsSessionInfo;
import com.tzy.s.wx.dto.Result;
import com.tzy.s.wx.service.WxAppletsApi;
import com.tzy.s.wx.util.HttpClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;

/**
 * 微信小程序接口
 */
@Slf4j
@Service
public class WxAppletsApiImpl implements WxAppletsApi {

    private Common common = new Common();
    //code2Session GET
    private static String CODE_T_SESSION = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
    //get accesstoken
    private static String GET_ACCESSTOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";

    /**
     * 獲取zccess token
     * @param appid
     * @param secret
     * @return
     */
    @Override
    public Result getAccessToken(String appid,String secret){
        if(StringUtils.isEmpty(appid))return Result.error(-1,"appid can't bull");
        if(StringUtils.isEmpty(secret))return Result.error(-1,"secret can't bull");
        String url = MessageFormat.format(GET_ACCESSTOKEN, appid, secret);
        return common.getAccesstoken(url);
    }

    /**
     * session
     * @param appid
     * @param code
     * @param secret
     * @return
     */
    @Override
    public Result code2Session(String appid,String secret ,String code){
        if(StringUtils.isEmpty(appid))return Result.error(-1,"appid can't null");
        if(StringUtils.isEmpty(secret))return Result.error(-1,"secret can't null");
        if(StringUtils.isEmpty(code))return Result.error(-1,"code can't null");
        String url = MessageFormat.format(CODE_T_SESSION, appid, secret, code);
        String ret = HttpClient.httpsRequest(url, "GET", null);
        if(StringUtils.isEmpty(ret)) return Result.error(-1,"请求失败");
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            AppletsSessionInfo appletsSessionInfo = JSONObject.toJavaObject(retJson,AppletsSessionInfo.class);
            return appletsSessionInfo;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(-1,"请求异常，请联系开发人员");
        }
    }

    /**
     * code 換取code
     * @param appid
     * @param secret
     * @param code
     * @return
     */
    @Override
    public Result code2Openid(String appid,String secret ,String code){
        return this.code2Session(appid,secret,code);
    }

}
