package com.sheep.gamegroup.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.sheep.gamegroup.model.api.BaseMessageConverter;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.ScreenShotConfig;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.service.FloatShotScreenService;
import com.sheep.jiuyan.samllsheep.utils.FileUtil;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;

import org.afinal.simplecache.ACache;
import org.afinal.simplecache.ApiKey;

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

import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import io.reactivex.schedulers.Schedulers;

import static android.app.Activity.RESULT_OK;

/**
 * Created by realicing on 2018/7/27.
 * realicing@sina.com
 */
public class DataUtil {
    public static final int PER_PAGE = 10;
    private static DataUtil instance;
    private static ACache aCache = ACache.get(SheepApp.getInstance());

    private DataUtil() {
        UserEntity cacheUser = getCacheResult(ApiKey.get_info, UserEntity.class);//先从缓存中初始化用户信息
        initUserEntity(cacheUser);
        if(!TextUtils.isEmpty(token)){//如果有token，启动后台进程并初始化正在运行的自动审核任务列表
            CommonUtil.getInstance().reloadAutoTaskList();
        }
        if (userEntity != null && !TextUtils.equals(userEntity.getId(), uid)) {//当前用户id与缓存的用户信息不符时，清除缓存
            clearData();
        }
        initScreenShotConfig();
    }
    //初始化用户相关信息
    public void initUserEntity(UserEntity userEntity){
        this.userEntity = userEntity;
        token = SpUtils.getToken(SheepApp.getInstance());
        uid = TextUtils.isEmpty(token) ? "" : token.split("@")[0];
    }


    public static DataUtil getInstance() {
        if (instance == null) {
            instance = new DataUtil();
        }
        return instance;
    }

    /**
     * 清除数据
     */
    public void clearData() {
        userEntity = null;
        aCache.clear();
    }
    /**
     * 清除aCache
     */
    public void clearACache() {
        userEntity = null;
        aCache.clear();
    }

    //-----------------------------------------用户信息部分-----------------------------------------------------开始
    private UserEntity userEntity;
    private String token;
    private String uid;

    public UserEntity getUserEntity() {
        return userEntity;
    }

    public void setUserEntity(UserEntity userEntity) {
        this.userEntity = userEntity;
    }

    /**
     * 获取当前用户的邀请码
     *
     * @return
     */
    public String getInvitationCode() {
        if (userEntity != null && userEntity.getInvitation_code() != null)
            return userEntity.getInvitation_code();
        return "";
    }

    /**
     * 获取当前用户的id
     *
     * @return
     */
    public String getUserId() {
        return uid;
    }

    //该用户id是当前登录用户的id
    public boolean isMe(int user_id) {
        return user_id == NumberFormatUtils.parseInteger(getUserId(), -1);
    }

    public String getToken() {
        return token;
    }

    /**
     * 获取当前用户的头像
     *
     * @return
     */
    public String getUserAvatar() {
        if (userEntity != null && userEntity.getAvatar() != null)
            return userEntity.getAvatar();
        return "";
    }

    /**
     * 获取当前用户的邀请人的邀请码
     *
     * @return
     */
    public String getUserParentCode() {
        if (userEntity != null && userEntity.getParent_code() != null)
            return userEntity.getParent_code();
        return "";
    }

    /**
     * 获取当前用户的手机号
     *
     * @return
     */
    public String getUserMobile() {
        if (userEntity != null && userEntity.getMobile() != null)
            return userEntity.getMobile();
        return "";
    }

    public void setUserMobile(String mobile) {
        if (userEntity != null)
            userEntity.setMobile(mobile);
    }

    /**
     * 获取当前用户的微信id
     *
     * @return
     */
    public String getUserWxOpenId() {
        if (userEntity != null && userEntity.getWx_openid() != null)
            return userEntity.getWx_openid();
        return "";
    }

    public void setUserNickName(String nickname) {
        if (userEntity != null)
            userEntity.setNickname(nickname);

    }

    public void setUserLoginName(String loginname) {
        if (userEntity != null)
            userEntity.setUser_name(loginname);

    }

    public void setUserAvatar(String avatar) {
        if (userEntity != null)
            userEntity.setAvatar(avatar);

    }

    //-----------------------------------------用户信息部分-----------------------------------------------------结束

