package com.example.administrator.zhapp.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.administrator.zhapp.BuildConfig;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.entity.PhoneInfo;
import com.example.administrator.zhapp.entity.UserInfo;
import com.example.administrator.zhapp.utils.ControllerActivity;
import com.example.administrator.zhapp.utils.GsonUtils;
import com.example.administrator.zhapp.utils.HttpListener;
import com.example.administrator.zhapp.utils.NetworkAvailableUtils;
import com.example.administrator.zhapp.utils.NohttpUtils;
import com.example.administrator.zhapp.utils.RSAUtils;
import com.example.administrator.zhapp.utils.SPUtils;
import com.example.administrator.zhapp.utils.UiUtlis;
import com.orhanobut.logger.Logger;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.yanzhenjie.permission.AndPermission;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.litepal.tablemanager.Connector;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;

/**
 * 登录界面
 */
public class LoginActivity extends BaseActivity {

    EditText et_use;
    EditText et_pwd;
    Button btn_login;
    RadioButton rb1;
    RadioButton rb2;
    RadioGroup rg;
    TextView tvVersion;
    CheckBox savePwUser;
    private String username;
    private String pwd;
    private long exitTime = 0;
    private boolean first;

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

    @Override
    protected void initView() {

        title = findViewById(R.id.title);
        tvVersion = findViewById(R.id.tv_version);
        savePwUser = findViewById(R.id.save_pw_user);
        et_use = findViewById(R.id.et_use);
        et_pwd = findViewById(R.id.et_pwd);
        btn_login = findViewById(R.id.btn_login);
        rg = findViewById(R.id.rg);
        rb1 = findViewById(R.id.rb1);
        rb2 = findViewById(R.id.rb2);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        AndPermission.with(this).requestCode(100).permission(
                Manifest.permission.CAMERA,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).send();

        //第一次进入，就创建文件夹
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            File sd = Environment.getExternalStorageDirectory();
            String path = sd.getAbsolutePath() + File.separator + "/com.rehome.ydapp/images";
            File file1 = new File(path);
            if (!file1.exists()) {
                file1.mkdirs();
            }
        }

        rb1.setChecked((Boolean) SPUtils.get(context, Contans.WIFI_4G, true));
        rb2.setChecked(!(Boolean) SPUtils.get(context, Contans.WIFI_4G, true));


        tvVersion.setText("版本" + getVersionName());
        username = (String) SPUtils.get(LoginActivity.this, Contans.USERNAME, "");
        String UserPwdTemp = (String) SPUtils.get(LoginActivity.this, Contans.USERPWD, "");
        boolean save = (boolean) SPUtils.get(LoginActivity.this, "save", true);
        savePwUser.setChecked(save);
        et_use.setText(username);

        if (save) {
            if (!TextUtils.isEmpty(UserPwdTemp)) {
                pwd = RSAUtils.decryptBASE64StrLocal(UserPwdTemp);
                et_pwd.setText(pwd);
            }
        }
        first = (boolean) SPUtils.get(this, Contans.FIRST, true);

//        String wifi = (String) SPUtils.get(context, Contans.KEY_WIFI_IP, "");
//        String mob = (String) SPUtils.get(context, Contans.KEY_4G_IP, "");

//        if (wifi.equals("") && mob.equals("")) {
//
//            //SPUtils.put(this, Contans.KEY_4G_IP, "http://192.168.2.215:9005/");
//
//            SPUtils.put(this, Contans.KEY_4G_IP, "http://219.131.195.3:8081/");
//            SPUtils.put(this, Contans.KEY_WIFI_IP, "http://10.19.0.72:8081/");
//
//
////            SPUtils.put(this, Contans.KEY_4G_IP, "http://192.168.2.134:8082/");
////            SPUtils.put(this, Contans.KEY_WIFI_IP, "http://192.168.2.134:8082/");
//        }

