package com.rdiot.yx485.util;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.king.zxing.util.LogUtils;
import com.rdiot.yx485.bean.DefHomeRoomBean;
import com.rdiot.yx485.bean.HomeBase;
import com.rdiot.yx485.bean.PersonBean;
import com.rdiot.yx485.login.LoginAccountBean;
import com.rdiot.yx485.login.LoginReplyBean;
import com.tencent.mmkv.MMKV;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class LocalCache {
    private static final String TAG = "LocalCache";
    private static final MMKV mLocalDB = MMKV.defaultMMKV();
    private static final String key_token = "token";
    private static final String key_expires_time = "expiresTime";
    private static final String key_user_info = "userInfo";
    private static final String key_phone = "phone";
    private static final String key_password = "password";
    private static final String key_home_id = "homeId";
    private static final String KEY_HOME_LIST = "home_list";
    private static final String KEY_DEFAULT_HOME = "default_home";

    public static void saveLoginAccount(String phone, String pwd) {
        mLocalDB.encode(key_phone, phone);
        mLocalDB.encode(key_password, pwd);
    }

    public static LoginAccountBean getLoginAccount() {
        LoginAccountBean bean = new LoginAccountBean();
        bean.phone = mLocalDB.decodeString(key_phone, "");
        bean.password = mLocalDB.decodeString(key_password, "");
        return bean;
    }

    public static void saveLoginInfo(LoginReplyBean.DataBean loginInfo) {
        if (loginInfo == null) {
            return;
        }

        String token = String.format("%s %s", loginInfo.token_type, loginInfo.access_token);
        mLocalDB.encode(key_token, token);
        mLocalDB.encode(key_expires_time, loginInfo.expires_at);
    }

    public static String getToken() {
        String token = mLocalDB.decodeString(key_token, "");
        LogUtils.d(token);
        return token;
    }

    public static boolean verifyLoginState() {
        String token = getToken();
        if (TextUtils.isEmpty(token)) {
            return false;
        }

        long expiresTime = mLocalDB.decodeLong(key_expires_time, 0);
        long currentTime = System.currentTimeMillis() / 1000;
        //过期时间大于当前时间，则当前登录有效
        return expiresTime > currentTime;
    }

    public static void saveUserInfo(PersonBean.UserInfo userInfo) {
        if (userInfo == null) {
            return;
        }

        saveDefaultHomeId(userInfo.default_home_id);

        String json = new Gson().toJson(userInfo);
        mLocalDB.encode(key_user_info, json);
    }

    public static void saveDefaultHomeId(String homeId) {
        if (TextUtils.isEmpty(homeId)) {
            return;
        }
        mLocalDB.encode(key_home_id, homeId);
    }

    public static String getDefaultHomeId() {
        String homeId = mLocalDB.decodeString(key_home_id, "");
        if (TextUtils.isEmpty(homeId)) {
            HomeBase info = getDefaultHome();
            if (info != null) {
                homeId = info.getId();
            }
        }
        LogUtils.d(homeId);
        return homeId;
    }

    public static PersonBean.UserInfo getUserInfo() {
        String json = mLocalDB.decodeString(key_user_info, "");
        if (TextUtils.isEmpty(json)) {
            return null;
        }

        PersonBean.UserInfo userInfo = null;
        try {
            userInfo = new Gson().fromJson(json, PersonBean.UserInfo.class);
        } catch (JsonSyntaxException e) {
            Log.e(TAG, "getUserInfo: ", e);
        }
        return userInfo;
    }

    public static void saveCityList(List<DefHomeRoomBean.DataBean.CityInfo> list) {
        if (list == null || list.isEmpty()) {
            return;
        }

        String json = new Gson().toJson(list);
        LogUtils.d("saveCityList:" + json);
        mLocalDB.encode("cityList", json);
    }

    public static List<DefHomeRoomBean.DataBean.CityInfo> getCityList() {
        List<DefHomeRoomBean.DataBean.CityInfo> list = new ArrayList<>();
        String json = mLocalDB.decodeString("cityList", "");
        if (TextUtils.isEmpty(json)) {
            return list;
        }

        Type type = new TypeToken<List<DefHomeRoomBean.DataBean.CityInfo>>() {
        }.getType();
        list = new Gson().fromJson(json, type);
        return list;
    }

    public static void logout() {
        mLocalDB.reKey(key_expires_time);
        mLocalDB.reKey(key_token);
        mLocalDB.reKey(key_user_info);
    }

    public static void saveCid(String cid) {
        LogUtils.d("saveCid: " + cid);
        mLocalDB.encode("cid", cid);
    }

    public static String getCid() {
        return mLocalDB.decodeString("cid", "");
    }

    /**
     * 保存默认家庭
     */
    public static void saveDefaultHome(HomeBase home) {
        if (home == null) return;
        saveDefaultHomeId(home.getId());
        String json = new Gson().toJson(home);
        mLocalDB.encode(KEY_DEFAULT_HOME, json);
    }

    /**
     * 获取默认家庭
     */
    public static HomeBase getDefaultHome() {
        String json = mLocalDB.decodeString(KEY_DEFAULT_HOME, "");
        if (TextUtils.isEmpty(json)) return null;
        return new Gson().fromJson(json, HomeBase.class);
    }

    /**
     * 保存家庭列表
     */
    public static void saveHomeList(List<HomeBase> homeList) {
        if (homeList == null) return;
        String json = new Gson().toJson(homeList);
        mLocalDB.encode(KEY_HOME_LIST, json);
    }

    /**
     * 获取家庭列表
     */
    public static List<HomeBase> getHomeList() {
        String json = mLocalDB.decodeString(KEY_HOME_LIST, "");
        if (TextUtils.isEmpty(json)) return new ArrayList<>();
        Type type = new TypeToken<List<HomeBase>>() {
        }.getType();
        return new Gson().fromJson(json, type);
    }

    public static void saveAgree() {
        mLocalDB.encode("agree", true);
    }

    public static boolean isAgree() {
        return mLocalDB.decodeBool("agree", false);
    }

    public static void saveDeviceListType(int type) {
        mLocalDB.encode("deviceListType", type);
    }

    //1是list 2 是 grid
    public static int getDeviceListType() {
        return mLocalDB.decodeInt("deviceListType", 1);
    }


    /**
     * 清除家庭相关缓存
     */
    public static void clearHomeCache() {
        mLocalDB.reKey(KEY_HOME_LIST);
        mLocalDB.reKey(KEY_DEFAULT_HOME);
    }
}
