package com.bjzc.zjyxdxj.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.azhon.appupdate.listener.OnButtonClickListener;
import com.azhon.appupdate.listener.OnDownloadListener;
import com.azhon.appupdate.manager.DownloadManager;
import com.bjzc.zjyxdxj.base.BaseCallBackNoProgress;
import com.bjzc.zjyxdxj.R;
import com.bjzc.zjyxdxj.base.BaseActivity;
import com.bjzc.zjyxdxj.bean.ApkUpdateBean;
import com.bjzc.zjyxdxj.bean.PhoneInfo;
import com.bjzc.zjyxdxj.bean.UserInfo;
import com.bjzc.zjyxdxj.contans.Contans;
import com.bjzc.zjyxdxj.utils.ControllerActivity;
import com.bjzc.zjyxdxj.utils.GsonUtils;
import com.bjzc.zjyxdxj.utils.HttpListener;
import com.bjzc.zjyxdxj.utils.HttpUtils;
import com.bjzc.zjyxdxj.utils.NetworkUtil;
import com.bjzc.zjyxdxj.utils.NohttpUtils;
import com.bjzc.zjyxdxj.utils.RSAUtils;
import com.bjzc.zjyxdxj.utils.SPUtils;
import com.bjzc.zjyxdxj.utils.StatusBarUtil;
import com.bjzc.zjyxdxj.utils.UiUtlis;
import com.google.gson.Gson;
import com.tencent.bugly.crashreport.CrashReport;
//import com.yanzhenjie.permission.AndPermission;
//import com.yanzhenjie.permission.runtime.Permission;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;

import retrofit2.Call;

public class LoginActivity extends BaseActivity {


    AppCompatTextView title;
    TextView tvVersion;
    CheckBox savePwUser;
    EditText etUse;
    EditText etPwd;
    Button btnLogin;
    RadioGroup rg;

    private String UserID;
    private String UserPwd;
    private String networkCheckType;
    private long exitTime = 0;

    @Override
    public int getContentViewID() {
        return R.layout.activity_login;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initView() {

        title = findViewById(R.id.title);
        tvVersion = findViewById(R.id.tv_version);
        savePwUser = findViewById(R.id.save_pw_user);
        etUse = findViewById(R.id.et_use);
        etPwd = findViewById(R.id.et_pwd);
        btnLogin = findViewById(R.id.btn_login);
        rg = findViewById(R.id.rg);

        tvVersion.setText("版本V" + getVersionName());
        StatusBarUtil.transparencyBar(LoginActivity.this);//设置透明状态栏

        String UserIDTemp = (String) SPUtils.get(LoginActivity.this, Contans.USERID, "");
        String UserPwdTemp = (String) SPUtils.get(LoginActivity.this, Contans.USERPWD, "");

//        Log.i("app", "--------->");
//        Log.i("app", UserIDTemp);
//        Log.i("app", UserPwdTemp);
        showLog("LoginActivity");

        boolean save = (boolean) SPUtils.get(LoginActivity.this, "save", true);
        networkCheckType = (String) SPUtils.get(LoginActivity.this, Contans.NETWORK_CHECK_TYPE, "");
        if (!TextUtils.isEmpty(networkCheckType)) {
            if (networkCheckType.equals("内网")) {
                this.rg.check(R.id.rb1);
                Contans.IP = Contans.network_type_Intranet;
            }
            if (networkCheckType.equals("外网")) {
                this.rg.check(R.id.rb2);
                Contans.IP = Contans.network_type_extranet;
            }
        } else {
            this.rg.check(R.id.rb2);
            SPUtils.put(LoginActivity.this, Contans.NETWORK_CHECK_TYPE, "外网");
            Contans.IP = Contans.network_type_extranet;
        }

        if (!TextUtils.isEmpty(UserIDTemp)) {
            UserID = RSAUtils.decryptBASE64StrLocal(UserIDTemp);
            etUse.setText(UserID);
        }
        savePwUser.setChecked(save);

        if (save) {
            if (!TextUtils.isEmpty(UserPwdTemp)) {
                UserPwd = RSAUtils.decryptBASE64StrLocal(UserPwdTemp);
                etPwd.setText(UserPwd);
            }
        }

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb1) {
                    SPUtils.put(LoginActivity.this, Contans.NETWORK_CHECK_TYPE, "内网");
                    Contans.IP = Contans.network_type_Intranet;
                } else if (checkedId == R.id.rb2) {
                    SPUtils.put(LoginActivity.this, Contans.NETWORK_CHECK_TYPE, "外网");
                    Contans.IP = Contans.network_type_extranet;
                }
            }
        });
        //initNFC();