    //-----------------------------------------缓存数据部分-----------------------------------------------------开始
    public <T> T getCacheResult(String key, Class<T> classT) {
        String cacheData = aCache.getAsString(SheepApp.getInstance().getConnectAddress().getAppUrl() + "v1/" + key);
        if (!TextUtils.isEmpty(cacheData)) {
            if (BuildConfig.XXTEA_ENCRYPT) {
                cacheData = BaseMessageConverter.decrypt(cacheData);
            }
            try {
                return JSON.parseObject(cacheData, BaseMessage.class).getData(classT);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 重新设置api为key的数据的时间为saveTime，若本身没有数据，则保存空数据
     *
     * @param key
     * @param saveTime 单位秒
     */
    public void resetCacheTime(String key, int saveTime) {
        String realKey = SheepApp.getInstance().getConnectAddress().getAppUrl() + "v1/" + key;
        String cacheData = aCache.getAsString(realKey);
        if (!TextUtils.isEmpty(cacheData)) {
            aCache.put(realKey, cacheData, saveTime);
        } else {
            aCache.put(realKey, "", saveTime);
        }
    }

    /**
     * 获取缓存的数据列表，为空代表没有获取过，为空字符串代表之前获取数据为空列表
     *
     * @param key
     * @param classT
     * @param <T>
     * @return
     */
    public <T> List<T> getCacheList(String key, Class<T> classT) {
        String cacheData = aCache.getAsString(SheepApp.getInstance().getConnectAddress().getAppUrl() + "v1/" + key);
        if (cacheData == null) {
            return ListUtil.emptyList();
        }
        if (BuildConfig.XXTEA_ENCRYPT) {
            cacheData = BaseMessageConverter.decrypt(cacheData);
        }
        try {
            return JSON.parseObject(cacheData, BaseMessage.class).getDataList(classT);
        } catch (Exception e) {
            e.printStackTrace();
            return ListUtil.emptyList();
        }
    }
    /**
     * 获取缓存的数据列表，为空代表没有获取过，为空字符串代表之前获取数据为空列表
     *
     * @param key
     * @param classT
     * @param <T>
     * @return
     */
    public <T> List<T> getCacheList(String key, Class<T> classT, Conversion<BaseMessage, List<T>> conversion, int page) {
        String cacheData = aCache.getAsString(SheepApp.getInstance().getConnectAddress().getAppUrl() + "v1/" + key);
        if (cacheData == null) {
            return null;
        } else if (cacheData.isEmpty()) {
            return ListUtil.emptyList();
        }
        if (BuildConfig.XXTEA_ENCRYPT) {
            cacheData = BaseMessageConverter.decrypt(cacheData);
        }
        try {
            BaseMessage baseMessage = JSON.parseObject(cacheData, BaseMessage.class);
            if(baseMessage != null) {
                if (conversion != null) {
                    return conversion.convert(baseMessage, page);
                } else {
                    return baseMessage.getDataList(classT);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ListUtil.emptyList();
    }


    /**
     * 获取缓存数据的时间
     *
     * @param key
     * @return
     */
    public void clearCache(String key) {
        aCache.remove(key);
    }

    public boolean isNewData(String key) {
        return !TextUtils.equals(aCache.getAsString(ApiKey.oldEqualsNew(SheepApp.getInstance().getConnectAddress().getAppUrl() + "v1/" + key)), "yes");//新老数据不同，说明是新数据
    }

    //-----------------------------------------缓存数据部分-----------------------------------------------------结束

    //-----------------------------------------其它数据部分-----------------------------------------------------开始
    public static int getAsInt(String key, int defaultValue) {
        String result = aCache.getAsString(key);
        return NumberFormatUtils.parseInteger(result, defaultValue);
    }
    public static void putAsInt(String key, int value) {
        aCache.put(key, String.valueOf(value));
    }
    public static String getAsString(String key, String defaultValue) {
        String result = aCache.getAsString(key);
        return result == null ? defaultValue : result;
    }
    public static void putAsString(String key, String value) {
        aCache.put(key, value);
    }
    public static boolean getAsBoolean(String key, boolean defaultValue) {
        String result = aCache.getAsString(key);
        return result == null ? defaultValue : TextUtils.equals(result, "true");
    }
    public static void putAsBoolean(String key, boolean value) {
        aCache.put(key, Boolean.toString(value));
    }


    private Map<String, Object> objectMap = new HashMap<>();

    /**
     * 存放共享数据
     *
     * @param key
     * @param data
     */
    public void putData(String key, Object data) {
        objectMap.put(key, data);
    }

    /**
     * 获取共享数据并删除
     *
     * @param key
     */
    public Object getData(String key) {
        if (objectMap.containsKey(key)) {
            return objectMap.remove(key);
        }
        return null;
    }
    //是否使用小绵羊截图方案
    public static boolean IS_USE_SCREEN_SHOT = false;//默认开启小剪刀截图，有很多问题，调整到单独的后台进程再测试
    //是否监听媒体库图片变化
    public static boolean IS_LISTEN_SCREEN_SHOT = false;
    //是否上传截图时使用所有图片
    public static boolean IS_USE_ALL_IMAGE = true;
    //初始化是否启用小绵羊两种截图方案
    private void initScreenShotConfig() {
        if(!IS_USE_ALL_IMAGE) {//不启用上传所有截图时才更新截图方案配置
            SheepApp.getInstance().getNetComponent().getApiService().needShotScreen()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                        @Override
                        public void onNext(BaseMessage baseMessage) {
                            ScreenShotConfig config = baseMessage.getData(ScreenShotConfig.class);
                            if (config != null) {
                                IS_USE_SCREEN_SHOT &= config.isNeed();//默认开启才可配置为false
                                IS_LISTEN_SCREEN_SHOT = config.isNeed();
                            }
                        }

                        @Override
                        public void onError(BaseMessage baseMessage) {
                        }
                    });
        }
    }
    /**
     * 截图路径
     *
     * @return
     */
    public static File getScreenShotsFile(String packageName) {
        File dir = getScreenShotsDir(packageName);
        return new File(dir, TimeUtil.getDate("yyyy-MM-dd-hh-mm-ss")+".png");
    }

    /**
     * 截图目录
     *
     * @return
     */
    public static File getScreenShotsDir() {
        return SheepApp.getInstance().getDir("ScreenShots", Context.MODE_PRIVATE);
    }
    /**
     * 指定程序的截图目录
     *
     * @return
     */
    public static File getScreenShotsDir(String packageName) {
        File dir = new File(getScreenShotsDir(), packageName);
        if(!dir.exists())
            dir.mkdirs();
        return dir;
    }

    /**
     * 获取所有小绵羊的截图
     *
     * @return
     */
    public static ArrayList<String> getAllScreenShotList() {
        File[] dirs = getScreenShotsDir().listFiles();
        ArrayList<String> list = ListUtil.emptyList();
        if(dirs != null) {
            for (File dir : dirs) {
                if (dir.exists() && dir.isDirectory()) {
                    File[] files = dir.listFiles();
                    if(files != null){
                        for (File file : files) {
                            if(file.exists() && file.isFile()){
                                list.add(file.getAbsolutePath());
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    /**
     * 删除所有截图
     */
    public void clearScreenShots() {
        FileUtil.deleteFile(getScreenShotsDir(), false);
    }
    /**
     * 删除指定应用下所有截图
     */
    public void clearScreenShots(String packageName) {
        FileUtil.deleteFile(getScreenShotsDir(packageName), false);
    }

    public static final int REQUEST_MEDIA_PROJECTION = 18;
    public static final String REQUEST_CAPTURE_PERMISSION = "requestCapturePermission";//获取录屏权限

    private Action1<Integer> action1;

    public void requestCapturePermission(Activity activity, Action1<Integer> action1) {
        if(IS_USE_SCREEN_SHOT) {//使用小绵羊截图方案
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                this.action1 = action1;
                //5.0 之后才允许使用屏幕截图
                MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) activity.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
                if (mediaProjectionManager != null) {
                    activity.startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
                    return;
                }
            }
            G.showToast("您的系统版本过低，暂不支持该功能");
        } else {
            action1.call(0);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_MEDIA_PROJECTION:
                if (resultCode == RESULT_OK && data != null) {
                    FloatShotScreenService.getInstance().setResultData(data);
                    if (action1 != null)
                        action1.call(0);
                }
                break;
        }

    }

    //-----------------------------------------其它数据部分-----------------------------------------------------结束
    //-----------------------------------------引导页中用到的是否为新版部分-----------------------------------------------------开始
    private int versionType = 0;
    public boolean notInitVersion() {
        return versionType == 0;
    }

    public void setIsNewSmallSheep(boolean isNewSmallSheep) {
        versionType = isNewSmallSheep ? 1 : 2;
    }

    public boolean isNewSmallSheep() {
        return versionType == 1;
    }
    public void resetIsNewSmallSheep() {
        versionType = 0;
    }

    //-----------------------------------------引导页中用到的是否为新版部分-----------------------------------------------------结束
    //-----------------------------------------数据转换部分-----------------------------------------------------结束

    /**
     * 获取bundle中的数据并转换为对应的类
     * @param bundle
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T getObject(Bundle bundle, Class<T> tClass) {
        if(bundle != null) {
            String data = bundle.getString(tClass.getSimpleName());
            try {
                return JSONObject.parseObject(data, tClass);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 设置数据到bundle中，注意，其key是类名，所以同一个类只支持一条
     * @param bundle
     * @param t
     * @param <T>
     */
    public static <T> void putObject(Bundle bundle, T t) {
        bundle.putString(t.getClass().getSimpleName(), JSONObject.toJSONString(t));
    }
    /**
     * 获取bundle中的数据并转换为对应的类
     * @param intent
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T getObject(Intent intent, Class<T> tClass) {
        if(intent != null) {
            String data = intent.getStringExtra(tClass.getSimpleName());
            try {
                return JSONObject.parseObject(data, tClass);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 设置数据到bundle中，注意，其key是类名，所以同一个类只支持一条
     * @param <T>
     * @param intent
     * @param t
     */
    public static <T> Intent putObject(Intent intent, T t) {
        return intent.putExtra(t.getClass().getSimpleName(), JSONObject.toJSONString(t));
    }
    /**
     * 设置数据到bundle中
     * @param <T>
     * @param intent
     * @param t
     * @param key
     */
    public static <T> Intent putObject(Intent intent, T t, String key) {
        return intent.putExtra(key, JSONObject.toJSONString(t));
    }


    //-----------------------------------------数据转换部分-----------------------------------------------------结束
}
