package com.dgtly.wxportal.utils.qywxutils;

import com.alibaba.fastjson.JSONObject;
import com.dgtly.wxportal.exception.QyWeixinException;
import com.dgtly.common.utils.RedisUtil;
import com.dgtly.common.utils.http.HttpUtils;
import com.dgtly.wxportal.domain.WxQyUser;
import com.dgtly.wxportal.service.IWxQyUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * 企业微信工具类
 */
@Component
public class QyWxUserUtil {
    private static final Logger log = LoggerFactory.getLogger(QyWxUserUtil.class);

    @Autowired
    private IWxQyUserService wxQyUserService;

    @Autowired
    private QyWxAccessTokenUtil qyWxAccessTokenUtil;

    private String redis_qywxtoken_key="QYWX_ACCESS_TOKEN";


    public String getJsApiTicket(String url, String agent) {
        return qyWxAccessTokenUtil.getWXSign(url, agent);
    }

    /**
     * 获取企业微信用户的userId
     * @return
     */
    public JSONObject getUserId(String code) {
        String url = QyWxServiceUrl.USERINFO_URL.getformatUrl(qyWxAccessTokenUtil.getAccessToken(),code );
        JSONObject json;
        try{
            json = JSONObject.parseObject(HttpUtils.sendGet(url));
        }catch (Exception e){
            log.error("获取WX用户信息失败！",e);
            throw e;
        }

        Integer errcode = json.getInteger("errcode");
        if(errcode!=0){
            throw new QyWeixinException(errcode,url);
        }
        /*
        * 当用户为企业成员时返回示例如下：
        * {
        *   "errcode": 0,
        *   "errmsg": "ok",
        *   "UserId":"USERID",
        *   "DeviceId":"DEVICEID"
        *   }
        *
        * 非企业成员授权时返回示例如下：
        * {
        *   "errcode": 0,
        *   "errmsg": "ok",
        *   "OpenId":"OPENID",
        *   "DeviceId":"DEVICEID"
        *   }
        *
        * */

        return json;
    }

    public String getOauth2Url(String redirect,String state){
        return QyWxServiceUrl.OAUTH2_URL.getformatUrl(qyWxAccessTokenUtil.getCorpid(),redirect,state);
    }

    public WxQyUser gerUserDetail(String userId){
        String url =  QyWxServiceUrl.USERDETAILINFO_URL.getformatUrl(qyWxAccessTokenUtil.getAccessToken(),userId);

        String result = HttpUtils.sendGet(url);

        JSONObject json = JSONObject.parseObject(result);

        Integer errcode = json.getInteger("errcode");
        if(errcode!=0){
            throw new QyWeixinException(errcode,url);
        }
        WxQyUser wxQyUser = JSONObject.parseObject(result,WxQyUser.class);
        wxQyUser.setJson(result);
        return wxQyUser;

    }

}
