package com.sipai.jspatrol.Loading;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.sipai.jspatrol.Base.ActivityCollector;
import com.sipai.jspatrol.Base.BaseView;
import com.sipai.jspatrol.Bean.Biz;
import com.sipai.jspatrol.Bean.LoginInfo;
import com.sipai.jspatrol.BuildConfig;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.Login.LoginActivity;
import com.sipai.jspatrol.Main.MainActivity;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.utils.EncryptUtils;
import com.sipai.jspatrol.utils.Global.GlobalVal;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.jspatrol.utils.RandomStringUtils;
import com.sipai.jspatrol.utils.SharedPreferencesData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class LoadingActivity extends BaseView<LoadingPresenter, LoadingContract.View> {

    private String mServer;
    private String mServerIP;
    private String mUserid;
    private String mPwd;
    private String mBizid;
    private String mBizName;
    private String mUsername;
    private String lcversion;
    private String androidId = "";
    private String apkname, vercod;
    private ProgressDialog progressDialog;
    private String BASE_URL = "CPELM_APK/";
    private String Nowurl = "";
    private String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.INTERNET, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};
    List<String> mPermissionList = new ArrayList<>();
    private final int mRequestCode = 100;//权限请求码
    private static final int GET_UNKNOWN_APP_SOURCES = 321;
    private static final int RESULT_PRE = 123;
    private HashMap<String, String> map = new HashMap<>();
    private int times = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);
        ActivityCollector.addActivity(this);
        init();
