package com.tofly.ghrq_route.common.util.app;

import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.mgq.base.utils.progressdialog.ProgressManager;
import com.mgq.base.utils.toast.ToastUtil;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.common.util.sharedPreference.SharePreUtil;
import com.tofly.ghrq_route.module.checkVersion.controller.VersionContr;
import com.tofly.ghrq_route.module.checkVersion.domain.CheckReslult;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.ui.activity.UiLogin;
import com.tofly.ghrq_route.common.ui.dialog.VersionUpdateHintDialog;
import com.tofly.ghrq_route.common.util.file.FileUtil;

import java.io.File;
import java.text.MessageFormat;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by li on 2017/1/19.
 * 版本更新工具类
 */

public class UpdateManager {
    private ProgressBar mProgressBar;//进度条
    private TextView tv1;
    private TextView tv2;
    private AlertDialog mDownloadDialog;//对话框

    private String mSavePath;//apk保存地址
    private int mProgress;//进度值

    private boolean mIsCancel = false;//是否取消下载标示符

    private static final int DOWNLOADING = 1;//apk下载中
    private static final int DOWNLOAD_FINISH = 2;//apk下载完毕
    private static final int DOWNLOAD_CANCEL = 3;
    private static final int DOWNLOAD_FAILED = 4;
    private long length;

    private static final int HAN_CHECK = 4;
    private static final int HAN_TOAST = 5;

    private String mVersion_code;//软件升级标示号
    private String mVersion_name = "cq_xj_mobile.apk";//apk名
    private String mVersion_desc;//更新详情
    private String mVersion_time; //更新时间
    private String mVersion_note;  //更新内容
    private String mVersion_path;//apk下载地址
    private Context mContext;//上下文
    private ProgressDialog checkProgressDia;
    private VersionContr versionContr;
    private boolean isDownload = false;

    private VersionUpdateHintDialog updateHintDialog;

    public UpdateManager(Context context) {
        mContext = context;
    }

    public static interface iGetVersionInfo {
        void getVersionInfo(CheckReslult checkReslult);
    }


    private Handler mUpdateProgressHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOADING:
                    // 设置进度条
                    long downloaded = (long) msg.arg1;
                    long total = (long) msg.arg2;
                    if (total >=0 && downloaded >= 0){
                        mProgress = Math.round(downloaded * 100 / total) ;
                        mProgressBar.setIndeterminate(false);
                        mProgressBar.setProgress(mProgress);
                        tv1.setText(MessageFormat.format("{0}/100", mProgress));
                    }else {
                        mProgressBar.setIndeterminate(true);
                    }

