package com.sipai.jspatrol.Loading;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sipai.jspatrol.Bean.Biz;
import com.sipai.jspatrol.Patrol.ProPatrolTaskListActivity;
import com.sipai.jspatrol.utils.DoubleClickUtils.DoubleHandler;
import com.sipai.jspatrol.utils.DoubleClickUtils.DoubleManager;
import com.sipai.jspatrol.utils.DoubleClickUtils.DoubleRunnable;
import com.sipai.jspatrol.utils.DoubleClickUtils.OnDoubleClickListener;
import com.sipai.jspatrol.R;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;



public class LoginActivity extends AppCompatActivity implements OnClickListener {
    protected static final String TAG = "LoginInActivity";
    private LinearLayout mLoginLinearLayout; // 登录内容的容器
    private LinearLayout mUserIdLinearLayout; // 将下拉弹出窗口在此容器下方显示
    private Animation mTranslate; // 位移动画
    private Dialog mLoginingDlg; // 显示正在登录的Dialog
    private EditText mNameEditText; // 登录ID编辑框
    private EditText mPwdEditText; // 登录密码编辑框
    private Button mLoginButton; // 登录按钮
    private String mNameString;
    private String mPwdString;
    private String mBizid = "";
    private String mCaption;
    private String mUserName;
    private String mUserid;
    private String patrolTypeId;//运行组别
    private String totaltime;
    private String token;
    private String role_id;
    private String role_name;
    private String role_description;
    private String role_serial;
    private String mBizName;
    private List<Biz> bizList = new ArrayList<>();
    private String mServer = "";
    private String mGroup;
    private String lcversion = "";
    public static final int REQUSET = 1;
    private DoubleManager keyDoubleManager = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        mServer=getSharedPreferences("config", MODE_PRIVATE).getString("server", "");
        setListener();
        initialvar();
        mLoginLinearLayout.startAnimation(mTranslate); // Y轴水平移动
        /*获取上次登录的用户名和密码*/
        if (!getSharedPreferences("config", MODE_PRIVATE).getString("username", "").equals("")) {
            mNameString = getSharedPreferences("config", MODE_PRIVATE).getString("username", "");
        }
        if (!getSharedPreferences("config", MODE_PRIVATE).getString("password", "").equals("")) {
            mPwdString = getSharedPreferences("config", MODE_PRIVATE).getString("password", "");
        }
        if (!getSharedPreferences("config", MODE_PRIVATE).getString("userid", "").equals("")) {
            mUserid = getSharedPreferences("config", MODE_PRIVATE).getString("userid", "");
        }
        if (!getSharedPreferences("config", MODE_PRIVATE).getString("caption", "").equals("")) {
            mCaption = getSharedPreferences("config", MODE_PRIVATE).getString("caption", "");
        }

