package com.sobot.common.login;

import android.content.Context;
import android.text.TextUtils;

import com.sobot.common.login.callback.SobotResultBlock;
import com.sobot.common.login.callback.SobotResultCode;
import com.sobot.common.login.db.HostManager;
import com.sobot.common.login.db.LoginUserInfoUtils;
import com.sobot.common.login.db.ServiceInfoManager;
import com.sobot.common.login.model.HostModel;
import com.sobot.common.login.model.LoginUserEntity;
import com.sobot.common.login.model.ServiceFunctionVoModel;
import com.sobot.common.login.model.SobotServiceInfoModel;
import com.sobot.gson.SobotGsonUtil;
import com.sobot.network.apiUtils.SobotBaseCode;
import com.sobot.network.apiUtils.SobotHttpUtils;
import com.sobot.network.http.HttpBaseUtils;
import com.sobot.utils.SobotSharedPreferencesUtil;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * app 登录合并类
 */
public class SobotLoginTools {

    /**
     * 获取登录信息
     */
    public static LoginUserEntity getLoginInfo() {
        return LoginUserInfoUtils.getUser();
    }

    /**
     * 获取坐席信息
     */
    public static SobotServiceInfoModel getServiceInfoModel() {
        return ServiceInfoManager.getInstance().getInfo();
    }

    /**
     * 获取域名信息
     */
    public static HostModel getHostModel() {
        return HostManager.getInstance().getHost();
    }

    // 执行APP登录接口
    public static void doAppLogin(final Object cancelTag, final Context mContext, final String host,long timeout, Map<String, Object> params, Map<String, String> headers, final SobotResultBlock resultBlock) {
        SobotHttpUtils.doPost(cancelTag, host + "/chat-sdk/sdk/admin/v1/login.action", timeout,params, headers, new HttpBaseUtils.StringCallBack() {
            @Override
            public void onResponse(String result) {
                if (!TextUtils.isEmpty(result)) {
                    SobotBaseCode<LoginUserEntity> baseModel = SobotGsonUtil.jsonToBeans(result, new com.sobot.gson.reflect.TypeToken<SobotBaseCode<LoginUserEntity>>() {
                    }.getType());
                    if (baseModel != null) {
                        //登录接口和获取坐席信息权限接口都成功才算真正登录成功
                        if ("1".equals(baseModel.getCode()) && baseModel.getData() != null) {
                            LoginUserInfoUtils.setUser(baseModel.getData());
                            getLoginUserInfo(cancelTag, mContext, baseModel.getData(), host, baseModel.getData().getToken(), resultBlock);
                        } else {
                            resultBlock.resultBolok(SobotResultCode.CODE_FAILED, baseModel.getMsg(), baseModel.getCode());
                        }
                    } else {
                        resultBlock.resultBolok(SobotResultCode.CODE_FAILED, "接口请求结果为空", null);
                    }
                }
            }

            @Override
            public void onError(Exception e, String msg, int responseCode) {
                resultBlock.resultBolok(SobotResultCode.CODE_FAILED, msg, null);
            }

            @Override
            public void inProgress(int progress) {

            }
        });
    }

    /**
     * 调用座席接口
     *
     * @param cancelTag
     * @param mContext
     * @param host
     * @param token
     * @param resultBlock 返回坐席信息
     */
    public static void getLoginUserInfo(final Object cancelTag, final Context mContext, String host, final String token, final SobotResultBlock resultBlock) {
        getLoginUserInfo(cancelTag, mContext, null, host, token, resultBlock);
    }

    /**
     * 调用座席接口
     *
     * @param cancelTag
     * @param mContext
     * @param loginUser   如果不为空 resultBlock返回就是这个；如果为空，返回坐席信息
     * @param host
     * @param token
     * @param resultBlock
     */
    public static void getLoginUserInfo(final Object cancelTag, final Context mContext, final LoginUserEntity loginUser, String host, final String token, final SobotResultBlock resultBlock) {
        final String url = host + "/basic-config-service/consoleAuth/queryAppAgentMenus";
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("temp-id", token);
        SobotHttpUtils.doGet(cancelTag, url, null, headerMap, new HttpBaseUtils.StringCallBack() {
            @Override
            public void onResponse(String result) {
                if (!TextUtils.isEmpty(result)) {
                    try {
                        org.json.JSONObject resonseObj = new org.json.JSONObject(result);
                        String retCode = resonseObj.optString("retCode");
                        String retMsg = resonseObj.optString("retMsg");
                        if ("000000".equals(retCode)) {
                            SobotServiceInfoModel serviceInfoModel = SobotGsonUtil.jsonToBean(resonseObj.optString("item"), SobotServiceInfoModel.class);
                            List<ServiceFunctionVoModel> functions = new ArrayList<>();
                            JSONArray items = resonseObj.optJSONArray("items");
                            getListByObj(functions, items);
                            serviceInfoModel.setFunctionStr(functions);
                            //保存在数据库
                            ServiceInfoManager.getInstance().saveInfo(serviceInfoModel);
                            SobotSharedPreferencesUtil.getInstance(mContext).put(SobotLoginConstant.SOBOT_LOGIN_USER_INFO, serviceInfoModel);
                            if (loginUser != null) {
                                resultBlock.resultBolok(SobotResultCode.CODE_SUCCEEDED, "登录成功", loginUser);
                            } else {
                                resultBlock.resultBolok(SobotResultCode.CODE_SUCCEEDED, "登录成功", serviceInfoModel);
                            }
                        } else {
                            resultBlock.resultBolok(SobotResultCode.CODE_FAILED, retMsg == null ? "" : retMsg, null);
                        }
                    } catch (Exception e) {
                        resultBlock.resultBolok(SobotResultCode.CODE_FAILED, "", null);
                    }
                }
            }

            @Override
            public void onError(Exception e, String msg, int responseCode) {
                resultBlock.resultBolok(SobotResultCode.CODE_FAILED, msg, null);
            }

            @Override
            public void inProgress(int progress) {

            }
        });
    }


    private static void getListByObj(List<ServiceFunctionVoModel> list, JSONArray items) {
        try {
            if (null != items) {
                for (int i = 0; i < items.length(); i++) {
                    org.json.JSONObject o = items.getJSONObject(i);
                    ServiceFunctionVoModel functionVoModel = SobotGsonUtil.jsonToBean(o.toString(), ServiceFunctionVoModel.class);
                    if (functionVoModel != null) {
                        list.add(functionVoModel);
                    }
                    boolean hasChildren = o.optBoolean("hasChildren", false);
                    if (hasChildren) {
                        if (null != o.optJSONArray("children")) {
                            JSONArray childrens = o.getJSONArray("children");
                            getListByObj(list, childrens);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