        if (BuildConfig.LOG_ERROR) {

//            et_use.setText("BA01");
//            et_pwd.setText("123");

//            et_use.setText("990001");
//            et_pwd.setText("000000");
//
//            et_use.setText("990002");
//            et_pwd.setText("000000");

//            et_use.setText("310258");
//            et_pwd.setText("Shi&7791");



//            et_use.setText("FGTL01");
//            et_pwd.setText("123");

//            et_use.setText("310673");
//            et_pwd.setText("Abcd@1234");

//            et_use.setText("310482");
//            et_pwd.setText("310482");

//            et_use.setText("FK1");
//            et_pwd.setText("123456");

            //谭添欢（燃料运行E班）
//            et_use.setText("310273");
//            et_pwd.setText("@Tth310273");
            //文华鲲(燃料运行C班)
            et_use.setText("310295");
            et_pwd.setText("@Whk310295");

        }
    }

    public void initData() {

        //setTitle("生产管理移动APP登录系统");
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (rb1.isChecked()) {
                    Contans.IP = Contans.IP_INTRANET;
                    //Contans.IP = "http://192.168.2.215:9005/";
                    showLog(Contans.IP);
                }
                if (rb2.isChecked()) {
                    Contans.IP = Contans.IP_EXTRANET;
                    //Contans.IP = "http://192.168.2.215:9005/";
                    showLog(Contans.IP);
                }

                //如果没网络，然后有账号，直接登录
                if (NetworkAvailableUtils.isNetworkAvailable(context)) {
                    if (isLogin()) {
                        String json = getPhoneInfo();
                        showLog(json);
                        showLog(Contans.IP + Contans.LOGIN);

                        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.LOGIN, RequestMethod.POST);
                        request.setDefineRequestBodyForJson(json);
                        NohttpUtils.getInstance().add(LoginActivity.this, 0, request, callback, true, true, "登录中...");
                    }
                } else {
                    if (isLogin()) {
                        if (UiUtlis.getText(et_use).equals(SPUtils.get(context, Contans.USERNAME, ""))
                                && UiUtlis.getText(et_pwd).equals(SPUtils.get(context, "pwd", ""))) {
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                        } else {
                            showToast("你还没有登录过");
                        }
                    }
                }
            }
        });

        if (first) {
            //如果是第一次进入程序，就创建数据库
            SQLiteDatabase db = Connector.getDatabase();
            SPUtils.put(this, Contans.FIRST, false);
            if (db != null) {
                //showToast("数据库创建成功");
            }
        }
    }

    private HttpListener<String> callback = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {

            String json = response.get();
            showLog("---login----");
            showLog(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();
                String token = user.getToken();
                if (status.equals("0")) {
                    showToast("用户名或密码错误");
                } else if (status.equals("1")) {

                    if (!rb1.isChecked()) {
                        MiPushClient.setAlias(context, et_use.getText().toString(), null);
                    }

                    SPUtils.put(LoginActivity.this, Contans.WIFI_4G, rb1.isChecked());
                    //如果已经选中记住密码，就保存用户名和密码
                    SPUtils.put(LoginActivity.this, "save", savePwUser.isChecked());
                    SPUtils.put(LoginActivity.this, Contans.USERNAME, et_use.getText().toString());
                    SPUtils.put(LoginActivity.this, Contans.USERPWD, RSAUtils.encryptBASE64StrLocal(et_pwd.getText().toString()));
                    SPUtils.put(LoginActivity.this, Contans.LOGIN_TOKEN, RSAUtils.encryptBASE64StrLocal(token));
                    SPUtils.put(LoginActivity.this, Contans.NAME, username);
                    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.SITEID, user.getSITEID() == null ? "" : user.getSITEID());
                    SPUtils.put(LoginActivity.this, Contans.ORGID, user.getORGID() == null ? "" : user.getORGID());

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

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

    @SuppressLint("MissingPermission")
    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.Secure.ANDROID_ID);
        }
        String model = Build.MODEL;//手机型号
        String sysVersion = Build.VERSION.RELEASE;//系统版本
        Logger.v("IMEI：" + imei + "  手机型号:" + model + "  系统版本:" + sysVersion);
        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(et_use));
        userInfo.setPassword(UiUtlis.getText(et_pwd));
        list.add(userInfo);
        info.setRows(list);
        String json = GsonUtils.GsonString(info);
        Logger.v(json);
        return json;
    }

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

    // 按两次返回键退出程序
    @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 {
                ControllerActivity.getAppManager().finishAllActivity();
                finish();
                System.exit(0);
                NohttpUtils.getInstance().cancelAll();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取版本名称:清单文件中
     *
     * @return 应用版本名称    返回null代表异常
     */
    private String getVersionName() {
        //1,包管理者对象packageManager
        PackageManager pm = getPackageManager();
        //2,从包的管理者对象中,获取指定包名的基本信息(版本名称,版本号),传0代表获取基本信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            //3,获取版本名称
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //权限允许，创建文件夹
            String state = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                File sd = Environment.getExternalStorageDirectory();
                String path = sd.getAbsolutePath() + File.separator + "/com.rehome.ydapp/images";
                File file1 = new File(path);
                if (!file1.exists()) {
                    file1.mkdirs();
                }
            }
        }
    }
}