package com.sheep.gamegroup.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.sheep.gamegroup.model.api.BaseMessageConverter;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.model.util.AutoTaskListUtil;
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.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static android.app.Activity.RESULT_OK;

/**
 * Created by realicing on 2018/7/27.
 * realicing@sina.com
 */
public class DataUtil {
    private static DataUtil instance = new DataUtil();
    private ACache aCache;

    private DataUtil() {
        LogUtil.println("DataUtil", "init");
        aCache = ACache.get(SheepApp.getInstance());
        userEntity = getCacheResult(ApiKey.get_info, UserEntity.class);//先从缓存中初始化用户信息
        String id = SpUtils.getToken(SheepApp.mContext);
        String uid = TextUtils.isEmpty(id) ? "" : id.split("@")[0];
        if (userEntity != null && !TextUtils.equals(userEntity.getId(), uid)) {//当前用户id与缓存的用户信息不符时，清除缓存
            clearData();
        }

    }

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

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

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

    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() {
        if (userEntity != null && userEntity.getId() != null)
            return userEntity.getId();
        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 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 null;
        } else if (cacheData.isEmpty()) {
            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
     * @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");//新老数据不同，说明是新数据
    }

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

    //-----------------------------------------其它数据部分-----------------------------------------------------开始
    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 final boolean IS_USE_SCREEN_SHOT = false;
    //是否监听媒体库图片变化
    public static final boolean IS_LISTEN_SCREEN_SHOT = false;
    /**
     * 截图路径
     *
     * @return
     */
    public File getScreenShotsFile(String packageName) {
        File dir = getScreenShotsDir(packageName);
        return new File(dir, TimeUtil.getDate("yyyy-MM-dd-hh-mm-ss")+".png");
    }

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

    /**
     * 删除所有截图
     */
    public void clearScreenShots() {
        FileUtil.deleteFile(getScreenShotsDir(), 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;
        }

    }

    /**
     * 获取前台运行的程序的包名
     * @return
     */
    @SuppressLint("NewApi")
    public String getPackageNameInForeground() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            UsageStatsManager mUsageStatsManager = (UsageStatsManager) SheepApp.getInstance().getSystemService(Context.USAGE_STATS_SERVICE);//usagestats
            long time = System.currentTimeMillis();
            if (mUsageStatsManager != null) {
                List<UsageStats> usageStatsList = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, AutoTaskListUtil.getInstance().getReceiveTaskTime(), time);

                if (!ListUtil.isEmpty(usageStatsList)) {
                    TreeMap<Long, UsageStats> mySortedMap = new TreeMap<>();
                    for (UsageStats item : usageStatsList) {
                        mySortedMap.put(item.getLastTimeUsed(), item);
                    }

                    UsageStats usageStats = mySortedMap.get(mySortedMap.lastKey());

                    return usageStats.getPackageName();
                }
            }
        }
        android.app.ActivityManager.RunningAppProcessInfo process = getAppProcessInfoInForeground();
        if (process != null) {
            return process.processName;
        }
        return null;
    }

    private android.app.ActivityManager.RunningAppProcessInfo getAppProcessInfoInForeground() {
        android.app.ActivityManager manager = (android.app.ActivityManager) SheepApp.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
        List<android.app.ActivityManager.RunningAppProcessInfo> processList = manager == null ? null : manager.getRunningAppProcesses();
        if (!ListUtil.isEmpty(processList)) {
            for (android.app.ActivityManager.RunningAppProcessInfo item : processList) {
                if (item != null && item.importance == android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    return item;
                }
            }
        }
        return null;
    }
    public static boolean 是官方包吗(){
        return "kfzs".equals(ChannelContent.getInstance().getChannel_name());
    }

    public void addPng(final String imagePath) {
        final String packageName = getPackageNameInForeground();
        if(TextUtils.isEmpty(packageName)){
            LogUtil.println("ScreenShotListenManager", "无法获取到当前运行的应用的包名");
            return;
        }
//        File shotFile = getScreenShotsFile(packageName);
        LogUtil.println("ScreenShotListenManager", packageName);
        Observable.just(1).delay(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        try {
                            FileUtil.copyFile(new File (imagePath), getScreenShotsDir(packageName));
                        } catch (IOException e) {
                            e.printStackTrace();
                            LogUtil.println("ScreenShotListenManager", "复制截屏图片失败");
                        }
                    }
                });

    }
//    //正在运行的任务
//    List<TaskAcceptedEty> taskAcceptedEtyList = ListUtil.emptyList();
//    public void addTaskAcceptedEtyList(List<TaskAcceptedEty> list) {
//        isInitTaskAcceptedList = true;
//        taskAcceptedEtyList.clear();
//        taskAcceptedEtyList.addAll(list);
//        LogUtil.println("DataUtil", "taskAcceptedEtyList", taskAcceptedEtyList.size());
//    }
//
//    /**
//     * 通过包名从内存中正在运行的任务列表中获取正在运行的任务
//     * @param pacageName
//     * @return
//     */
//    public TaskAcceptedEty getTaskAcceptedEtyFromPackageName(String pacageName) {
//        if(!TextUtils.isEmpty(pacageName))
//            for (TaskAcceptedEty taskAcceptedEty : taskAcceptedEtyList) {
//                if(taskAcceptedEty != null && taskAcceptedEty.getRelease_task() != null && taskAcceptedEty.getRelease_task().getTask() != null
//                        && TextUtils.equals(taskAcceptedEty.getRelease_task().getTask().getPackage_names(), pacageName)){
//                    return taskAcceptedEty;
//                }
//            }
//        return null;
//    }
//
//    private boolean isInitTaskAcceptedList = false;
//
//    public boolean isInitTaskAcceptedList() {
//        return isInitTaskAcceptedList;
//    }
//
//    public List<TaskAcceptedEty> getTaskAcceptedEtyList() {
//        return taskAcceptedEtyList;
//    }
    //-----------------------------------------其它数据部分-----------------------------------------------------结束
}
