package com.efounder.chat.http;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.util.Log;

import com.efounder.chat.R;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.chat.utils.DeviceInfo;
import com.efounder.common.BaseRequestManager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.language.MultiLanguageUtil;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.socket.JFAuthManager;
import com.efounder.message.socket.JFSocketHandler;
import com.efounder.message.socket.JFSocketManager;
import com.efounder.util.AppContext;
import com.efounder.util.BaseDeviceUtils;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.MobilePushUtils;
import com.efounder.utils.ResStringUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;

/**
 * 消息服务登录管理
 */
public class WeChatHttpLoginManager implements JFSocketHandler.OnChannelActiveListener, BaseRequestManager.ReqCallBack<String> {
    private static final String TAG = "WeChatHttpLoginManager";
    private static volatile WeChatHttpLoginManager weChatHttpRequest;
    //消息tcp服务的 IP地址
    private String messageChannelIP = null;

    private String deviceVersion; //5.1
    private String deviceCompany;//meizu
    private String deviceModel;//m1metal
    private String appVersion = "";//1.25
    private String deviceId;
    private String LoginExp;
    private String locale = "";//语言国家
    //是否支持推送 0：不支持， 1：支持
    private String supportPush = "0";
    //华为小米推送的token
    private String deviceToken = "";
    private final String deviceClass = "phone";
    private Context context;
    private List<LoginListener> loginListenerList = new ArrayList<>();


    public static WeChatHttpLoginManager getInstance(Context context) {
        if (weChatHttpRequest == null) {
            synchronized (WeChatHttpLoginManager.class) {
                if (weChatHttpRequest == null) {
                    weChatHttpRequest = new WeChatHttpLoginManager(context);
                }
            }
        }
        return weChatHttpRequest;
    }

    private WeChatHttpLoginManager(Context context) {
        this.context = AppContext.getInstance();
    }