        mNameEditText.setText(mNameString);
        initPermissions();
    }

    private void initPermissions() {
		        /*
        动态申请网络权限
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionList = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                permissionList.add(Manifest.permission.REQUEST_INSTALL_PACKAGES);
                permissionList.add(Manifest.permission.READ_PHONE_STATE);
                permissionList.add(Manifest.permission.ACCESS_WIFI_STATE);
                permissionList.add(Manifest.permission.ACCESS_NETWORK_STATE);
                permissionList.add(Manifest.permission.WAKE_LOCK);
                permissionList.add(Manifest.permission.VIBRATE);
                permissionList.add(Manifest.permission.READ_CONTACTS);
                permissionList.add(Manifest.permission.WRITE_CONTACTS);
                permissionList.add(Manifest.permission.RECEIVE_BOOT_COMPLETED);
                permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                permissionList.add(Manifest.permission.WRITE_SETTINGS);
                permissionList.add(Manifest.permission.RESTART_PACKAGES);
                permissionList.add(Manifest.permission.BROADCAST_STICKY);
                permissionList.add(Manifest.permission.KILL_BACKGROUND_PROCESSES);
                permissionList.add(Manifest.permission.GET_TASKS);
                permissionList.add(Manifest.permission.READ_LOGS);
                permissionList.add(Manifest.permission.BLUETOOTH);
                permissionList.add(Manifest.permission.BATTERY_STATS);
                permissionList.add(Manifest.permission.VIBRATE);
                permissionList.add(Manifest.permission.CAMERA);
                permissionList.add(Manifest.permission.DISABLE_KEYGUARD);
                permissionList.add(Manifest.permission.WAKE_LOCK);
                permissionList.add(Manifest.permission.SYSTEM_ALERT_WINDOW);
                permissionList.add(Manifest.permission.NFC);
            }
            if (!permissionList.isEmpty()) {
                String[] permissions = permissionList.toArray(new String[permissionList.size()]);
                ActivityCompat.requestPermissions(this, permissions, 1212);
            }
        }
    }

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

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

    public String getMacAddress() {
        // start get mac address
        WifiManager wifiMan = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiMan != null) {
            WifiInfo wifiInf = wifiMan.getConnectionInfo();
            if (wifiInf != null && wifiInf.getMacAddress() != null) {
                // 48位，如FA:34:7C:6D:E4:D7
                return wifiInf.getMacAddress();
            }
        }
        return null;
    }

    private void setListener() {
        mNameEditText.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                mNameString = s.toString();
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        mPwdEditText.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                mPwdString = s.toString();
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        mLoginButton.setOnClickListener(this);
    }

    private void initView() {
//        mNameEditText = findViewById(R.id.login_edtId);
//        mPwdEditText = findViewById(R.id.login_edtPwd);
//        mLoginButton = findViewById(R.id.login_btnLogin);
        mLoginLinearLayout = findViewById(R.id.login_linearLayout);
        mUserIdLinearLayout = findViewById(R.id.userId_LinearLayout);
        mTranslate = AnimationUtils.loadAnimation(this, R.anim.my_translate); // 初始化动画对象
        TextView tv_lc_version = findViewById(R.id.tv_version);
        lcversion = getLocalVersionName(this);
        tv_lc_version.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (keyDoubleManager == null) {
                    keyDoubleManager = new DoubleManager(new DoubleRunnable(new DoubleHandler(new OnDoubleClickListener() {
                        @Override
                        public void onSinglePress() {
                        }

                        @Override
                        public void onDoublePress() {
//                            Intent intent = new Intent(LoginInActivity.this, SettingActivity.class);
//                            startActivity(intent);
                        }
                    })));
                }
                keyDoubleManager.start();
            }
        });
        if (lcversion != null && !lcversion.isEmpty()) {
            tv_lc_version.setText("版本号：V" + lcversion);
        }
        initLoginingDlg();
    }


    /* 初始化正在登录对话框 */
    private void initLoginingDlg() {

        mLoginingDlg = new Dialog(this, R.style.loginingDlg);
        mLoginingDlg.setContentView(R.layout.logining_dlg);

        Window window = mLoginingDlg.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        // 获取和mLoginingDlg关联的当前窗口的属性，从而设置它在屏幕中显示的位置

        // 获取屏幕的高宽
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int cxScreen = dm.widthPixels;
        int cyScreen = dm.heightPixels;

        int height = (int) getResources().getDimension(
                R.dimen.loginingdlg_height);// 高42dp
        int lrMargin = (int) getResources().getDimension(
                R.dimen.loginingdlg_lr_margin); // 左右边沿10dp
        int topMargin = (int) getResources().getDimension(
                R.dimen.loginingdlg_top_margin); // 上沿20dp

        params.y = ((cyScreen - height) / 2) + topMargin; // -199
        /* 对话框默认位置在屏幕中心,所以x,y表示此控件到"屏幕中心"的偏移量 */

        params.width = cxScreen;
        params.height = height;
        // width,height表示mLoginingDlg的实际大小

        mLoginingDlg.setCanceledOnTouchOutside(true); // 设置点击Dialog外部任意区域关闭Dialog
    }

    /* 显示正在登录对话框 */
    private void showLoginingDlg() {
        if (!LoginActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mLoginingDlg != null)
                        mLoginingDlg.show();
                }
            });
        }
    }

    /* 关闭正在登录对话框 */
    private void closeLoginingDlg() {
        if (!LoginActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mLoginingDlg != null && mLoginingDlg.isShowing())
                        mLoginingDlg.dismiss();
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.login_btnLogin:
//                showLoginingDlg(); // 显示"正在登录"对话框,因为此Demo没有登录到web服务器,所以效果可能看不出.可以结合情况使用
//                attemptLogin(LoginActivity.this);
//                break;
            default:
                break;
        }

    }

    /* 退出此Activity时保存users */
    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            sign_out();
        }
        return false;
    }

    public void attemptLogin(Context context) {
        if (mServer.equals("")) {
            closeLoginingDlg();// 关闭对话框
            Toast.makeText(LoginActivity.this, "未设置服务器IP地址", Toast.LENGTH_SHORT).show();
            return;
        }
        // Reset errors.
        mNameEditText.setError(null);
        mPwdEditText.setError(null);
        if (mNameEditText.getText() != null) {
            mUserName = mNameEditText.getText().toString();
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mNameEditText.setError("请填写用户名");
                }
            });
            return;
        }
        if (mPwdEditText.getText() != null) {
            mPwdString = mPwdEditText.getText().toString();
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mPwdEditText.setError("不能为空");
                }
            });
            return;
        }
        if (mUserName != null && !mUserName.isEmpty() && mPwdString != null && !mPwdString.isEmpty()) {
            validateLogin(mUserName, mPwdString, mBizid, mGroup);//验证用户名密码
        } else {
            Toast.makeText(LoginActivity.this, "用户名或密码不能为空！", Toast.LENGTH_SHORT).show();
        }
    }

    private String[] permissions = {Manifest.permission.READ_PHONE_STATE};

    private void validateLogin(String user, final String password, String bizid, String group) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mNameEditText.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(mPwdEditText.getWindowToken(), 0);
        final String username = user;
        final String passwords = password;
