package com.sjkj.appthreefloor_tsgz.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Message;
import android.text.TextUtils;

import androidx.core.content.FileProvider;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.sjkj.appthreefloor_tsgz.BuildConfig;
import com.sjkj.appthreefloor_tsgz.app.App;
import com.sjkj.appthreefloor_tsgz.bean.VersionBean;
import com.sjkj.appthreefloor_tsgz.net.CheckVersionNet;
import com.sjkj.appthreefloor_tsgz.utils.UpdateDialog;
import com.sjkj.base_lib.app.AppManager;
import com.sjkj.base_lib.entity.Params;
import com.sjkj.base_lib.entity.ResponseBean;
import com.sjkj.base_lib.net.domain.interactor.ProcessErrorSubscriber;
import com.sjkj.base_lib.utils.ToastUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class VersionUtils {
    private Activity activity;
    private CheckVersionNet checkVersionNet = new CheckVersionNet(App.getInstance());
    public static String apkPath = "";

    public boolean isExistApk() {
        if (TextUtils.isEmpty(apkPath)) {
            return false;
        }
        return true;
    }

    public String getApkPath() {
        return apkPath;
    }

    public VersionUtils(Activity activity) {
        this.activity = activity;
    }

    public interface CallBack {
        void onError(String msg);

        void onSuccess();

        void onNewest();
    }

    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    ToastUtils.show("安装包地址不存在");
                    break;
                case 1:
                    ToastUtils.show(/*file.getPath()*/"下载成功，准备安装");
                    break;
                case 2:
                    ToastUtils.show("文件下载出错，请重试");
                    break;
                case 3:
                    ToastUtils.show("文件安装出错，请重试");
                    break;
            }
        }
    };

    public void checkVersion(String versionName, int versionCode, CallBack callBack) {
        if (isExistApk()) {
            installApkFile(AppManager.getAppManager().currentActivity(), getApkPath());
            return;
        }
        if (TextUtils.isEmpty(versionName)) {
            if (callBack != null) {
                callBack.onError("获取当前版本信息失败");
                return;
            }
        }
        checkVersionNet.setParams(new Params());
        checkVersionNet.execute(new ProcessErrorSubscriber<ResponseBean<VersionBean>>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                if (callBack != null)
                    callBack.onError("" + e.getMessage());
            }

            @Override
            public void onNext(final ResponseBean<VersionBean> o) {
                super.onNext(o);
                final ResponseBean<VersionBean> responseBean = o;
                if (responseBean != null && responseBean.getData() != null) {

                    if (responseBean.getData().getVersionCode() <= versionCode) {
                        if (callBack != null) {
                            callBack.onNewest();
                        }
                        return;
                    }
                    UpdateDialog updateDialog = new UpdateDialog(activity);
                    updateDialog.showDialog();
                    updateDialog.setParams(versionName, responseBean.getData().getVersionName(), "版本更新",!"Y".equals(responseBean.getData().getIsForceupdate()));
                    updateDialog.setOnItemClickListener(new UpdateDialog.OnItemClickListener() {
                        @Override
                        public void onItemClick(int type) {
                            switch (type) {
                                case 1:
//                                    ToastUtils.show("更新中...");
                                    String fileUrl = responseBean.getData().getPath();
                                    if (TextUtils.isEmpty(fileUrl)) {
                                        updateDialog.hideDialog();
                                        if (callBack != null) {
                                            callBack.onError("下载更新包失败");
                                            return;
                                        }
                                    }
                                    downLoadApk(fileUrl, activity, callBack);
                                    break;
                                default:
                                    break;
                            }
                        }
                    });
                }
            }
        });
    }

    /* * 从服务器中下载APK */
    private void downLoadApk(final String updateUrl, final Context context, final CallBack callBack) {
        final ProgressDialog pd;
        // 进度条对话框
        pd = new ProgressDialog(context);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.show();
        pd.setCancelable(false);
        pd.setCanceledOnTouchOutside(false);
        new Thread() {
            @Override
            public void run() {

                File file = null;
                try {
                    file =getFileFromServer(updateUrl, pd);
                    sleep(3000);
                    pd.dismiss(); // 结束掉进度条对话框
                    handler.sendEmptyMessage(1);
                } catch (Exception e) {
                    if (callBack != null) {
                        callBack.onError("文件下载失败");
                        pd.dismiss();
                        return;
                    }
                    handler.sendEmptyMessage(2);
                    pd.dismiss(); // 结束掉进度条对话框
                }
                try {
                    if (file != null && file.exists()) {
                        apkPath = file.getPath();
                        //check version o
                        if (Build.VERSION.SDK_INT >= 26) {
                            boolean b = activity.getPackageManager().canRequestPackageInstalls();
                            if (b) {
                                installApkFile(activity, file.getPath());//安装应用的逻辑(写自己的就可以)
                            } else {
                                final File finalFile = file;
                                XXPermissions.with(AppManager.getAppManager().currentActivity())
                                        .permission(Permission.REQUEST_INSTALL_PACKAGES)
                                        .request(new OnPermissionCallback() {
                                            @Override
                                            public void onGranted(List<String> permissions, boolean all) {
                                                if (all) {
                                                    installApkFile(activity, finalFile.getPath());
                                                } else {
                                                    ToastUtils.show("获取部分权限成功，但部分权限未正常授予");
                                                }
                                            }

                                            @Override
                                            public void onDenied(List<String> permissions, boolean never) {
                                                if (never) {
                                                    ToastUtils.show("被永久拒绝授权，请手动授予权限");
                                                    // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                                    XXPermissions.startPermissionActivity(AppManager.getAppManager().currentActivity(), permissions);
                                                } else {
                                                    ToastUtils.show("获取权限失败");
                                                }
                                            }
                                        });
                            }
                        } else {
                            installApkFile(activity, file.getPath());
                        }
                    } else {
                        apkPath = "";
                    }
                } catch (Exception e) {
                    pd.dismiss(); // 结束掉进度条对话框
                    apkPath = "";
                    if (callBack != null) {
                        callBack.onError("安装失败");
                        return;
                    }
                    handler.sendEmptyMessage(3);

                }
                if (callBack != null) {
                    callBack.onSuccess();
                    return;
                }
            }
        }.start();
    }

