package com.gic.haoban.manage.service.util;

import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.ConfigService;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.GlobalVar;
import com.gic.commons.util.HttpClient;
import com.gic.haoban.manage.service.pojo.QwOpenResultBO;
import com.gic.haoban.manage.service.pojo.QwOpenResultInitBO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * https://www.showdoc.com.cn/1889765213630885/8704551724545128    密码:147258
 */
public class OpenUtils {

    private static Logger logger = LogManager.getLogger(OpenUtils.class);

    private static final String gicCallbackHost = GlobalVar.ctxPropertiesMap.get("haoban_service_host") + "/haoban-manage3-operation-web/qywx-msg-notice";

    private static String getHost() {
        return CustomSwitcher.qywx_open_host ;
    }

    public static ServiceResponse<QwOpenResultInitBO> init(Long qwUserId, boolean qrcodeFlag , String deverType) {
        JSONObject initJson = new JSONObject();
        if (null != qwUserId) {
            initJson.put("vid", qwUserId);
        }
        if(null != deverType) {
            initJson.put("deverType",deverType) ;
        }
        String initStr = HttpClient.sendPostJSON(String.format(getHost(), "init"), initJson.toJSONString(), "utf-8");
        logger.info("企微初始化,req={},{}", initJson.toJSONString(), initStr);
        QwOpenResultBO initResult = result(initStr);
        if (!initResult.isOk()) {
            return ServiceResponse.failure("9999", initResult.getErrmsg());
        }
        QwOpenResultInitBO initBO = JSONObject.parseObject(initResult.getData().toString(), QwOpenResultInitBO.class);
        String uuid = initBO.getUuid();
        // 设置回调
        setCallback(uuid);
        if (initBO.isIs_login()) {
            logger.info("客户端是登录中的={}", qwUserId);
            return ServiceResponse.success(initBO);
        }
        if (qrcodeFlag) {
            // 获取二维码
            ServiceResponse<QwOpenResultInitBO> response = getQrcode(uuid, initBO, 1);
            if (!response.isSuccess()) {
                return response;
            }
        }
        return ServiceResponse.success(initBO);
    }

    public static ServiceResponse<Void> checkCode(String uuid, String qrcodeKey, String validCode) {
        JSONObject json = new JSONObject();
        json.put("uuid", uuid);
        json.put("qrcodeKey", qrcodeKey);
        json.put("code", validCode);
        String backJson = HttpClient.sendPostJSON(String.format(getHost(), "CheckCode"), json.toJSONString(), "utf-8");
        logger.info("校验验证码={},uuid={}", backJson, uuid);
        QwOpenResultBO bo = result(backJson);
        if (!bo.isOk()) {
            return ServiceResponse.failure("9999", bo.getErrmsg());
        }
        return ServiceResponse.success();
    }

    public static void logout(String uuid) {
        JSONObject json = new JSONObject();
        json.put("uuid", uuid);
        String backJson = HttpClient.sendPostJSON(String.format(getHost(), "LoginOut"), json.toJSONString(), "utf-8");
        logger.info("退出={},uuid={}", backJson, uuid);
    }

    private static void setCallback(String uuid) {
        JSONObject json = new JSONObject();
        json.put("uuid", uuid);
        json.put("url", gicCallbackHost);
        String backJson = HttpClient.sendPostJSON(String.format(getHost(), "SetCallbackUrl"), json.toJSONString(), "utf-8");
        logger.info("设置回调={},uuid={}", backJson, uuid);
    }

    public static ServiceResponse<QwOpenResultInitBO> getQrcode(String uuid, QwOpenResultInitBO initBO, int times) {
        String req = "getQrCode";
        if (times == 2) {
            req = "SecondaryValidation";
        }
        JSONObject json = new JSONObject();
        json.put("uuid", uuid);
        String backJson = HttpClient.sendPostJSON(String.format(getHost(), req), json.toJSONString(), "utf-8");
        logger.info("获取qrcode={},uuid={},times={}", backJson, uuid, times);
        QwOpenResultBO initResult = result(backJson);
        if (!initResult.isOk()) {
            return ServiceResponse.failure("9999", initResult.getErrmsg());
        }
        QwOpenResultInitBO backBO = JSONObject.parseObject(initResult.getData().toString(), QwOpenResultInitBO.class);
        if (null == initBO) {
            return ServiceResponse.success(backBO);
        }
        initBO.setQrcode(backBO.getQrcode());
        initBO.setKey(backBO.getKey());
        initBO.setQrcode_data(backBO.getQrcode_data());
        return ServiceResponse.success(initBO);
    }

    private static QwOpenResultBO result(String json) {
        QwOpenResultBO bo = JSONObject.parseObject(json, QwOpenResultBO.class);
        return bo;
    }

    /**
     * 自动登录
     *
     * @param uuid
     */
    public static boolean autoLogin(String uuid) {
        JSONObject json = new JSONObject();
        json.put("uuid", uuid);
        String backJson = HttpClient.sendPostJSON(String.format(getHost(), "automaticLogin"), json.toJSONString(), "utf-8");
        logger.info("自动登录={},uuid={}", backJson, uuid);
        JSONObject resultJson = JSONObject.parseObject(backJson);
        int errcode = resultJson.getIntValue("errcode");
        if (errcode == 0) {
            logger.info("自动登录成功={}");
            return true;
        }
        return false;
    }

    /**
     * 判断账号是否登录中
     *
     * @param uuid
     * @return
     */
    public static boolean isLogin(String uuid) {
        JSONObject json = new JSONObject();
        json.put("uuid", uuid);
        String backJson = HttpClient.sendPostJSON(String.format(getHost(), "GetProfile"), json.toJSONString(), "utf-8");
        logger.info("获取当前账号详情={},uuid={}", backJson, uuid);
        JSONObject resultJson = JSONObject.parseObject(backJson);
        int errcode = resultJson.getIntValue("errcode");
        if (errcode == 500) {
            return false;
        }
        return true;
    }
}