//        CookieUtils.clearCookie(this);
        RequestParams params = new RequestParams();
        params.put("j_username", user);
        params.put("j_password", password);
        params.put("verCode", "64368180");

        AsyncHttpClient client = new AsyncHttpClient();
        client.setTimeout(5000);
//        CookieUtils.saveCookie(client, this);
        client.post(mServer + "SIPAIIS_Base/j_spring_security_check?", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                if (response != null && response.length() > 0) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String res = jsonObject.optString("res");
                        token = jsonObject.optString("Access_Token");
                        if (jsonObject.getBoolean("status")) {
                            JSONObject json = new JSONObject(res);
                            mCaption = json.optString("caption");
                            mUserName = json.optString("name");
                            mUserid = json.optString("id");
                            totaltime = json.optString("totaltime");
                            if (json.optString("dept")!=null&&!json.optString("dept").isEmpty()) {
                                JSONObject jsonob = new JSONObject(json.optString("dept"));
                                if (jsonob.optString("patrolTypeId")!=null&&!jsonob.optString("patrolTypeId").isEmpty()) {
                                    patrolTypeId = jsonob.optString("patrolTypeId");
                                }
                            }else {
                                patrolTypeId = "P";
                            }
                            JSONArray roles = new JSONArray(json.opt("roles").toString());
                            for (int i=0;i<roles.length();i++){
                                if (roles.getJSONObject(i).optString("name").contains("管理")) {
                                    role_id = roles.getJSONObject(i).optString("id");
                                    role_name = roles.getJSONObject(i).optString("name");
                                    role_description = roles.getJSONObject(i).optString("description");
                                    break;
                                }else {
                                    role_id = roles.getJSONObject(0).optString("id");
                                    role_name = roles.getJSONObject(0).optString("name");
                                    role_description = roles.getJSONObject(0).optString("description");
                                }
                            }
                            if (json.optString("serial")!=null&&!json.optString("serial").isEmpty()) {
                                role_serial = json.optString("serial");
                            }else {
                                role_serial = "";
                            }
                            saveUserInfo(token,mCaption, mUserName, mUserid, totaltime, role_id, role_name, role_description, role_serial, password,patrolTypeId);
                            String tk = token;
                            String url = mServer + "/SIPAIIS_Base/user/getSearchBizsByUserId4Select.do";
                            doGetBizList(url, tk);
                        } else {
                            errorLogin(res);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        closeLoginingDlg();
                        loginError();
                    }
                }
            }

            @Override
            public void onFailure(Throwable e) {
                closeLoginingDlg();// 关闭对话框
                Toast.makeText(LoginActivity.this, getString(R.string.error_incorrect_connection), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });


    }

    private void loginError() {
        if (!LoginActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LoginActivity.this, "用户信息格式错误，请联系管理员！", Toast.LENGTH_LONG).show();
                }
            });
        }
    }


    private void errorLogin(final String res) {
        closeLoginingDlg();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("错误")
                        .setContentText(res)
                        .setConfirmText("确认")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismissWithAnimation();
                            }
                        }).show();
            }
        });
    }

    private void saveUserInfo(String token,String caption, String username, String userid, String totaltime, String roleid, String rolename, String roledescription, String roleserial, String password,String patrolTypeId) {
        SharedPreferences sharedPre = getSharedPreferences("config", MODE_PRIVATE);
        //获取Editor对象
        Editor editor = sharedPre.edit();
        editor.putString("token", token);
        editor.putString("caption", caption);
        editor.putString("username", username);
        editor.putString("password", password);
        editor.putString("userid", userid);
        editor.putString("totaltime", totaltime);
        editor.putString("roleid", roleid);
        editor.putString("rolename", rolename);
        editor.putString("roledescription", roledescription);
        editor.putString("roleserial", roleserial);
        editor.putString("patrolTypeId", patrolTypeId);
        editor.commit();
    }

    private void doGetBizList(String url, String tk) {
//        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        RequestParams params = new RequestParams();
        AsyncHttpClient client = new AsyncHttpClient();
        client.addHeader("token",tk);
        client.setTimeout(60000);
        client.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                if (response != null && response.length() > 0) {
                    bizList = getData(response);
                    if (bizList.size() > 0) {
                        mBizid = bizList.get(0).getId();
                        mBizName = bizList.get(0).getName();
                    }
                    mBizid = "blgworkshop1";
                    mBizName = "白龙港一车间";
                    saveBizlist(LoginActivity.this, response, mBizid, mBizName);
                    Intent intent = new Intent(LoginActivity.this, ProPatrolTaskListActivity.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void onFailure(Throwable e) {
                closeLoginingDlg();// 关闭对话框
                Toast.makeText(LoginActivity.this, getString(R.string.error_incorrect_connection), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    private List<Biz> getData(String response) {
        List<Biz> listres = new ArrayList<Biz>();
        try {
            JSONArray aNews = new JSONArray(response);
            if (aNews != null && aNews.length() > 0) {
                for (int i = 0; i < aNews.length(); i++) {
                    Biz item = new Biz();
                    item.setId(aNews.getJSONObject(i).get("id").toString());
                    item.setName(aNews.getJSONObject(i).get("text").toString());
                    item.setBizid(aNews.getJSONObject(i).get("id").toString());
                    listres.add(item);
                }
            }
        } catch (JSONException ex) {
            Log.e("JSON Error: ", ex.toString());
        }

        return listres;
    }

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


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        //requestCode标示请求的标示   resultCode表示有数据
        if (requestCode == LoginActivity.REQUSET && resultCode == RESULT_OK) {
            initialvar();
            /* 获取已经保存好的用户密码 */
//			userlist(mBizid,mGroup);

        }
    }

    @Override
    protected void onResume() {
//		userlist(mBizid,mGroup);
        super.onResume();
        initialvar();
    }

    private void initialvar() {
        if (!getSharedPreferences("config", MODE_PRIVATE).getString("bizid", "").equals("")) {
            mBizid = getSharedPreferences("config", MODE_PRIVATE).getString("bizid", "");
        }
        if (!getSharedPreferences("config", MODE_PRIVATE).getString("server", "").equals("")) {
            mServer = getSharedPreferences("config", MODE_PRIVATE).getString("server", "");
        }
        if (!getSharedPreferences("config", MODE_PRIVATE).getString("group", "").equals("")) {
            mGroup = getSharedPreferences("config", MODE_PRIVATE).getString("group", "");
        }
    }

    private void sign_out() {
        SweetAlertDialog dia = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
        dia.setCanceledOnTouchOutside(true);
        dia.setTitleText("确定登出？").setConfirmText("确认").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                finish();
            }
        }).setCancelText("取消").setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismissWithAnimation();
            }
        }).show();

    }

}