//    // 安装apk
//    private void installApk(File file, Context context) {
//        Intent intent = new Intent();
//        // 执行动作
//        intent.setAction(Intent.ACTION_VIEW);
//        // 执行的数据类型
//        intent.setDataAndType(Uri.fromFile(file),
//                "application/vnd.android.package-archive");
//        context.startActivity(intent);
//    }

    public void installApkFile(Context context, String filePath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", new File(filePath));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    public File getFileFromServer(String path, ProgressDialog progressDialog)
            throws Exception {
        // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
//            conn.setRequestProperty("Accept-Encoding", "identity");
//            conn.connect();
            int length = conn.getContentLength();
            if (length <= 0) {
                // 获取到文件的大小
                progressDialog.setMax(53684474);
            } else {
                // 获取到文件的大小
                progressDialog.setMax(conn.getContentLength());
            }

//            Log.e("progress_tag", "DownLoadManager_setMax_" + conn.getContentLength());
            InputStream is = conn.getInputStream();

            File file = new File(Environment.getExternalStorageDirectory() + File.separator + "Android/data/" + App.getInstance().getPackageName() + "/Files/");
            if (!file.exists()) {
                file.mkdirs();
            }
            File mF = new File(file.getPath(), "update.apk");
            if (mF.exists()) {
                mF.delete();
            }
            FileOutputStream fos = new FileOutputStream(mF);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                // 获取当前下载量
                progressDialog.setProgress(total);
//                Log.e("progress_tag", "DownLoadManager_setProgress_" + total);
            }
            progressDialog.dismiss();
            fos.close();
            bis.close();
            is.close();
            return mF;
        } else {
            return null;
        }
    }
}