    public void httpLogin(final String userId, final String password) {
        if (("0".equals(userId) && "0".equals(password)) || !EnvSupportManager.isSupportIM()) {
            //TODO 0,0不登录了 或者不支持IM
            return;
        }

        //如果连接活着，直接return，不再登陆，否则会出现多终端登陆现象
        if (JFMessageManager.isChannelActived()) {
            for (LoginListener loginListener : loginListenerList) {
                if (loginListener != null) {
                    loginListener.onLoginSuccess();
                }
            }
            return;
        }
        //1.登录
        getDeviceInfo();//获取设备信息
        //2.判断是否支持推送
        if (MobilePushUtils.isSupportPush()) {
            supportPush = "1";
            //支持推送，判断如果是华为
            //if (MobilePushUtils.isSupportHuaWeiPush()) {
            //华为手机获取token 在进行操作
            CommonThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    //获取token，如果没有，表示没请求下来 等待2s,如果还没有，使用上一次的token(通常不会失效)
                    try {
                        deviceToken = EnvironmentVariable.getProperty("pushToken", "");
                        if (deviceToken.equals("")) {
                            Thread.sleep(2000);
                            deviceToken = EnvironmentVariable.getProperty("pushToken", "");
                            if ("".equals(deviceToken)) {
                                deviceToken = EnvironmentVariable.getProperty("lastPushToken", "");
                            }
                        }
                        startLogin(userId, password);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            supportPush = "0";
            startLogin(userId, password);
        }
    }

    //开始登录
    private void startLogin(String userId, String password) {

        LoginExp = EnvironmentVariable.getProperty("LoginExp", "1");
        //参数
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("userId", userId);
        paramMap.put("passWord", password);
        paramMap.put("deviceType", "Android");
        paramMap.put("deviceVersion", deviceVersion);
        paramMap.put("deviceCompany", deviceCompany);
        paramMap.put("deviceModel", deviceModel);
        paramMap.put("appVersion", appVersion);
        paramMap.put("deviceId", deviceId);
        paramMap.put("deviceClass", deviceClass);
        paramMap.put("LoginExp", LoginExp);
        paramMap.put("supportPush", supportPush);
        paramMap.put("locale", locale);
        paramMap.put("subAppId", EnvironmentVariable.getProperty("subAppId", ""));
        if (MobilePushUtils.isSupportPush()) {
            paramMap.put("deviceToken", deviceToken);
        }

        JFCommonRequestManager.getInstance().requestGetByAsyn(TAG, GetHttpUtil.ROOTURL + "/IMServer/user/login", paramMap, this);
        //为了快速连接消息服务，如果有值，表示我们已经设置过消息服务器的信息了，直接连接消息服务
        if (messageChannelIP != null && !TextUtils.isEmpty(JFSocketManager.token)) {
            activateMessageChannel();
        }
    }


    /**
     * 激活消息通道
     */
    private void activateMessageChannel() {
        //检查用户权限信息
        JFAuthManager.getInstance().requestAuth();

        CommonThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                synchronized (WeChatHttpLoginManager.class) {
                    try {
                        if (JFMessageManager.isChannelActived()) {
                            Log.i(TAG, "消息服务连接正常，无需重连");
                            return;
                        }


                        //先关闭之前的TCP链接
                       // Log.e("MessageService","先关闭之前的TCP链接");
                       // JFSocketManager.getInstance().stop();
                        //设置监听 初始化通道
                        JFSocketManager socketManager = JFSocketManager.getInstance();
                        socketManager.setOnChannelActiveListener(WeChatHttpLoginManager.this);
                        socketManager.init();
                    } catch (Exception e) {
                        e.printStackTrace();
                        for (LoginListener loginListener : loginListenerList) {
                            if (loginListener != null) {
                                loginListener.onLoginFail("连接TCP失败...");
                            }
                        }
                    }
                }
            }
        });
    }


    /**
     * 添加登录监听
     *
     * @param loginListener
     */
    public void addLoginListener(LoginListener loginListener) {
        if (!loginListenerList.contains(loginListener)) {
            loginListenerList.add(loginListener);
        }
    }

    /**
     * 移除登陆监听
     *
     * @param loginListener
     */
    public void removeLoginListener(LoginListener loginListener) {
        if (loginListenerList.contains(loginListener)) {
            loginListenerList.remove(loginListener);
        }
    }

    @Override
    public void onReqSuccess(String response) {
        Log.i(TAG, "IM服务登录成功：" + response);
        try {
            JSONObject jsonObject = new JSONObject(response);
            String loginInfo = jsonObject.optString("login", "");
            if ("success".equals(loginInfo)) {//返回成功
                //登录--2.激活TCP消息通道

                //{"token":"ae2b11bd-7205-47e0-86fc-89e93b7f3bf5","server":["TCP:192.168.1.115:8000"],"login":"success"}
                //改为
                //{"sessionTime":1470714865121,"token":"a8824966-1377-435b-a6a6-9559d3bedccb",
                // "server":{"UDP":[],"TCP":["61.136.95.175:9690"]},"login":"success"}
                JFMessageManager.sessionTime = jsonObject.getLong("sessionTime");
                String token = jsonObject.getString("token");
                JSONObject serverJsonObject = jsonObject.getJSONObject("server");
                JSONArray jsonArrayTCP = serverJsonObject.getJSONArray("TCP");
                //随机获取一个ip和端口
                if (jsonArrayTCP.length() > 0) {
                    String serverString = jsonArrayTCP.getString(new Random().nextInt(jsonArrayTCP.length()));
                    String[] ip_port = serverString.split(":");
                    String ip = ip_port[0];
                    String port = ip_port[1];

                    JFSocketManager.token = token;
                    JFSocketManager.URL = ip;
                    JFSocketManager.PORT = Integer.parseInt(port);
                    //2.登录成功，激活通道
                    if (messageChannelIP == null || "".equals(JFSocketManager.token)) {
                        messageChannelIP = ip;
                        activateMessageChannel();
                    }
                }
            } else {
                imServerLoginFail();
            }
        } catch (Exception e) {
            e.printStackTrace();
            imServerLoginFail();
        }
    }

    /***
     * IM消息服务登录失败
     */
    private void imServerLoginFail() {
        for (LoginListener loginListener : loginListenerList) {
            if (loginListener != null) {
                loginListener.onLoginFail(ResStringUtil.getString(R.string.wechatview_amount_or_password_error));
            }
        }
    }

    @Override
    public void onReqFailed(String errorMsg) {
        Log.e(TAG, "onReqFailed:" + errorMsg);
        imServerLoginFail();
    }


    public interface LoginListener {

        void onLoginSuccess();

        void onLoginFail(String errorMsg);
    }


    @Override
    public void onChannelActiveSuccess() {
//		//向服务器发送一条注册消息
//		IMStruct001 im = new IMStruct001();
//		im.setClientId(JFSocketManagerService.token);
//		JFMessageManager.getInstance().sendStruce(im);
        //3.激活通道成功，表示真正登录成功，通知Activity跳转界面
        for (LoginListener loginListener : loginListenerList) {
            if (loginListener != null) {
                loginListener.onLoginSuccess();
            }
        }
    }

    @Override
    public void onChannelActiveFail() {
        for (LoginListener loginListener : loginListenerList) {
            if (loginListener != null) {
                loginListener.onLoginFail("onChannelActiveFail：激活通道失败");
            }
        }
    }

    public void getDeviceInfo() {
        //得到app版本号
        PackageManager pm = context.getPackageManager();//context为当前Activity上下文
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(context.getPackageName(), 0);

            deviceVersion = DeviceInfo.GetOs().replace(" ", "-"); //5.1
            deviceCompany = DeviceInfo.GetManufacturer().replace(" ", "-");//meizu
            deviceModel = DeviceInfo.GetModel().replace(" ", "-");//m1metal
            if (pi != null && pi.versionName != null) {
                appVersion = pi.versionName.replace(" ", "-");//1.25
            }
//            deviceId = ((TelephonyManager) context.getSystemService(TELEPHONY_SERVICE)).getDeviceId();
//            deviceId = PhoneUtils.getDeviceId();
            //TODO 20190815 换用新方式，需要存储权限才可以
            deviceId = BaseDeviceUtils.getUniqueId(AppContext.getInstance());
            if (deviceId == null) {
                deviceId = "";
            } else {
                deviceId = deviceId.replace(" ", "-");
            }
            //如果获取不到deviceID需要我们自己处理一下 deviceid 必须唯一
            if ("012345678912345".equals(deviceId) || "".equals(deviceId)) {
                deviceId = EnvironmentVariable.getProperty("lxDeviceId", "");
                if ("".equals(deviceId)) {
                    deviceId = UUID.randomUUID().toString();
                    EnvironmentVariable.setProperty("lxDeviceId", deviceId);
                }
            }

            locale = getSystemLocale();
            Log.i("deviceVersion", deviceVersion);
            Log.i("deviceModel", deviceModel);
            Log.i("deviceCompany", deviceCompany);
            Log.i("appVersion", appVersion);
            Log.i("deviceId", deviceId);

            EnvironmentVariable.setProperty("deviceVersion", deviceVersion);
            EnvironmentVariable.setProperty("deviceModel", deviceModel);
            EnvironmentVariable.setProperty("appVersion", appVersion);
            EnvironmentVariable.setProperty("deviceId", deviceId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前应用语言以及国家
     *
     * @return
     */
    public static String getSystemLocale() {
        Locale systemLocale = MultiLanguageUtil.getSetLanguageLocale(AppContext.getInstance());
        String locale = systemLocale.getLanguage();
        if (systemLocale.getCountry() != null && !TextUtils.isEmpty(systemLocale.getCountry())) {
            locale = locale + "_" + systemLocale.getCountry();
        }
        return locale;
    }
}
