package com.navinfo.outdoor.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.lzy.okgo.model.HttpParams;
import com.navinfo.outdoor.R;
import com.navinfo.outdoor.api.Constant;
import com.navinfo.outdoor.base.BaseActivity;
import com.kongzue.dialog.util.DialogSettings;
import com.navinfo.outdoor.bean.ApkVersionBean;
import com.navinfo.outdoor.http.Callback;
import com.navinfo.outdoor.http.HttpInterface;
import com.navinfo.outdoor.http.OkGoBuilder;
import com.navinfo.outdoor.util.APKVersionCodeUtils;


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 MainActivity extends BaseActivity {

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what==0){
                Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                //将下载进度对话框取消
                pBar.cancel();
                //调用系统安装程序
                //安装apk，也可以进行静默安装
                Intent intent = new Intent(Intent.ACTION_VIEW);
                File file = new File(Constant.NAVINFO_APk+"DTXB.apk");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(MainActivity.this, "com.navinfo.outdoor.fileprovider", file);
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                } else {
                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }
               startActivity(intent);
            }else if (msg.what==1){
                pBar.setProgress(progress);
            }
            return false;
        }
    });
    private ProgressDialog pBar;
    private int progress;

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData() {
        super.initData();
        //必须全局才可以改变样式
        DialogSettings.style = (DialogSettings.STYLE.STYLE_KONGZUE);
        DialogSettings.init();//初始化清空 BaseDialog 队列
    }

    private void initPermission() {
        XXPermissions.with(this)
                // 申请安装包权限
                //.permission(Permission.REQUEST_INSTALL_PACKAGES)
                // 申请悬浮窗权限
                //.permission(Permission.SYSTEM_ALERT_WINDOW)
                // 申请通知栏权限
                //.permission(Permission.NOTIFICATION_SERVICE)
                // 申请系统设置权限
                //.permission(Permission.WRITE_SETTINGS)
                // 申请单个权限
                .permission(Permission.RECORD_AUDIO)
                // 申请多个权限
                //.permission(Permission.Group.CALENDAR)
                // 申请读写外部存储卡
                .permission(Permission.MANAGE_EXTERNAL_STORAGE/*, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE*/)
                // 申请相机权限
                .permission(Permission.CAMERA)
                .permission(Permission.REQUEST_INSTALL_PACKAGES)
                // 位置权限
                .permission(Permission.ACCESS_FINE_LOCATION)
                //.permission(Permission.ACCESS_BACKGROUND_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                //读写权限
                .permission(Permission.READ_PHONE_STATE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            initCheckVersion();
                            //initTime();
                        } else {
                            initPermission();
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                            MessageDialog.show(MainActivity.this, "提示", permissions.toString() + " 被永久拒绝授权请手动授权,", "确定").setOkButton(new OnDialogButtonClickListener() {
                                @Override
                                public boolean onClick(BaseDialog baseDialog, View v) {
                                    XXPermissions.startPermissionActivity(MainActivity.this, permissions);
                                    finish();
                                    return false;
                                }
                            });

                        }
                    }
                });
    }

    private void initCheckVersion() {
        int versionCode = APKVersionCodeUtils.getVersionCode(this);//获取当前版本号
        HttpParams httpParams = new HttpParams();
        httpParams.put("version", versionCode);
        httpParams.put("operationType", "android");
        showLoadingDialog();
        OkGoBuilder.getInstance()
                .Builder(this)
                .url(HttpInterface.APP_CHECK_VERSION)
                .params(httpParams)
                .cls(ApkVersionBean.class)
                .token(Constant.ACCESS_TOKEN)
                .getRequest(new Callback<ApkVersionBean>() {
                    @Override
                    public void onSuccess(ApkVersionBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode() == 200) {
                            int version = response.getBody().getVersion();
                            if (versionCode <version) {//TODO 改成<
                                //升级
                                ApkVersionBean.bodyBean body = response.getBody();
                                showUpdateDialog(body);
                            } else {//不需要升级
                                initTime();
                            }

                        } else {
                            initTime();
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {
                        dismissLoadingDialog();
                        Toast.makeText(MainActivity.this, e.getMessage()+"", Toast.LENGTH_SHORT).show();
                        initTime();

                    }
                });


    }

    /**
     * 显示升级信息的对话框
     */
    private void showUpdateDialog(ApkVersionBean.bodyBean bodyBean) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setMessage("请升级APP版本至" + bodyBean.getVersion());
        builder.setCancelable(false);
        if (bodyBean.getUpdateState()==0){//非必须更新
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        downFile(bodyBean.getApkUrl());//点击确定将apk下载
                    } else {
                        Toast.makeText(MainActivity.this, "SD卡不可用，请插入SD卡", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //用户点击了取消
                    initTime();
                }
            });
        }else{//强制更新
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        downFile(bodyBean.getApkUrl());//点击确定将apk下载
                    } else {
                        Toast.makeText(MainActivity.this, "SD卡不可用，请插入SD卡", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //用户点击了取消
                    initTime();
                }
            });

        }

        builder.create().show();
    }

    public void initTime() {
        new CountDownTimer(3000, 1000) {
            @Override
            public void onTick(long l) {
            }

            @Override
            public void onFinish() {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
                MainActivity.this.finish();
            }
        }.start();
    }

    /**
     * 下载最新版本的apk
     *
     * @param path apk下载地址
     */
    private void downFile(final String path) {
        pBar = new ProgressDialog(this);
        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pBar.setCancelable(false);
        pBar.setTitle("正在下载...");
        pBar.setMessage("请稍候...");
        pBar.setProgress(0);
        pBar.show();
        new Thread() {
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setReadTimeout(60000);
                    con.setConnectTimeout(15000);
                    con.setRequestProperty("Charset", "UTF-8");
                    con.setRequestMethod("GET");
                    con.connect();
                    if (con.getResponseCode() == 200) {
                        File files = new File(Constant.NAVINFO_APk);
                        if (!files.exists()){
                            files.mkdir();
                        }
                        int length = con.getContentLength();// 获取文件大小
                        InputStream is = con.getInputStream();
                        pBar.setMax(100); // 设置进度条的总长度
                        FileOutputStream fileOutputStream = null;
                        if (is != null) {
                            //对apk进行保存
                            File file = new File(Constant.NAVINFO_APk+"DTXB.apk");
                            fileOutputStream = new FileOutputStream(file);
                            byte[] buf = new byte[1024];
                            int ch;
                            int process = 0;
                            while ((ch = is.read(buf)) != -1) {
                                fileOutputStream.write(buf, 0, ch);
                                process += ch;
                                progress = (int) (((float) process / length) * 100);
                                handler.sendEmptyMessage(1);
                            }
                        }
                        if (fileOutputStream != null) {
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        }
                        //apk下载完成，使用Handler()通知安装apk
                        handler.sendEmptyMessage(0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }.start();
    }



    @Override
    protected void initView() {
        super.initView();
        initPermission();

    }
}