package org.shunt.service;

import java.io.UnsupportedEncodingException;
import java.util.*;

import cn.hutool.http.HttpUtil;
import com.admin.major.domain.StudentInfo;
import com.google.common.collect.ImmutableMap;
import org.shunt.common.JWTAuthUtil;
import org.shunt.common.XmoseAssert;
import org.shunt.contorller.request.LoginRequest;
import org.shunt.contorller.response.AppDTO;
import org.shunt.mapper.ShuntMapper;
import org.shunt.service.bean.WechatAccess;
import org.shunt.service.bean.WechatExtUserInfo;
import org.shunt.service.bean.WechatInfo;
import org.shunt.service.bean.WechatUserDetailInfo;
import org.shunt.service.bean.WechatUserInfo;
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.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;

import lombok.NonNull;

import javax.servlet.http.HttpServletRequest;

/**
 * 微信逻辑接口实现
 */
@Service
public class WechatService {
    private static final Logger log = LoggerFactory.getLogger(WechatService.class);
    @Autowired
    private ShuntMapper mapper;

    @Value("${env:prod}")
    private String env;

    /**
     * 获取微信userId
     *
     * @return
     */
    public WechatUserDetailInfo getWechatUserInfo(LoginRequest loginRequest) {
        // 微信网页授权access_token信息
        initWechatAccess(loginRequest.getAppId());
        // 获取微信userId
        return getWechatUserInfo(loginRequest.getCode());
    }


    private static final String WECHAT_ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s";

    private WechatAccess wechatAccess = null;
    /**
     * 微信网页授权access_token信息
     * @param appId
     * @return
     */
    private void initWechatAccess(String appId) {
        // 如果当前存在token并且未过期,返回token
        if (wechatAccess != null && wechatAccess.getExpiresIn() > System.currentTimeMillis()/1000) {
            return ;
        }
        AppDTO app = mapper.getApp(appId);
        if(app == null){
            XmoseAssert.configNotice("未配置appId数据");
        }
        // 获取token
        String resultString = HttpUtil.get(String.format(WECHAT_ACCESS_TOKEN_URL, app.getAppId(), app.getSecret()));
        log.info("resultString:{}", resultString);

        JSONObject wechatAccessJson = JSONObject.parseObject(resultString);
        wechatAccess = new WechatAccess();
        wechatAccess.setAccessToken(wechatAccessJson.getString("access_token"));
        wechatAccess.setCreateTime(new Date());
        wechatAccess.setExpiresIn(System.currentTimeMillis()/1000+wechatAccessJson.getLong("expires_in")-200);
    }


    private static final String WECHAT_USERINFO_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=%s&code=%s";
    private static final String WECHAT_USERPHONE_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=%s&userid=%s";

    /**
     * 获取微信个人用户信息（学号）
     *
     * @param
     * @return
     */
    private WechatUserDetailInfo getWechatUserInfo(String code) {
        // 请求
        String userInfoResult = HttpUtil.get(String.format(WECHAT_USERINFO_URL, wechatAccess.getAccessToken(), code));
        log.info("wechat getUserInfo result: {}", userInfoResult);
        if (!StringUtils.hasLength(userInfoResult)) {
            return null;
        }
        try {
            userInfoResult = new String(userInfoResult.getBytes("ISO-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 微信用户信息转化
        log.info("userInfoResult:{}", userInfoResult);
        WechatUserInfo userInfo = JSONObject.parseObject(userInfoResult, WechatUserInfo.class);
        log.info("userInfo:{}", userInfo);
        String userId = "";

        if (StringUtils.hasLength(userInfo.getUserId())) {
            userId = userInfo.getUserId();
        }
//        // 微信用户信息转化
//        WechatExtUserInfo extUserInfo = JSONObject.parseObject(userInfoResult, WechatExtUserInfo.class);
//        if (StringUtils.hasLength(extUserInfo.getExternalUserid())) {
//            userId = extUserInfo.getExternalUserid();
//        }
//
//        String strReturn = HttpUtil.get(String.format(WECHAT_USERPHONE_URL, wechatAccess.getAccessToken(), userId));
//        if (!StringUtils.hasLength(strReturn)) {
//            return null;
//        }
//        try {
//            strReturn = new String(strReturn.getBytes("ISO-8859-1"), "utf-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        log.info(">>>>" + strReturn);
//        WechatUserDetailInfo detailInfo = JSONObject.parseObject(strReturn, WechatUserDetailInfo.class);
//        log.info(">>>>" + detailInfo.toString());

        //TODO 将学号与openId关联起来  ,企业微信用户userId与openId可以一同看待

        return WechatUserDetailInfo.builder()
                .userid(userId)
                .jd(userId)
                .openId("")
                .build();
    }
}