//        etUse.setText("181145");
//        etPwd.setText("13902576510");

        etUse.setText("180701");
        etPwd.setText("13902576186");

    }

    public void initData() {
        CrashReport.putUserData(context, "UserName", UserID);
        onclick();
        String UserIDTemp = (String) SPUtils.get(LoginActivity.this, Contans.USERID, "");
        String username = RSAUtils.decryptBASE64StrLocal(UserIDTemp);
        if (!TextUtils.isEmpty(username)) {
            //检查最后登录时间，如果超过10天就不自动跳转到首页，需要重新登录
            if (checkLogin()) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        } else {
            checkUpdateApk();
        }
    }

    private boolean checkLogin() {
        String lastLoginDate = (String) SPUtils.get(LoginActivity.this, Contans.LASTLOGINDATE, String.valueOf(""));
        //Log.i("app",lastLoginDate);
        //lastLoginDate="2022年02月18日";
        //Log.i("app",lastLoginDate);
        if (!TextUtils.isEmpty(lastLoginDate)) {
            try {
                //格式化日期的对象(转化成习惯的时间格式)
                SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy年MM月dd日");
                Date date = sdFormat.parse(lastLoginDate);
                Calendar calendarOne = Calendar.getInstance();
                calendarOne.setTime(date);
                if (!Calendar.getInstance().after(calendarOne)) {
                    return true;
                }
            } catch (Exception e) {

            }
        }
        return false;
    }


    private void onclick() {
        btnLogin.setOnClickListener(view -> {
            if (isLogin()) {
                if (NetworkUtil.hasNetWorkStatus(context, false)) {
                    Log.i("app", "有网络");
                    OnlineLogin();
                } else {
                    Log.i("app", "无网络");
                    OfflineLogin();
                }
            }
        });
    }

    private void OfflineLogin() {
        if (UserID.equals("")) {
            showToast("首次登陆请连接厂内WIFI");
        } else {
            if (!UserID.equals(etUse.getText().toString())) {
                showToast("工号错误");
            } else {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        }
    }

    private void OnlineLogin() {
        String json = getPhoneInfo();
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.LOGIN, RequestMethod.POST);
//        SSLSocketFactory socketFactory = NohttpUtils.getSSLSocketFactory(context);
//        if(socketFactory!=null){
//            request.setSSLSocketFactory(socketFactory);
//            request.setHostnameVerifier(new HostnameVerifier() {
//                @Override
//                public boolean verify(String s, SSLSession sslSession) {
//                    return true;
//                }
//            });
//        }
        request.setDefineRequestBodyForJson(json);
        NohttpUtils.getInstance().add(LoginActivity.this, 0, request, callback, true, true, "登录中...");
    }

    private HttpListener<String> callback = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) throws ParseException {
            String json = response.get();
            showLog("login-----");
            showLog(json);

            String jsonDecode = RSAUtils.decryptBASE64StrByPublic(json);
            if(TextUtils.isEmpty(jsonDecode)){
                showToast("登录异常...");
            }else{
                UserInfo userInfo = GsonUtils.GsonToBean(jsonDecode, UserInfo.class);
                showLog(new Gson().toJson(userInfo));
                showLog(jsonDecode);

                if (userInfo != null) {
                    UserInfo.User user = userInfo.getRows().get(0);
                    String status = user.getStatus();
                    String username = user.getUsernames();
                    String token = user.getToken();
                    switch (status) {
                        case "0":
                            showToast("用户名或密码错误");
                            break;
                        case "1":
                            SPUtils.put(LoginActivity.this, "save", savePwUser.isChecked());
                            SPUtils.put(LoginActivity.this, Contans.USERID, RSAUtils.encryptBASE64StrLocal(etUse.getText().toString()));
                            SPUtils.put(LoginActivity.this, Contans.USERPWD, RSAUtils.encryptBASE64StrLocal(etPwd.getText().toString()));
                            SPUtils.put(LoginActivity.this, Contans.LOGIN_TOKEN, RSAUtils.encryptBASE64StrLocal(token));
                            SPUtils.put(LoginActivity.this, Contans.USERNAME, username);
                            SPUtils.put(LoginActivity.this, Contans.REQUEST_ID, RSAUtils.encryptBASE64StrLocal(user.getId()));
                            SPUtils.put(LoginActivity.this, Contans.BZBH, user.getBzbh() == null ? "" : user.getBzbh());
                            SPUtils.put(LoginActivity.this, Contans.BZMC, user.getBzmc() == null ? "" : user.getBzmc());
                            SPUtils.put(LoginActivity.this, Contans.PERMISSIONSRESULT, user.getPermissionsResult() == null ? "" : user.getPermissionsResult());
                            SPUtils.put(LoginActivity.this, Contans.ZY, user.getZY() == null ? "" : user.getZY());
                            SPUtils.remove(context, Contans.NFCBM);
                            //格式化日期的对象(转化成习惯的时间格式)
                            SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy年MM月dd日");
                            //静态方法getInstance()使用默认时区和语言环境获得一个日历。
                            Calendar calendar = Calendar.getInstance();
                            //输出当前系统时间;
                            //System.out.println("当前系统时间: "+sdFormat.format(calendar.getTime()));
                            //add()增加日期，以天为单位（Calendar封装了很多静态的操作时间的单位）
                            //增加10天，负数则为减少天数
                            calendar.add(Calendar.DATE, 10);
                            //输出增加10天后的时间;
                            //System.out.println("增加10天后的时间: "+sdFormat.format(calendar.getTime()));
                            //输出时间为2020年的第100天
                            Date date = sdFormat.parse(sdFormat.format(calendar.getTime()));
                            Calendar calendarOne = Calendar.getInstance();
                            calendarOne.setTime(date);
                            SPUtils.put(LoginActivity.this, Contans.LASTLOGINDATE, sdFormat.format(calendarOne.getTime()));
                            //System.out.println("加10天后的日期: "+sdFormat.format(calendarOne.getTime()));
                            //System.out.println("登录已失效: "+String.valueOf(Calendar.getInstance().after(calendarOne)));


                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                            break;
                        case "2":
                            showToast("登录异常...");
                            break;
                        case "3":
                            showToast("未激活或未授权...");
                            break;
                        case "4":
                            showToast("禁止登陆...");
                            break;
                    }
                } else {
                    showToast(UiUtlis.getString(context, R.string.login_no_connect_to_server));
                }
            }
        }

        @Override
        public void onFailed(int what, Response<String> response) {
            showToast(UiUtlis.getString(context, R.string.login_no_connect_to_server));
        }
    };

    @SuppressLint({"MissingPermission", "HardwareIds"})
    public String getPhoneInfo() {
        String imei;
        TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (Build.VERSION.SDK_INT < 29) {
            imei = manager.getDeviceId();//IMEI
        } else {
            imei = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        }
        String model = Build.MODEL;//手机型号
        String sysVersion = Build.VERSION.RELEASE;//系统版本
        PhoneInfo info = new PhoneInfo();
        info.setTotal(1);
        List<PhoneInfo.UserInfo> list = new ArrayList<>();
        PhoneInfo.UserInfo userInfo = new PhoneInfo.UserInfo();
        userInfo.setImeinum(imei);
        userInfo.setSysversion(sysVersion);
        userInfo.setPhonemodel(model);
        userInfo.setPhonenum("");
        userInfo.setUsername(UiUtlis.getText(etUse));
        userInfo.setPassword(UiUtlis.getText(etPwd));
        //公钥加密处理
//        userInfo.setUsername(RSAUtils.encryptBASE64Str(UiUtlis.getText(etUse)));
//        userInfo.setPassword(RSAUtils.encryptBASE64Str(UiUtlis.getText(etPwd)));
        list.add(userInfo);
        info.setRows(list);
        String json = GsonUtils.GsonString(info);
        showLog(json);
        showLog(RSAUtils.encryptBASE64Str(json));
        return RSAUtils.encryptBASE64Str(json);
    }

    public String getNfcInfo(String nfcId) {
        Map<String, String> map = new HashMap();
        map.put("Action", "UserLogin_NFC");
        map.put("NFC", nfcId);
        return GsonUtils.GsonString(map);
    }

    private boolean isLogin() {
        if (TextUtils.isEmpty(etUse.getText().toString()) && TextUtils.isEmpty(etPwd.getText().toString())) {
            showToast("用户名和密码不能为空");
            return false;
        } else if (TextUtils.isEmpty(etUse.getText().toString())) {
            showToast("用户名不能为空");
            return false;
        } else if (TextUtils.isEmpty(etPwd.getText().toString())) {
            showToast("密码不能为空");
            return false;
        } else {
            return true;
        }
    }


    private String getVersionName() {
        PackageManager pm = getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void checkUpdateApk() {

        HttpUtils.getApi(context).getCheckUpdataApk().enqueue(new BaseCallBackNoProgress<ApkUpdateBean>(context) {
            @Override
            public void onSuccess(Call<ApkUpdateBean> call, retrofit2.Response<ApkUpdateBean> response) {
                ApkUpdateBean appUploadInfo = response.body();
                if (appUploadInfo != null) {
                    if (appUploadInfo.getTotal() != null && appUploadInfo.getTotal().equals("1")) {
                        String appURL = appUploadInfo.getRows().get(0).getApkurl();
                        String appversionname = appUploadInfo.getRows().get(0).getVersionname();
                        String versioncode = appUploadInfo.getRows().get(0).getVersioncode();
                        String appdesc = appUploadInfo.getRows().get(0).getAppdesc();

                        if (appURL != null && appURL.contains("http://")) {
                            int startIndex = appURL.indexOf("Apps");
                            //Log.i("app", String.valueOf(startIndex));
                            if (startIndex != -1) {
                                String baseApkUrl = appURL.substring(startIndex);
                                appURL = Contans.IP + baseApkUrl;
                                //Log.i("app",appURL);
                            }
                        } else {
                            appURL = Contans.IP + appURL;
                        }

                        if (!appversionname.equals(getVersionName())) {
                            DownloadAndInstall(appURL, appversionname, appdesc, versioncode);
                        }
                    }
                }
            }

            @Override
            public void onError(Call<ApkUpdateBean> call, Throwable t) {
            }
        });
    }

    private void DownloadAndInstall(String downloadURL, String versionName, String description, String versionCode) {
        new DownloadManager.Builder(this)
                .apkUrl(downloadURL)
                .apkName("中粤能源点巡检.apk")
                .smallIcon(R.mipmap.logo1)
                .showNewerToast(true)
                .apkVersionCode(Integer.parseInt(versionCode))
                .apkVersionName(versionName)
                .apkDescription(description)
                .enableLog(true)
                .jumpInstallPage(true)
                .dialogButtonTextColor(Color.WHITE)
                .dialogButtonColor(Color.parseColor("#FF8247"))
                .dialogProgressBarColor(Color.parseColor("#FF8247"))
                .showNotification(true)
                .showBgdToast(true)
                .forcedUpgrade(true)
                .onDownloadListener(new OnDownloadListener() {
                    @Override
                    public void start() {

                    }

                    @Override
                    public void downloading(int i, int i1) {

                    }

                    @Override
                    public void done(@NonNull File file) {

                    }

                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void error(@NonNull Throwable throwable) {

                    }
                }).onButtonClickListener(new OnButtonClickListener() {
                    @Override
                    public void onButtonClick(int i) {

                    }
                }).build().download();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                showToast("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                NohttpUtils.getInstance().cancelAll();
                ControllerActivity.getAppManager().finishAllActivity();
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private HttpListener<String> callbackNfc = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) throws ParseException {
            String json = response.get();
            Log.i("app", json);
            UserInfo userInfo = GsonUtils.GsonToBean(json, UserInfo.class);
            if (userInfo != null) {
                UserInfo.User user = userInfo.getRows().get(0);
                String status = user.getStatus();
                String username = user.getUsernames();
                switch (status) {
                    case "0":
                        showToast("NFC登录失败，无此用户");
                        break;
                    case "1":
                        SPUtils.put(context, "save", savePwUser.isChecked());
                        SPUtils.remove(context, Contans.USERPWD);
                        SPUtils.put(context, Contans.USERID, user.getUsername());
                        SPUtils.put(context, Contans.USERNAME, username);
                        SPUtils.put(context, Contans.BZBH, user.getBzbh() == null ? "" : user.getBzbh());
                        SPUtils.put(context, Contans.BZMC, user.getBzmc() == null ? "" : user.getBzmc());
                        SPUtils.put(context, Contans.PERMISSIONSRESULT, user.getPermissionsResult() == null ? "" : user.getPermissionsResult());
                        SPUtils.put(LoginActivity.this, Contans.ZY, user.getZY() == null ? "" : user.getZY());
                        //格式化日期的对象(转化成习惯的时间格式)
                        SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy年MM月dd日");
                        //静态方法getInstance()使用默认时区和语言环境获得一个日历。
                        Calendar calendar = Calendar.getInstance();
                        //输出当前系统时间;
                        //System.out.println("当前系统时间: "+sdFormat.format(calendar.getTime()));
                        //add()增加日期，以天为单位（Calendar封装了很多静态的操作时间的单位）
                        //增加10天，负数则为减少天数
                        calendar.add(Calendar.DATE, 10);
                        //输出增加10天后的时间;
                        //System.out.println("增加10天后的时间: "+sdFormat.format(calendar.getTime()));
                        //输出时间为2020年的第100天
                        Date date = sdFormat.parse(sdFormat.format(calendar.getTime()));
                        Calendar calendarOne = Calendar.getInstance();
                        calendarOne.setTime(date);
                        SPUtils.put(LoginActivity.this, Contans.LASTLOGINDATE, sdFormat.format(calendarOne.getTime()));
                        //System.out.println("加10天后的日期: "+sdFormat.format(calendarOne.getTime()));
                        //System.out.println("登录已失效: "+String.valueOf(Calendar.getInstance().after(calendarOne)));

                        Intent intent = new Intent(context, MainActivity.class);
                        startActivity(intent);
                        finish();
                        break;
                    case "2":
                        showToast("登录异常...");
                        break;
                    case "3":
                        showToast("未激活或未授权...");
                        break;
                    case "4":
                        showToast("禁止登陆...");
                        break;
                }
            } else {
                showToast(UiUtlis.getString(context, R.string.data_error));
            }
        }

        @Override
        public void onFailed(int what, Response<String> response) {
        }
    };

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

    @Override
    public void handleNfc(String result) {
        super.handleNfc(result);
        //nfcOnlineLogin(result);
    }
}