                    if (downloaded >= 0){
                        length = downloaded;
                        double len = (double) length / 1024.00 / 1024;
                        tv2.setText(String.format("%.2fM", len));
                    }
                    break;
                case DOWNLOAD_CANCEL:
                    isDownload = false;
                    mDownloadDialog.dismiss();
                    ToastUtil.showToast(mContext, "用户取消下载");
                    break;
                case DOWNLOAD_FINISH:
                    // 隐藏当前下载对话框
                    isDownload = false;
                    mDownloadDialog.dismiss();
                    // 安装 APK 文件
                    checkAppCanInstall();
                    break;
                case DOWNLOAD_FAILED:
                    isDownload = false;
                    tv1.setText("下载失败");
                    mDownloadDialog.dismiss();
                    ToastUtil.showToast(mContext, "下载失败!");
                    break;
                default:
                    break;
            }
        }

        ;
    };

    /*
     * 检测软件是否需要更新
     */
    public void checkUpdate() {
        if (isDownload){
            return;
        }

        UserBean user = BaseApp.getInstance().getLoginUser();
        if (user == null)
            return;

        isDownload = true;
        checkProgressDia = new ProgressDialog(this.mContext);
        checkProgressDia.setMessage("正在检测新版本");
        checkProgressDia.setTitle("提 示");
        checkProgressDia.setCanceledOnTouchOutside(false);
        checkProgressDia.setCancelable(true);
        checkProgressDia.show();
        if (versionContr == null) {
            versionContr = new VersionContr(this.mContext);
        }
        int localVersion = AppUtil.getLocalVersionCode(mContext);
        versionContr.getNewVersion(mContext, localVersion + "", (success, what, message, lastVersion) -> {
            if (success && lastVersion != null) {
                String version = lastVersion.getVersionSub();
                mVersion_code = version;
                mVersion_desc = lastVersion.getVersion();
                mVersion_time = lastVersion.getCreateTime();
                mVersion_note = lastVersion.getNotes();
                mVersion_name = lastVersion.getFileName();
                String url = lastVersion.getDownurl();
                mVersion_path = url;

                boolean isMustUpdate = lastVersion.getIsupdate() == 1;
                BaseApp.setIsAppMustUpdate(isMustUpdate);

                if (isUpdate()) {
                    showNoticeDialog(lastVersion, isMustUpdate);
                } else {
                    Toast.makeText(mContext, "已是最新版本", Toast.LENGTH_SHORT).show();
                }

                isDownload = false;
                checkProgressDia.dismiss();
            }else {
                isDownload = false;
                checkProgressDia.dismiss();
                ToastUtil.showToast(mContext, "检测新版本失败：" + message);
            }
        });
    }

    public void getVersionInfo(String version_sub, final iGetVersionInfo iGetVersionInfo) {
        UserBean user = BaseApp.getInstance().getLoginUser();
        if (user == null)
            return;

        if (versionContr == null) {
            versionContr = new VersionContr(this.mContext);
        }

        String strUploading = mContext.getString(R.string.updating_data);
        ProgressManager.getInstance().showProgress(mContext, null, strUploading, true);
        versionContr.getAppInfo(mContext, version_sub, (isSuccess, errorCode, errMsg, reslult) -> {
            ProgressManager.getInstance().cancelProgress();

            CheckReslult checkReslult = null;
            if (isSuccess && reslult != null) {
                checkReslult = reslult;
            }

            if (iGetVersionInfo != null){
                iGetVersionInfo.getVersionInfo(checkReslult);
            }
        });
    }

    /*
     * 与本地版本比较判断是否需要更新
     */
    protected boolean isUpdate() {
        int serverVersion = 1;
        int localVersion = 1;
        try {
           serverVersion = Integer.parseInt(mVersion_code);
        }catch (NumberFormatException e){

        }
        //获得当前apk版本号versionCode
        localVersion = AppUtil.getLocalVersionCode(mContext);
        return serverVersion > localVersion;
    }

    /*
     * 有更新时显示提示对话框
     */
    protected void showNoticeDialog(CheckReslult newVersion, final boolean isMustUpdate) {
        if (updateHintDialog == null) {
            updateHintDialog = new VersionUpdateHintDialog(mContext, newVersion, view -> {
                // 显示下载对话框
                showDownloadDialog(isMustUpdate);
            }, view -> {
                if (isMustUpdate) {
                    gotoUiLogin();
                }
            });
        }
        updateHintDialog.setCanceledOnTouchOutside(!isMustUpdate);
        updateHintDialog.setCancelable(!isMustUpdate);
        updateHintDialog.show();
    }

    private void gotoUiLogin() {
        BaseApp.getInstance().stopBackgroundService(mContext);

        BaseApp.getInstance().finishAllActivity();

        SharePreUtil.setIsNeedReLogin(mContext, true);
        Intent intent = new Intent();
        intent.setClass(mContext, UiLogin.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mContext.startActivity(intent);
    }

    /*
     * 显示正在下载对话框
     */
    protected void showDownloadDialog(boolean isMustUpdate) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_progress, null);
        TextView titleTv = (TextView) view.findViewById(R.id.tv_dialog_title);
        titleTv.setText("下载中");
        mProgressBar = (ProgressBar) view.findViewById(R.id.myprogress);
        tv1 = (TextView) view.findViewById(R.id.progressbar_tv1);
        tv2 = (TextView) view.findViewById(R.id.progressbar_tv2);
        builder.setView(view);

        // 设置按钮(左)
        if (!isMustUpdate){
            builder.setPositiveButton("取消", (dialog, which) -> {
                // 隐藏当前对话框
                dialog.dismiss();
                // 设置下载状态为取消
                mIsCancel = true;
            });

            // 设置按钮(右)
            builder.setNegativeButton("隐藏", (dialog, which) -> dialog.dismiss());
        }

        mDownloadDialog = builder.create();
        mDownloadDialog.setCancelable(false);
        mDownloadDialog.setCanceledOnTouchOutside(false);
        mDownloadDialog.show();

        // 下载文件
        downloadAPK();
    }

    /*
     * 开启新线程下载文件
     */
    private void downloadAPK() {
//        if (versionContr == null){
//            versionContr = new VersionContr(mContext);
//        }
        isDownload = true;
        String url = NetRequestURL.newApi_dyrq.getFormattedDownFile(mVersion_path, mVersion_name);
        Log.w(getClass().getName(), "downloadAPK: url = " + url);
        Uri uri = Uri.parse(url);
        final DownloadManager.Request request = new DownloadManager.Request(uri);
        //request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.setNotificationVisibility(DownloadManager.Request
                .VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        String base = C.dir.base;
        mSavePath = "apk/" + mVersion_name;
        request.setDestinationInExternalFilesDir(mContext,
                Environment.DIRECTORY_DOWNLOADS, mSavePath);
        request.setTitle("巡检系统更新中");
        request.setDescription("下载完后请点击打开");
        request.setMimeType("application/vnd.android.package-archive");

// Ok go!
        final Timer myTimer = new Timer();
        final DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        final long downloadId = dm.enqueue(request);
        final DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (!mIsCancel){
                    Cursor cursor = dm.query(query);
                    if (cursor != null){
                        if (cursor.moveToFirst()){
                            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                            if (status == DownloadManager.STATUS_SUCCESSFUL){
                                myTimer.cancel();
                                mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            }else if (status == DownloadManager.STATUS_FAILED){
                                dm.remove(downloadId);
                                myTimer.cancel();
                                mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FAILED);
                            }else {
                                int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                                int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                                cursor.close();
                                final int dl_progress = (bytes_downloaded * 100 / bytes_total);
                                if (dl_progress == 100){
                                    myTimer.cancel();
                                    mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                                }else {
                                    mUpdateProgressHandler.sendMessage(
                                            mUpdateProgressHandler.obtainMessage(DOWNLOADING, bytes_downloaded, bytes_total));
                                }
                            }
                        }
                    }
                }else {
                    dm.remove(downloadId);
                    myTimer.cancel();
                    mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_CANCEL);
                }
            }
        }, 0, 10);

