package com.sheep.gamegroup.util;

import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.provider.AlarmClock;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.kfzs.duanduan.utils.ApkUtils;
import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.model.entity.AppInfo;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.entity.Version;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.afinal.simplecache.ACache;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Response;
import rx.functions.Action1;

import static com.sheep.gamegroup.util.UMConfigUtils.Event.UPGRADE_DIALOG_BT;

/**
 * Created by realicing on 2018/5/29.
 * realicing@sina.com
 */
public class SysAppUtil {

    private static Dialog dialog;
    public static void startAlermApp(Activity activity, String msg, int hour, int min){
        boolean notDone = true;
        if(Build.VERSION.SDK_INT > 18) {
            try {
                Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM);
                intent.putExtra(AlarmClock.EXTRA_MESSAGE, msg);
                intent.putExtra(AlarmClock.EXTRA_HOUR, hour);
                intent.putExtra(AlarmClock.EXTRA_MINUTES, min);
                ArrayList<Integer> arrayList = ListUtil.emptyList();
                arrayList.add(Calendar.MONDAY);
                arrayList.add(Calendar.TUESDAY);
                arrayList.add(Calendar.WEDNESDAY);
                arrayList.add(Calendar.THURSDAY);
                arrayList.add(Calendar.FRIDAY);
                arrayList.add(Calendar.SATURDAY);
                arrayList.add(Calendar.SUNDAY);
                intent.putExtra(AlarmClock.EXTRA_DAYS, arrayList);
                intent.putExtra(AlarmClock.EXTRA_VIBRATE, true);
                if (intent.resolveActivity(activity.getPackageManager()) != null) {
                    activity.startActivity(intent);
                    notDone = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(notDone){
            G.showToast(R.string.coming_soon);
        }
    }

    /**
     * 是否第一次运行新的小绵羊
     * @return
     */
    public static boolean isNewSmallSheep() {
        if(DataUtil.getInstance().notInitVersion()){
            int version_code = ForeverCacheUtil.getInstance().getVersionCode();
            int cur_version_code = 3000005;//要想发新版本后让用户显示引导页面，就直接修改为一个更大的值
            ForeverCacheUtil.getInstance().saveVersionCode(cur_version_code);
            boolean isNewSmallSheep = version_code != cur_version_code
//                || BuildConfig.DEBUG
                ;
            DataUtil.getInstance().setIsNewSmallSheep(isNewSmallSheep);
        }
        return DataUtil.getInstance().isNewSmallSheep();
    }

    public static void clearCache(final AbsObserver<Object> action1) {
        Observable.just(1)
                .map(new Function<Integer, Integer>() {
                    @Override
                    public Integer apply(Integer integer) throws Exception {
                        Glide.get(SheepApp.getInstance()).clearDiskCache();//清理图片
                        ClassFileHelper.getInstance().clearDir();//清理下载文件
                        DataUtil.getInstance().clearScreenShots();//清除所有截图
                        return integer;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(action1);
    }
    public static String getAppCacheSize() {
        try {
//            File filesDir = SheepApp.getInstance().getExternalFilesDir(null);
//            File cacheDir = SheepApp.getInstance().getExternalCacheDir();
//            long filesDirSize = getFolderSize(filesDir);
//            long cacheSize = getFolderSize(cacheDir);
            long screenShotsSize = getFolderSize(DataUtil.getScreenShotsDir());
            long apkSize = getFolderSize(new File(ClassFileHelper.DIR));
            File cacheDirPath = SheepApp.getInstance().getCacheDir();
            long glideSize = getFolderSize(new File( cacheDirPath, InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR));
            return getFormatSize(//filesDirSize+cacheSize+
                    screenShotsSize+apkSize+glideSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    // 获取文件大小
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
    public static long getFolderSize(File file){
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 格式化单位
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
//            return size + "Byte";
            return "0K";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "K";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "M";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }
    public static String getFileFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "K";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "M";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }
    /**
     * 返回正确的UserAgent
     * @return
     */
    public  static String getUserAgent(){
        StringBuilder sb = null;
        try {
            String userAgent;
            sb = new StringBuilder();
            userAgent = System.getProperty("http.agent");//Dalvik/2.1.0 (Linux; U; Android 6.0.1; vivo X9L Build/MMB29M)

            for (int i = 0, length = userAgent.length(); i < length; i++) {
                char c = userAgent.charAt(i);
                if (c <= '\u001f' || c >= '\u007f') {
                    sb.append(String.format("\\u%04x", (int) c));
                } else {
                    sb.append(c);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return TextUtils.isEmpty(sb) ? "Dalvik/2.1.0 (Linux; U; Android 5.1.1; letv x501 Build/LMY48Z)" : sb.toString();
    }

    public static void checkNet(AbsObserver<Integer> action1) {
        Observable.just(1)
                .map(new Function<Integer, Integer>() {
                    @Override
                    public Integer apply(Integer integer) throws Exception {
                        int result;
                        try {
                            Response response = OkHttpUtils.get().url("http://www.baidu.com").build().execute();
                            result = response.isSuccessful() ? 0 : -1;
                        } catch (IOException e) {
                            e.printStackTrace();
                            result = -2;
                        }
                        switch (result){
                            case 0://有网
                                NetUtil.CAN_CONNECT_SERVICE = true;
                                break;
                            default://无网
                                NetUtil.CAN_CONNECT_SERVICE = false;
                                break;
                        }
                        return result;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(action1);
    }

    public static List<AppInfo> getAppInfos(){
        //首先获取到包的管理者
        PackageManager packageManager = SheepApp.getInstance().getPackageManager();
        //获取到所有的安装包
        List<PackageInfo> installedPackages = packageManager.getInstalledPackages(PackageManager.GET_ACTIVITIES | PackageManager.GET_SIGNATURES);
        ArrayList<AppInfo> appInfos = new ArrayList<>();
        for (PackageInfo installedPackage : installedPackages) {
            AppInfo appInfo = new AppInfo();
            //程序包名
            String packageName = installedPackage.packageName;
            appInfo.setPackageName(packageName);
            //获取到图标
            Drawable icon = installedPackage.applicationInfo.loadIcon(packageManager);
            appInfo.setIcon(icon);
            //获取到应用的名字
            String appName = installedPackage.applicationInfo.loadLabel(packageManager).toString();
            appInfo.setAppName(appName);
            //获取到安装包的路径
            String sourceDir = installedPackage.applicationInfo.sourceDir;
            appInfo.setSourceDir(sourceDir);
            File file = new File(sourceDir);
            //获取到安装apk的大小
            long apkSize = file.length();
            //格式化apk的大小
            appInfo.setApkSize(Formatter.formatFileSize(SheepApp.getInstance(),apkSize));
            appInfo.setSha1(getSHA1(installedPackage));

            int flags = installedPackage.applicationInfo.flags;
            //判断当前是否是系统app
            if((flags & ApplicationInfo.FLAG_SYSTEM) !=0){
                //那么就是系统app
                appInfo.setUserApp(false);
            }else{
                //那么就是用户app
                appInfo.setUserApp(true);
            }

            if((flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0){
                //那么当前安装的就是sd卡
                appInfo.setSD(true);

            }else{
                //那么就是手机内存
                appInfo.setSD(false);
            }
            appInfos.add(appInfo);
        }
        return appInfos;
    }
    public static String getSHA1(PackageInfo packageInfo) {
        try {
            byte[] cert = packageInfo.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuilder hexString = new StringBuilder();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length()-1);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    //运行命令行的方法
    public static void execShell(String cmd) {
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    p.getInputStream()));
            String readLine;
            while((readLine = br.readLine()) != null) {
                LogUtil.println("execShell", "getInputStream", readLine);
            }
            BufferedReader errorBr = new BufferedReader(new InputStreamReader(
                    p.getErrorStream()));
            while((readLine = errorBr.readLine()) != null) {
                LogUtil.println("execShell", "getErrorStream", readLine);
            }
            br.close();
            p.destroy();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static ComponentName getAppComponentName(String packageName) {

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageName);

        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = SheepApp.getInstance().getPackageManager()
                .queryIntentActivities(resolveIntent, 0);

        ResolveInfo resolveinfo = null;
        try {
            resolveinfo = resolveinfoList.iterator().next();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (resolveinfo != null) {
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
            String className = resolveinfo.activityInfo.name;
            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            // 设置ComponentName参数1:packagename参数2:MainActivity路径
            ComponentName cn = new ComponentName(packageName, className);
            return cn;
        }
        return null;
    }





    /**
     * 显示升级对话框
     * @param activity
     * @param ignoreMd5 用户手动时传null；进入主要界面时不要传null，传保存的忽略md5值，为空字符串时传""
     */
    public static void showVersionInfo(final Activity activity, final String ignoreMd5) {
        /**
         *游戏认证过来的不提示升级
         */
        if(!TextUtils.isEmpty(SheepApp.getInstance().getGamePackgeName()))
            return;
        showVersionInfo(activity, ignoreMd5, null);
    }

    /**
     * 显示升级对话框
     * @param activity
     * @param ignoreMd5 用户手动时传null；进入主要界面时不要传null，传保存的忽略md5值，为空字符串时传""
     * @param action1 动作完成后的回调
     */
    public static void showVersionInfo(final Activity activity, final String ignoreMd5, final Action1<Integer> action1) {
        if(!ConfigUtil.getInstance().isUpgrade()) {
            if(action1 != null)
                action1.call(0);
            return;
        }
        if(dialog != null){
            try {
                if(dialog.isShowing()) {
                    dialog.dismiss();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(TestUtil.isSheep()) {
            checkUpdateNewVersion(activity, ignoreMd5, action1);
        } else if(!TestUtil.isDev()) {
            TestUtil.checkUpdateFromJenkins(activity, ignoreMd5, action1);
        }
    }
    //通过接口检查更新
    public static void checkUpdateNewVersion(final Activity activity, final String ignoreMd5, final Action1<Integer> action1) {
        SheepApp.getInstance().getNetComponent().getApiService().getNewVersion(SheepApp.getInstance().getConnectAddress().getVersionType())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        Version version = baseMessage.getData(Version.class);
                        loadVersion(activity, ignoreMd5, action1, version);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        ACache.get(SheepApp.getInstance()).put("version_url", "");
                        if (ignoreMd5 == null)
                            Beta.checkUpgrade();
                        if (action1 != null)
                            action1.call(0);
                    }
                });
    }

    private static void loadVersion(final Activity activity, final String ignoreMd5, final Action1<Integer> action1, final Version version) {
        if(version == null){
            if(ignoreMd5 == null)
                G.showToast("当前版本为最新版本，无需更新");
            if(action1 != null)
                action1.call(0);
            return;
        }
        boolean isNewApp;
        if(TestUtil.isSheep()) {
            if(ignoreMd5 != null && TextUtils.equals(ignoreMd5, version.getVersion_number()+"") && !version.isForceUpdate()){
                LogUtil.println("showVersionInfo", "忽略", ignoreMd5, version.getVersion_name());
                if(action1 != null)
                    action1.call(0);
                return;
            }
            int versionCode = SysAppUtil.getAppVersionCode();
            if (versionCode == 0) {
                if (ignoreMd5 == null)
                    G.showToast("请稍候重试");//无法获取当前版本号，程序出错
                if (action1 != null)
                    action1.call(0);
                return;
            }
            isNewApp = versionCode >= version.getVersion_number();
        } else {
            if(ignoreMd5 != null && TextUtils.equals(ignoreMd5, version.getMd5_address()) && !version.isForceUpdate()){
                LogUtil.println("showVersionInfo", "忽略", ignoreMd5, version.getVersion_name());
                if(action1 != null)
                    action1.call(0);
                return;
            }
            String fileMD5 = SysAppUtil.getConnectAdrressFileMD5();
            if (TextUtils.isEmpty(fileMD5)) {//无法获取当前appMd5值，程序出错
                if (ignoreMd5 == null)
                    G.showToast("请稍候重试");
                if (action1 != null)
                    action1.call(0);
                return;
            }
            isNewApp = fileMD5.equalsIgnoreCase(version.getMd5_address());
        }
        if(isNewApp){//已经是最新版本
            ACache.get(SheepApp.getInstance()).put("version_url", "");
            if(ignoreMd5 == null)
                G.showToast("当前版本为最新版本，无需更新");
            if(action1 != null)
                action1.call(0);
        } else {//有新版本
            ACache.get(SheepApp.getInstance()).put("version_url", version.getAddress());
            final String fileName = version.getMd5_address()+".apk";
            final File file = new File(ClassFileHelper.DIR, fileName);
            DialogConfig dialogConfig = new DialogConfig();
            dialogConfig.setTitle("小绵羊V"+version.getVersion_name());
            dialogConfig.setMsg(TextUtils.isEmpty(version.getUpdate_content()) ? "当前版本小绵羊V"+getConnectAdrressPackageInfo().versionName : version.getUpdate_content()).setMsgGravity(Gravity.START)
                    .setBtnLeftText(file.exists() ? "立即安装" : "立即更新").setBtnLeftNotDissDialog(true).setBtnLeftOnClickListener(new View.OnClickListener() {
                private void installApk(File file){
                    if(file != null && file.exists()) {
                        //升级后继承渠道
                        String channel = ChannelContent.getInstance().getChannel_name();
                        try {
                            if(!TextUtils.isEmpty(channel) && !ZipChannelUtil.isAddQUA(file)){
                                ZipChannelUtil.writeQUA(file, channel);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        ApkUtils.installApk(SheepApp.getInstance(), file.getAbsolutePath());
                    }
                }
                @Override
                public void onClick(final View view) {
                    if(view instanceof TextView)
                        UPGRADE_DIALOG_BT.onEvent("action", ((TextView) view).getText());
                    if(file.exists() && Md5Util.checkMD5(version.getMd5_address(), file)){//文件存在并且md5值相同则直接安装
                        installApk(file);
                    } else if(TextUtils.isEmpty(version.getAddress())){//地址错误
                        G.showToast(R.string.error_download_link);
                    } else {//下载安装
                        OkHttpUtils.get().url(version.getAddress()).build().execute(new FileCallBack(ClassFileHelper.DIR, fileName) {
                            @Override
                            public void inProgress(float progress, long total, int id) {
                                if(view instanceof TextView) {
                                    TextView btnLeftTextView = (TextView) view;
                                    btnLeftTextView.setEnabled(false);
                                    btnLeftTextView.setText(String.format(Locale.CHINA, "%d%%", Math.round(progress * 100)));
                                }
                            }
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                if(view instanceof TextView) {
                                    TextView btnLeftTextView = (TextView) view;
                                    btnLeftTextView.setEnabled(true);
                                    btnLeftTextView.setText("重新下载");
                                }
                            }

                            @Override
                            public void onResponse(File response, int id) {
                                if(response != null && response.exists()) {
                                    if(view instanceof TextView){
                                        TextView btnLeftTextView = (TextView) view;
                                        btnLeftTextView.setEnabled(true);
                                        btnLeftTextView.setText("立即安装");
                                    }

                                    installApk(response);
                                }
                            }
                        });
                    }
                }
            });
            if(version.isForceUpdate() && TestUtil.isSheep()){//强更
                dialogConfig.setCancelable(false);
            } else {
                dialogConfig.setBtnRightText("下次更新").setBtnRightOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        SpUtils.saveIgnoreMd5(TestUtil.isSheep() ? version.getVersion_number()+"" : version.getMd5_address());
                        if(view instanceof TextView)
                            UPGRADE_DIALOG_BT.onEvent("action", ((TextView) view).getText());
                    }
                });
            }
            dialog = ViewUtil.showMsgDialog(activity, dialogConfig);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
                    if (action1 != null)
                        action1.call(0);
                }
            });
        }
    }

    private static PackageInfo getConnectAdrressPackageInfo() {
        return ApkUtils.getPackageInfo(SheepApp.getInstance().getConnectAddress().getPackageName());
    }
    public static String getConnectAdrressFileMD5() {
        PackageInfo packageInfo = getConnectAdrressPackageInfo();
        if(packageInfo == null || TextUtils.isEmpty(packageInfo.applicationInfo.sourceDir)){
            return "";
        }
        String fileMD5 = Md5Util.getFileMD5(new File(packageInfo.applicationInfo.sourceDir));
        LogUtil.println("FileMD5", fileMD5);
        return fileMD5;
    }

    public static int getAppVersionCode() {
        try {
            PackageInfo info = getConnectAdrressPackageInfo();
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * bugly 检查更新
     */
    public static Version checkBuglyUpdate(){
//        Beta.checkUpgrade();
        UpgradeInfo upgradeInfo = Beta.getUpgradeInfo();
        if(upgradeInfo != null) {
            Version version = new Version();
            version.setAddress(upgradeInfo.apkUrl);
            version.setMd5_address(upgradeInfo.apkMd5);
            version.setStrong_update(upgradeInfo.upgradeType-1);//version.getStrong_update == 1/upgradeInfo.upgradeType == 2 为强更
            version.setUpdate_content(upgradeInfo.newFeature+"\n"+upgradeInfo.publishType);
            version.setVersion_name(upgradeInfo.versionName);
            version.setVersion_number(upgradeInfo.versionCode);
            version.setUpdate_time((int) (upgradeInfo.publishTime/1000));
            return version;
        }
        return null;
    }

    //获取设备的信息
    public static String getUserAgentOrDeviceInfo(){
        StringBuilder sb = null;
        try {
            String userAgent;
            sb = new StringBuilder();
            userAgent = System.getProperty("http.agent");//Dalvik/2.1.0 (Linux; U; Android 6.0.1; vivo X9L Build/MMB29M)

            for (int i = 0, length = userAgent.length(); i < length; i++) {
                char c = userAgent.charAt(i);
                if (c <= '\u001f' || c >= '\u007f') {
                    sb.append(String.format("\\u%04x", (int) c));
                } else {
                    sb.append(c);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return TextUtils.isEmpty(sb) ? String.format(Locale.CHINA, "Android %s/%d; Model %s; Brand %s", getSystemVersion(), Build.VERSION.SDK_INT, getSystemModel(), getDeviceBrand()) : sb.toString();
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return  系统版本号
     */
    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获取手机型号
     *
     * @return  手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return  手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    public static String readCpuInfo() {
        String result = "";
        try {
            String[] args = {"/system/bin/cat", "/proc/cpuinfo"};
            ProcessBuilder cmd = new ProcessBuilder(args);

            Process process = cmd.start();
            StringBuffer sb = new StringBuffer();
            String readLine = "";
            BufferedReader responseReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf-8"));
            while ((readLine = responseReader.readLine()) != null) {
                sb.append(readLine);
            }
            responseReader.close();
            result = sb.toString().toLowerCase();
        } catch (IOException ex) {
        }
        return result;
    }

    /**
     * 判断cpu是否为电脑来判断 模拟器
     *
     * @return true 为模拟器
     */
    public static boolean checkIsNotRealPhone() {
        String cpuInfo = readCpuInfo();
        if ((cpuInfo.contains("intel") || cpuInfo.contains("amd"))) {
            return true;
        }
        return false;
    }
}
