package com.sjkj.base_lib.camera.dh;

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

import androidx.lifecycle.LifecycleOwner;

import com.android.business.adapter.DataAdapterImpl;
import com.android.business.entity.EnvironmentInfo;
import com.android.business.entity.LoginType;
import com.android.business.entity.UserInfo;
import com.android.business.exception.BusinessException;
import com.sjkj.base_lib.app.BaseApp;
import com.sjkj.base_lib.camera.dh.async.AsyncBuilder;
import com.sjkj.base_lib.camera.dh.bean.DhServiceBeanInfo;
import com.sjkj.base_lib.entity.Params;
import com.sjkj.base_lib.net.domain.interactor.ProcessErrorSubscriber;
import com.sjkj.base_lib.net.request.DhServiceInfoRequest;
import com.sjkj.base_lib.utils.ToastUtils;
import com.tencent.mmkv.MMKV;

import java.util.UUID;

public class DhUtils {
    private static MMKV mmkv = MMKV.defaultMMKV();
    public static final String IP_DH_KEY = "dh_ip";
    public static final String PORT_DH_KEY = "dh_port";
    public static final String USERNAME_DH_KEY = "dh_username";
    public static final String PASSWORD_DH_KEY = "dh_password";

    public static String ip = "202.98.7.130";
    public static String port = "7905";
    public static String username = "system";
    public static String password = "Admin123";

    public static final String DH_UUID = "uuid";
    public static final String DH_GROUP_ID = "group_id";
    private static DhUtils instance;
    private String mUuid = "";
    private DhServiceInfoRequest request = new DhServiceInfoRequest(BaseApp.getInstance());

    public static DhUtils getInstance() {
        if (instance == null) {
            synchronized (DhUtils.class) {
                if (instance == null) {
                    instance = new DhUtils();
                }
            }
        }
        return instance;
    }

    private OnDhListener listener;

    public interface OnDhListener {
        void callBack();
    }

    private OnDhIpPortSettingListener ipPortSettingListener;

    public interface OnDhIpPortSettingListener {
        void onSuccess();
    }

    public void setIpPortSettingListener(OnDhIpPortSettingListener ipPortSettingListener) {
        this.ipPortSettingListener = ipPortSettingListener;
    }

    public void initDhSDK(LifecycleOwner life, OnDhListener listener) {
        request.setParams(new Params());
        request.execute(new ProcessErrorSubscriber<DhServiceBeanInfo>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
//                ToastUtils.show("获取服务器地址失败");
            }

            @Override
            public void onNext(DhServiceBeanInfo beanInfo) {
                super.onNext(beanInfo);
                if (beanInfo != null) {
                    ip = beanInfo.getLoginIpApp();
                    port = beanInfo.getLoginPortApp();
                    username = beanInfo.getUserNameApp();
                    password = beanInfo.getUserPwdApp();
//                    Log.e("XXC",ip+"_"+port);
                    initDhSdk2(life, listener);
                }
            }
        });
    }

    private void initDhSdk2(LifecycleOwner life, OnDhListener listener) {
        this.listener = listener;
        initEnvironment();
        AsyncBuilder.createTask(new AsyncBuilder.BusinessTask<UserInfo>() {
            @Override
            public UserInfo doInBackground() throws Exception {
                if (TextUtils.isEmpty(mUuid)) {
                    mUuid = UUID.randomUUID().toString();
                    mmkv.encode(DH_UUID, mUuid);
                }
                DataAdapterImpl.getInstance().initServer(ip, Integer.parseInt(port));
                return DataAdapterImpl.getInstance().login(username, password, "1", mUuid, LoginType.TYPE_APP_CHINESE);
            }
        }).resultInMain(life, new AsyncBuilder.ResultListener<UserInfo>() {
            @Override
            public void onSuccess(UserInfo userInfo) {
                Log.e("dh_login_success", "登录成功_ip:"+ip+"_port:"+ port+"_username:"+ username+"_password:"+  password);
                ToastUtils.show("登录成功");
                setUserInfo(userInfo);
                saveLoginData(ip, port, username, password);
                if (listener != null)
                    listener.callBack();
            }

            @Override
            public void onError(BusinessException e) {
                ToastUtils.show("登录失败");
//                ToastUtils.show(e.errorDescription);
                Log.e("dh_login_error", e == null ? "null" : e.getLocalizedMessage());
            }
        });
    }


    private void initEnvironment() {
        try {
            //初始化平台SDK
            DataAdapterImpl.getInstance().createDataAdapter("com.android.business.adapter.DataAdapterVCloudImpl");
        } catch (BusinessException e) {
            e.printStackTrace();
        }
        EnvironmentInfo environmentInfo = new EnvironmentInfo();
        //设置是否使用https请求
        environmentInfo.setHttps(true);
        try {
            //设置当前版本名称 VersionName
            environmentInfo.setVersionName(BaseApp.getInstance().getPackageManager().getPackageInfo(BaseApp.getInstance().getPackageName(), 0).versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        //设置当前语言
        environmentInfo.setLanguage(BaseApp.getInstance().getResources().getConfiguration().locale.getLanguage());
        environmentInfo.setApplication(BaseApp.getInstance());
        //设置当前客户端类型 （选填）
        environmentInfo.setClientType("Android");
        try {
            DataAdapterImpl.getInstance().initEnvironmentInfo(environmentInfo);
            setEnvironmentInfo(environmentInfo);
        } catch (BusinessException e) {
            e.printStackTrace();
        }
    }


    private UserInfo mUserInfo;
    private EnvironmentInfo mEnvironmentInfo;

    public UserInfo getUserInfo() {
        return mUserInfo;
    }

    public void setUserInfo(UserInfo mUserInfo) {
        this.mUserInfo = mUserInfo;
    }

    public EnvironmentInfo getEnvironmentInfo() {
        return mEnvironmentInfo;
    }

    public void setEnvironmentInfo(EnvironmentInfo mEnvironmentInfo) {
        this.mEnvironmentInfo = mEnvironmentInfo;
    }

    /**
     * 保存ip和端口号以及登录成功的用户名和密码
     */
    public void saveLoginData(String ip, String port, String username, String password) {
        String restToken = (String) mUserInfo.getExtandAttributeValue("token");
        mEnvironmentInfo.setRestToken(restToken);
        mmkv.encode(IP_DH_KEY, ip);
        mmkv.encode(PORT_DH_KEY, port);
        mmkv.encode(USERNAME_DH_KEY, username);
        mmkv.encode(PASSWORD_DH_KEY, password);
    }

    public static String getIp() {
        return mmkv.decodeString(IP_DH_KEY);
    }

    public static String getPort() {
        return mmkv.decodeString(PORT_DH_KEY);
    }

    public static String getUsername() {
        return mmkv.decodeString(USERNAME_DH_KEY);
    }

    public static String getPassword() {
        return mmkv.decodeString(PASSWORD_DH_KEY);
    }
}