/*        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor c = dm.query(query);
        if (c != null) {
            if (c.moveToFirst()) {
                String path = mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) +
                        "/apk";
                File file = new File(path, mVersion_name);
                Uri uri1 = Uri.fromFile(file);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(uri1, "application/vnd.android.package-archive");
                mContext.startActivity(intent);
//                Log.w(getClass().getName(), "downloadAPK: uri1 = " + uri1.toString() );
                Log.w(getClass().getName(), "downloadAPK: uri1 = " + c.getColumnNames() );
            }
            c.close();
            isDownload = false;

        }*/
//        requestQueue.add()
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//
//                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//                    if (TextUtils.isEmpty(BaseApp.sdDownloadPath)) {
//                        mSavePath = GlobalContent.dir.download;
//                    } else {
//                        mSavePath = BaseApp.sdDownloadPath;
//                    }
//                    File dir = new File(mSavePath);
//                    if (!dir.exists())
//                        dir.mkdir();
//                    // 下载文件
////                    OkHttpClient client = BaseApp.getInstance().okHttpClient;
//                    OkHttpClient client = new OkHttpClient.Builder().
//                            readTimeout(10, TimeUnit.SECONDS).
//                            writeTimeout(10, TimeUnit.SECONDS).
//                            connectTimeout(10, TimeUnit.SECONDS).
//                            build();
//                    String url = GlobalContent.httpProtocol + GlobalContent.getIpAddress() + mVersion_path;
//                    Log.w("TAG", "run: 下载文件的url = " + url);
//                    Request request = new Request.Builder()
//                            .addHeader("Accept-Encoding", "identity")
//                            .url(url)
//                            .build();
//                    Response response = null;
//                    try {
//                        response = client.newCall(request).execute();
//                        if (response.isSuccessful()) {
//                            ResponseBody body = response.body();
//                            InputStream is = body.byteStream();
//                            final int totallength = (int) body.contentLength();
//                            Log.w("TAG", "run: totallength = " + totallength);
//                            File apkFile = new File(mSavePath, mVersion_name);
//                            FileOutputStream fos = new FileOutputStream(apkFile);
//                            length = 0;
//                            byte[] buffer = new byte[1024];
//                            while (!mIsCancel) {
//                                int numread = is.read(buffer);
//                                length += numread;
//                                // 计算进度条的当前位置
//                                mProgress = (int) (((float) length / totallength) * 100);
//                                Log.w("TAG", "run: mProgress = " + mProgress);
//                                // 更新进度条
//                                mUpdateProgressHandler.sendEmptyMessage(DOWNLOADING);
//
//                                // 下载完成
//                                if (numread < 0) {
//                                    mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FINISH);
//                                    break;
//                                }
//                                fos.write(buffer, 0, numread);
//                            }
//                            if (mIsCancel) {
//                                mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_CANCEL);
//                            }
//                            fos.close();
//                            is.close();
//                        }
//                        response.close();
//
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        };
//
//        ThreadManager.getInstance().createLongPool().execute(runnable);
    }

    private void checkAppCanInstall() {
        boolean installAllowed;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            installAllowed = mContext.getPackageManager().canRequestPackageInstalls();
            if (!installAllowed) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + mContext.getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        }
        installAPK();
    }

    /*
     * 下载到本地后执行安装
     */
    protected void installAPK() {
        File rootFile = mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        File apkFile = new File(rootFile, mSavePath);
        if (!apkFile.exists()){
            ToastUtil.showToast(mContext, "安装包未找到，退出安装!");
            return;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //参数1 上下文, 参数2 Provider主机地址和清单文件中保持一致   参数3 共享的文件
            Uri apkUri = FileUtil.getUri(mContext, apkFile);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);

        SharePreUtil.setRemoveApkPackage(mContext, true);
        SharePreUtil.setApkPackagePath(mContext, apkFile.getPath());
    }
}