//        SQLiteDatabase db = LitePal.getDatabase();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initPermissions();
    }

    @Override
    protected LoadingPresenter getPresenter() {
        return new LoadingPresenter();
    }

    @Override
    public LoadingContract.View getContract() {
        return new LoadingContract.View<LoginInfo>() {
            @Override
            public void handlerResult(LoginInfo item) {
                if (item != null) {
                    if (item.isStatus()) {
                        saveLoginInfo(item);
//                        registerXG();
                        getComList(item);
                    } else {
                        ToLogin();
                    }
                } else {
                    ToLogin();
                }
            }

            @Override
            public void handlerComResult(String result, String t) {
                if (result.equals(GlobalVal.RESULT_SUCCESS)) {
                    List<Biz> bizs = parseBiz(t);
                    if (bizs.size() > 0) {
                        if (bizs.size()==1){
                            mBizid = bizs.get(0).getBizid();
                            mBizName = bizs.get(0).getName();
                        }else if (mBizName==null||mBizName.isEmpty()){
                            mBizid = bizs.get(0).getBizid();
                            mBizName = bizs.get(0).getName();
                        }
                    }
                    saveBizlist(LoadingActivity.this, "response", mBizid, mBizName, t);
                    MainActivity.actionStart(LoadingActivity.this);
                    finish();
                } else {
                    ToLogin();
                }
            }
        };
    }


    private List<Biz> parseBiz(String result) {
        List<Biz> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(result);
            for (int i = 0; i < array.length(); i++) {
                Biz item = new Biz();
                item.setId(array.getJSONObject(i).optString("id"));
                item.setBizid(array.getJSONObject(i).optString("id"));
                item.setName(array.getJSONObject(i).optString("text"));
                if (item.getName().contains("一车")){
                    mBizid = item.getBizid();
                    mBizName = item.getName();
                }
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return list;
        }
        return list;
    }

    private void getComList(LoginInfo item) {
        map = new HashMap<>();
        p.getContract().requestComList(LoadingActivity.this, map, mServer, MethodURL.ComList_Method, item.getUser().getToken());
    }

    private void saveBizlist(Context context, String response, String bizid, String bizname, String t) {
        //获取SharedPreferences对象
        SharedPreferences sharedPre = context.getSharedPreferences("config", MODE_PRIVATE);
        //获取Editor对象
        SharedPreferences.Editor editor = sharedPre.edit();
        editor.putString("bizlist", response);
        editor.putString("bizid", bizid);
        editor.putString("bizname", bizname);
        editor.putString("biz", t);
        //提交
        editor.commit();
    }

    private void saveLoginInfo(LoginInfo item) {
        SharedPreferencesData sharedPreferencesData = new SharedPreferencesData(this);
        Map<String, String> map = new HashMap<>();
        map.put("userid", item.getUser().getId());
        map.put("caption", item.getUser().getCaption());
        map.put("name", item.getUser().getName());
        map.put("totaltime", String.valueOf(Math.round(item.getUser().getTotaltime())));
        map.put("lastlogintime", item.getUser().getLastlogintime());
        map.put("nfc", item.getUser().getNfc());
        map.put("subtask", item.getUser().getSubTask());
        sharedPreferencesData.saveInfo(map);
    }

    private void init() {
        SharedPreferences sharedPre = getSharedPreferences("config", MODE_PRIVATE);
        mServer = sharedPre.getString("server", "");
        mServerIP = sharedPre.getString("serverip", "");
        mUserid = sharedPre.getString("userid", "");
        mPwd = sharedPre.getString("password", "");
        mBizid = sharedPre.getString("bizid", "");
        mBizName = sharedPre.getString("bizname", "");
        mUsername = sharedPre.getString("username", "");
        lcversion = getLocalVersionName(this);
        TelephonyManager tm = (TelephonyManager) LoadingActivity.this.getSystemService(TELEPHONY_SERVICE);
//        mtyb = android.os.Build.BRAND;// 手机品牌
//        mtype = android.os.Build.MODEL; // 手机型号
//                imei = tm.getDeviceId();//uuid
        androidId = Settings.System.getString(
                getContentResolver(), Settings.Secure.ANDROID_ID);//10.0以后获取不到UUID，用androidId来代表唯一性
    }

    private void check() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                if (!LoadingActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                            startActivityForResult(intent, 350);
                        }
                    });
                }
            } else {
                final int nWelcomeScreenDisplay = 1000;
                if (mServer != null && !mServer.isEmpty()) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            checkAPKVersion();
                        }
                    }, nWelcomeScreenDisplay);
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ToLogin();
                        }
                    }, nWelcomeScreenDisplay);
                }
            }

        } else {
            final int nWelcomeScreenDisplay = 1000;
            if (mServer != null && !mServer.isEmpty()) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        checkAPKVersion();
//                    login();
                    }
                }, nWelcomeScreenDisplay);
            } else {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ToLogin();
                    }
                }, nWelcomeScreenDisplay);
            }
        }
    }

    /**
     * 检测服务器APK版本
     */
    private void checkAPKVersion() {
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.Check_Apk_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
                login();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(res);
                    if (res != null && !res.isEmpty()) {
                        apkname = jsonObject.getString("ApkName");
                        int ind = apkname.lastIndexOf("-");
                        int end = apkname.lastIndexOf(".");
                        vercod = apkname.substring(ind + 1, end);
                        BASE_URL = getString(R.string.appflag) + "_APK/";
                        Nowurl = mServer + BASE_URL + apkname;
                        if (Double.valueOf(lcversion) < Double.valueOf(vercod)) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    new SweetAlertDialog(LoadingActivity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("提示")
                                            .setContentText("检测到有新版本，是否更新？")
                                            .setConfirmText("确认")
                                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                                @Override
                                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                    sweetAlertDialog.dismissWithAnimation();
                                                    String path = Environment.getExternalStorageDirectory() + "/" + getString(R.string.appflag) + "/" + getString(R.string.appflag) + "_APK/";
                                                    downloadFile(Nowurl, path);
                                                }
                                            }).setCancelText("取消")
                                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                                @Override
                                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                    sweetAlertDialog.dismissWithAnimation();
                                                    login();
                                                }
                                            }).show();

                                }
                            });

                        } else {
                            login();
                        }
                    }
                } catch (Exception e) {
                    login();
                }
            }
        });
    }

    private void downloadFile(String nowurl, String path) {
        File filep = new File(path);
        if (!filep.exists()) {
            filep.mkdirs();
        }
        filep = null;
        progressDialog = new ProgressDialog(this);
        org.xutils.http.RequestParams requestParams = new org.xutils.http.RequestParams(nowurl);
        requestParams.setAutoRename(false);
        requestParams.setSaveFilePath(path + apkname);
        x.http().get(requestParams, new org.xutils.common.Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {
            }

            @Override
            public void onStarted() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoadingActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.setMessage("下载中...");
                progressDialog.show();
                progressDialog.setProgressNumberFormat("");

                progressDialog.setMax((int) total);
                progressDialog.setProgress((int) current);
            }


            @Override
            public void onSuccess(File result) {
                Toast.makeText(LoadingActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
                //下载成功,file为下载好的APk文件
                File file = result;
                Log.d("xutil", "下载成功");
                //安装apk的方法
                installAPK(file);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                Toast.makeText(LoadingActivity.this, "下载失败，请检查网络和SD卡", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
                login();
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void login() {
        if (mUsername != null && !mUsername.isEmpty() && mPwd != null && !mPwd.isEmpty()) {
            map = new HashMap<>();
            String p_pwd = "";
            String vcode = "";
            String code = RandomStringUtils.getRandomStr(1,4);
            try {
                vcode = "64368180";
                vcode = "64368180"+code;
                vcode = EncryptUtils.encrypt(vcode).replace("\n","");
                code = EncryptUtils.encrypt(code).replace("\n","");
                vcode = URLEncoder.encode(vcode,"UTF-8");
                code = URLEncoder.encode(code,"UTF-8");
                p_pwd = URLEncoder.encode(mPwd,"UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put("j_password",p_pwd);
            map.put("j_username",mUsername);
            map.put("androidId",androidId);
            map.put("verCode",vcode);
            map.put("code",code);
            p.getContract().requestData(LoadingActivity.this,map,mServer, MethodURL.Login_Method);
        } else {
            ToLogin();
        }
    }

    private void ToLogin() {
        Intent intent = new Intent(LoadingActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    private void initPermissions() {
        if (Build.VERSION.SDK_INT >= 26) {
            boolean isAllowed = getPackageManager().canRequestPackageInstalls();
            if (isAllowed) {
                for (int i = 0; i < permissions.length; i++) {
                    if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                        mPermissionList.add(permissions[i]);//添加还未授予的权限
                    }
                }
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (mPermissionList.size() > 0) {
                    // 如果没有授予该权限，就去提示用户请求
                    ActivityCompat.requestPermissions(this, permissions, mRequestCode);
                } else {
                    check();
                }
            } else {
                //无权限 申请权限
                showInstallAPKDialog();
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                for (int i = 0; i < permissions.length; i++) {
                    if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                        mPermissionList.add(permissions[i]);//添加还未授予的权限
                    }
                }
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (mPermissionList.size() > 0) {
                    // 如果没有授予该权限，就去提示用户请求
                    ActivityCompat.requestPermissions(this, permissions, mRequestCode);
                } else {
                    check();
                }
            } else {
                check();
            }
//            check();
        }
    }

    /**
     * 获取本地软件版本号名称
     */
    public static String getLocalVersionName(Context ctx) {
        String localVersion = "";
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionName;
//            LogUtil.d("TAG", "本软件的版本号。。" + localVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    private void showInstallAPKDialog() {
        if (!LoadingActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(LoadingActivity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("提示")
                            .setContentText("检测到暂无APP安装权限，请前往开启，以便检测最新版本！")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    //将用户引导至安装未知应用界面。
                                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                                    startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);
                                }
                            }).show();
                }
            });
        }
    }

    private void showHaveNewAPKDialog(final String durl) {
        if (!LoadingActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(LoadingActivity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("提示")
                            .setContentText("检测到有新版本，请更新")
                            .setConfirmText("确认")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    String path = Environment.getExternalStorageDirectory() + "/" + getString(R.string.app_flag) + "/" + getString(R.string.app_flag) + "_APK/";
//                                    downloadFile(durl, path);
                                }
                            })
                            .show();
                }
            });
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDismiss = false;//有权限没有通过
        if (mRequestCode == requestCode) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = true;
                }
            }
            if (hasPermissionDismiss) {
                // 用户还是想用我的 APP 的
                // 提示用户去应用设置界面手动开启权限
                showDialogTipUserGoToAppSettting();
            } else {
                if (times == 0) {
                    times = times + 1;
                    check();
                }
            }
        }
    }

    // 提示用户去应用设置界面手动开启权限

    private void showDialogTipUserGoToAppSettting() {
        if (!LoadingActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(LoadingActivity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("部分权限不可用")
                            .setContentText("请在-应用设置-权限-中，点击允许")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    goToAppSetting();
                                }
                            }).show();
                }
            });
        }
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, RESULT_PRE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK) {
                } else {
                    LoginNow();
                }
                break;
