package com.seeyon.apps.qrCodeForm.sso;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.weixin.manager.WechatUserManager;
import com.seeyon.apps.weixin.po.WechatUser;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.portal.sso.SSOLoginContext;
import com.seeyon.ctp.portal.sso.SSOLoginHandshakeAbstract;
import com.seeyon.ctp.util.HttpClientUtil;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.annotation.Inject;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 
 * @title: WechatQRHandShake
 * @description: 企业微信扫码发起单据
 * @date 2021/11/30  9:47
 */
public class WechatQRHandShake extends SSOLoginHandshakeAbstract {

    private static final Log log = CtpLogFactory.getLog(WechatQRHandShake.class);
    //企业微信appid
    public static final String _CORPID = AppContext.getSystemProperty("qrCodeForm.corpid");
    //企业微信corpsecret
    public static final String _corpsecret = AppContext.getSystemProperty("qrCodeForm.corpsecret");
    //验证方式
    public static final String handshakeType = AppContext.getSystemProperty("qrCodeForm.handshakeType");

    @Inject
    public WechatUserManager wechatUserManager;
    @Autowired
    private  OrgManager orgManager;
    @Override
    public String handshake(String s) {
        log.info("--进入企业微信回调接口!");
        HttpServletRequest request = AppContext.getRawRequest();
        String code =request.getParameter("code");

        String corpid =_CORPID;
        String corpsecret =_corpsecret;
        
        log.info("获取access接口url:https://qyapi.weixin.qq.com/cgi-bin/gettoken?"+"corpid="+corpid+"&corpsecret="+corpsecret);
        String access = null;
        try {
            access = HttpClientUtil.getContent("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret);
            log.info("获取access接口返回:"+access);
            if(access==null || access.equals("")){
                log.error("--未获取到access!");
                return null;
            }

            JSONObject jsonObject = JSONObject.parseObject(access);
            if(jsonObject==null){
                log.error("--未获取到access的jsonObject!");
                return null;
            }

            String accessToken = (String)jsonObject.get("access_token");
            if(accessToken==null || accessToken.equals("")){
                log.error("--未获取到accessToken!");
                return null;
            }

            log.info("--获取访问用户身份接口url:https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?"+"access_token=" + accessToken + "&code=" + code);
            String user =  HttpClientUtil.getContent("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + accessToken + "&code=" + code);
            log.info("--获取访问用户身份接口返回值：" + user);
            if(user==null || user.equals("")){
                log.error("--未获取到user!");
                return null;
            }

            JSONObject userJson = JSONObject.parseObject(user);
            if(userJson==null){
                log.error("--未获取到user的jsonObject!");
                return null;
            }

            String userid = userJson.getString("UserId");
            if(userid==null || userid.equals("")){
                log.error("--未获取到userid!");
                return null;
            }
            String Loginname = null;
//            if("1".equals(handshakeType)){//使用标准模块的微信绑定
            if(false){ //企业微信、微协同绑定等信息存储在微协同云服务中，废弃逻辑
                WechatUser wechatUser =wechatUserManager.getWechatUserByUserIdAndcorpId(userid,corpid);
                Loginname=wechatUser.getXtLoginName();
            }else {//自定义如何根据微信得用户id获取OA的用户
                log.info("--获取成员接口url:https://qyapi.weixin.qq.com/cgi-bin/user/get?"+"access_token=" + accessToken + "&userid=" + userid);
                String member =  HttpClientUtil.getContent("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken + "&userid=" + userid);
                log.info("获取成员接口返回值:" + member);
                if(member==null || member.equals("")){
                    log.error("--未获取到member!");
                    return null;
                }

                JSONObject memberJson = JSONObject.parseObject(member);
                if(userJson==null){
                    log.error("--未获取到member的jsonObject!");
                    return null;
                }

                String mobile = memberJson.getString("mobile");
                if(mobile==null || mobile.equals("")){
                    log.error("--未获取到mobile!");
                    return null;
                }
                List<V3xOrgMember> memberList=orgManager.getMemberListByMobile(mobile,null);
                Loginname = memberList!=null?memberList.get(0).getLoginName():null;
            }
            if(Loginname ==null || Loginname.equals("")){
                log.error("--未获取到loginName!");
                return null;
            }
            return Loginname;

        } catch (Exception e) {
            log.error("获取微信验证失败",e);
        }

        return null;
    }

    @Override
    public void logoutNotify(String s) {

    }

    @Override
    public String getToUrl(HttpServletRequest req, SSOLoginContext ssoLoginContext, String ticket) {
        return req.getParameter("tourl");
    }
}
