package com.bbitcn.silk.ui.dialog;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.bbitcn.silk.base.BaseDialog;
import com.bbitcn.silk.databinding.DialogCustomBinding;
import com.bbitcn.silk.utils.DialogUtil;
import com.bbitcn.silk.utils.log.MyLog;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.FileUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

import es.dmoral.toasty.Toasty;

/**
 * @Description TODO
 * @Author DuanKaiji
 * @CreateTime 2024年04月02日 16:59:30
 */
public class UpdateDialog extends BaseDialog<DialogCustomBinding> {
    public UpdateDialog(@NonNull Context context, String apkUpdateUrl, String versionName, String versionDescription) {
        this(context, apkUpdateUrl, versionName, versionDescription, false);
    }

    public UpdateDialog(@NonNull Context context, String apkUpdateUrl, String versionName, String versionDescription, boolean isForce) {
        super(context);
        binding.btnYes.setText("更新");
        //询问确定执行的弹窗
        binding.btnYes.setOnClickListener(view -> {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                //点击确定将apk下载
                downFile(context, apkUpdateUrl, versionName);
            } else {
                Toasty.error(context, "SD卡不可用，请插入SD卡").show();
            }
        });
        binding.btnNo.setVisibility(isForce ? View.GONE : View.VISIBLE);
        binding.ivDialogClose.setVisibility(isForce ? View.GONE : View.VISIBLE);
        binding.tvTitle.setText("检测到新版本");
        binding.tvMessage.setText("最新版本：" + versionName + "\n新版本内容：" + versionDescription);
    }

    /**
     * 下载APK
     *
     * @param path 下载地址
     */
    private void downFile(Context context, final String path, String newVersionName) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
            context.startActivity(intent);
            return;
        }
        String fileName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + "智慧共育" + newVersionName + ".apk";
        FileUtils.delete(fileName);
        RequestParams params = new RequestParams(path);
        params.setSaveFilePath(fileName);
        params.setAutoRename(true);
        x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onStarted() {
                DialogUtil.showProgressIndicatorDialog(context, "开始下载新版本");
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                if (isDownloading) {
                    int progress = (int) ((current * 100) / total);
                    DialogUtil.setProgressIndicatorDialog("正在下载新版本，已下载" + progress + "%", progress);
                }
            }

            @Override
            public void onSuccess(File result) {
                MyLog.network("下载成功: " + result);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    installAPK(context, fileName);
                } else {
                    AppUtils.installApp(result);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                MyLog.networkError("下载失败，原因：" + ex.getMessage());
                new ConfirmDialog(context, "提示", "下载失败，原因：" + ex.getMessage(), null).show();

            }

            @Override
            public void onWaiting() {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                DialogUtil.hideProgressIndicatorDialog();

            }
        });
    }

    /**
     * 安装程序
     *
     * @param context  上下文
     * @param filePath 安装的文件路径
     */
    public static void installAPK(Context context, String filePath) {
        try {
            File apkFile = new File(filePath);
            if (apkFile.exists()) {


                Intent intent = new Intent(Intent.ACTION_VIEW);
                Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } else {
                Toasty.error(context, "安装包文件不存在").show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toasty.error(context, "安装失败：" + e.getMessage()).show();
        }
    }
}