//            case GET_UNKNOWN_APP_SOURCES:
//                initPermissions();
//                break;
            case RESULT_PRE:
                if (resultCode == RESULT_OK) {
                    LoginNow();
                }
                break;
            case 350:
                check();
                break;
        }
    }

    /**
     * 登录
     */
    private void LoginNow() {
        if (mUsername != null && !mUsername.isEmpty() && mPwd != null && !mPwd.isEmpty()) {
            map = new HashMap<>();
            String p_pwd = "";
            String vcode = "";
            String code = RandomStringUtils.getRandomStr(1,4);
            try {
                vcode = "64368180";
                vcode = "64368180"+code;
                vcode = EncryptUtils.encrypt(vcode).replace("\n","");
                code = EncryptUtils.encrypt(code).replace("\n","");
                vcode = URLEncoder.encode(vcode,"UTF-8");
                code = URLEncoder.encode(code,"UTF-8");
                p_pwd = URLEncoder.encode(mPwd,"UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put("j_password",p_pwd);
            map.put("j_username",mUsername);
            map.put("androidId",androidId);
            map.put("verCode",vcode);
            map.put("code",code);
            p.getContract().requestData(LoadingActivity.this,map,mServer, MethodURL.Login_Method);
        } else {
            ToLogin();
        }
    }

    /**
     * 开启安装APK页面的逻辑
     *
     * @param file 要安装的APK文件
     */
    private void installAPK(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //版本在7.0以上是不能直接通过uri访问的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            File file = (new File(apkPath));
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".fileProvider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}
