package com.sipai.jspatrol.Login;

import static com.sipai.jspatrol.utils.RxCaptcha.TYPE.NUMBER;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.kyleduo.switchbutton.SwitchButton;
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.Main.MainActivity;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.setting.SettingActivity;
import com.sipai.jspatrol.utils.EncryptUtils;
import com.sipai.jspatrol.utils.Global.GlobalVal;
import com.sipai.jspatrol.utils.ProgressForAll;
import com.sipai.jspatrol.utils.RandomStringUtils;
import com.sipai.jspatrol.utils.RxCaptcha;
import com.sipai.jspatrol.utils.SharedPreferencesData;

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

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;

public class LoginActivity extends BaseView<LoginPresenter,LoginContract.View> implements View.OnClickListener {
    private EditText edt_name,edt_pwd;
    private SwitchButton sb_network;
    private Button btn_login,btn_setting;
    private String ip_in_plant = "", ip_off_site = "";//厂内，厂外ip地址
    private String mServer = "";
    private String mServerIp = "";
    private static final int SET_IP = 121;
    private SharedPreferencesData sharedpre;

    private HashMap<String,String> map = new HashMap<>();
    private HashMap<String,String> map_base = new HashMap<>();
    private String androidId = "";
    private String mBizid = "";
    private String mBizName;
    private String lcversion;
    private TextView tv_version;
    private ImageView iv_eye;
    private Boolean isOpen = false;
    private ImageView iv_code;
    private EditText edt_code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ActivityCollector.addActivity(this);
        init();
        initView();
        TelephonyManager tm = (TelephonyManager) LoginActivity.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 initView() {
        edt_name = findViewById(R.id.moudle_login_edt_name);
        edt_pwd = findViewById(R.id.moudle_login_edt_pwd);
        sb_network = findViewById(R.id.moudle_login_sb_network);
        sb_network.setTextColor(getResources().getColor(R.color.white));
        btn_login = findViewById(R.id.moudle_login_btn_login);
        btn_login.setOnClickListener(this);
        btn_setting = findViewById(R.id.moudle_login_btn_setting);
        btn_setting.setOnClickListener(this);
        tv_version = findViewById(R.id.tv_version);
        tv_version.setText("版本号：V"+lcversion);
        if (ip_off_site.length() < 3 && ip_in_plant.length() < 3) {
            showNoIpDialog();
        } else {
            setSweetButton();
        }
        iv_eye = findViewById(R.id.moudle_iv_eye);
        iv_eye.setColorFilter(getResources().getColor(R.color.gray));
        iv_eye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isOpen){
                    edt_pwd.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    iv_eye.setColorFilter(getResources().getColor(R.color.gray));
                    isOpen = !isOpen;
                }else {
                    edt_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    iv_eye.setColorFilter(getResources().getColor(R.color.white));
                    isOpen = !isOpen;
                }
            }
        });
        edt_code = findViewById(R.id.moudle_login_edt_code);
        iv_code = findViewById(R.id.moudle_iv_code);
        iv_code.setOnClickListener(this);
        refreshCode();
    }

    private void refreshCode() {
        RxCaptcha.build()
                .backColor(0xffffff)
                .codeLength(4)
                .fontSize(60)
                .lineNumber(2)
                .size(200, 70)
                .type(NUMBER)
                .into(iv_code);
    }

    private void showMsgFinish() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ProgressForAll.cancelProgress();
            }
        });
    }

    private void showMsgDialog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ProgressForAll.showProgress(LoginActivity.this,"","登录中...");
            }
        });
    }

    private void init() {
        sharedpre = new SharedPreferencesData(this);
        map_base = sharedpre.getAll();
        ip_in_plant = map_base.get("ip_in_plant");
        ip_off_site = map_base.get("ip_off_site");
        mServer = map_base.get("mServer");
        mServerIp = map_base.get("mServerIp");
        lcversion = getLocalVersionName(this);
    }

    /**
     * 获取本地软件版本号名称
     */
    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 setSweetButton() {
        if (mServerIp != null && mServerIp.length() > 3) {
            if (ip_in_plant.equals(mServerIp)) {
                sb_network.setChecked(true);
            } else {
                sb_network.setChecked(false);
                mServerIp = ip_off_site;
            }
        } else {
            if (ip_in_plant.length()>3){
                mServerIp = ip_in_plant;
                sb_network.setChecked(true);
            }else if (ip_off_site.length()>3){
                mServerIp = ip_off_site;
                sb_network.setChecked(false);
            }
        }
        mServer = "http://" + mServerIp + "/";
        final HashMap<String,String> server_map = new HashMap<>();
        server_map.put("server",mServer);
        server_map.put("serverip",mServerIp);
        sharedpre.saveInfo(server_map);
        init();
        if (ip_in_plant.length()<4||ip_off_site.length()<4){
            sb_network.setEnabled(false);
        }else {
            sb_network.setEnabled(true);
        }
        sb_network.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isChecked) {
                            mServerIp = ip_in_plant;
                            mServer = "http://" + mServerIp + "/";
                            server_map.clear();
                            server_map.put("server",mServer);
                            server_map.put("serverip",mServerIp);
                            sharedpre.saveInfo(server_map);
                            init();
                        } else {
                            mServerIp = ip_off_site;
                            mServer = "http://" + mServerIp + "/";
                            server_map.clear();
                            server_map.put("server",mServer);
                            server_map.put("serverip",mServerIp);
                            sharedpre.saveInfo(server_map);
                            init();
                        }
                    }
                });
            }
        });
    }

    private void showNoIpDialog() {
        if (!LoginActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("提示")
                            .setContentText("检测到APP暂未设置IP地址，若不设置则无法进行下一步操作！")
                            .setConfirmText("设置")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    Intent intent = new Intent(LoginActivity.this, SettingActivity.class);
                                    startActivityForResult(intent, SET_IP);
                                }
                            }).setCancelText("取消")
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            }).show();
                }
            });
        }
    }

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

    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();
    }

    @Override
    public LoginContract.View getContract() {
        return new LoginContract.View<LoginInfo>(){
            @Override
            public void handlerResult(LoginInfo item) {
                if (item!=null){
                    if (item.isStatus()){
                        saveLoginInfo(item);
                        getComList(item);
                    }else {
                        showMsgFinish();
                        if (item.getReason()!=null&&!item.getReason().isEmpty()) {
                            failLogin(item.getReason());
                        }else {
                            failLogin("登录请求失败！");
                        }
                    }
                }else {
                    showMsgFinish();
                    showError("登录请求失败！");
                }
            }

            @Override
            public void handlerComResult(String result,String t) {
                showMsgFinish();
                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 (mBizid.isEmpty()){
                            mBizid = bizs.get(0).getBizid();
                            mBizName = bizs.get(0).getName();
                        }
                        saveBizlist(LoginActivity.this, "response", mBizid, mBizName,t);
                        MainActivity.actionStart(LoginActivity.this);

                    }else {
                        showError("未关联厂区，无法登录");
                    }
                }else {
                    showError("登录失败");
                }
            }
        };
    }

    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<>();
        showMsgDialog();
        p.getContract().requestComList(LoginActivity.this,map,mServer, MethodURL.ComList_Method,item.getUser().getToken());
    }

    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("username",edt_name.getText().toString());
        map.put("password",edt_pwd.getText().toString());
        map.put("token",item.getUser().getToken());
        map.put("nfc", item.getUser().getNfc());
        map.put("subtask", item.getUser().getSubTask());
        sharedPreferencesData.saveInfo(map);
    }

    private void failLogin(final String reason) {
        if (!LoginActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("提示")
                            .setContentText(reason)
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            }).show();
                }
            });
        }
    }

    private void showError(String s) {
        if (!LoginActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LoginActivity.this, s, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.moudle_login_btn_login:
                if (edt_code.getText()!=null&&!edt_code.getText().toString().isEmpty()&&edt_code.getText().toString().equals(RxCaptcha.build().getCode())) {
                    String st_name = "";
                    String st_pwd = "";
                    if (judgeString(mServer,"服务器地址")){
                        if (edt_name.getText()!=null&&!edt_name.getText().toString().isEmpty()){
                            st_name = edt_name.getText().toString();
                        }else {
                            showCannotNull(edt_name);
                        }
                        if (edt_pwd.getText()!=null&&!edt_pwd.getText().toString().isEmpty()){
                            st_pwd = edt_pwd.getText().toString();
                        }else {
                            showCannotNull(edt_pwd);
                        }
                        if (!st_name.isEmpty()&&!st_pwd.isEmpty()) {
                            toLogin(st_name, st_pwd);
                        }
                    }
                }else {
                    Toast.makeText(this, "验证码错误", Toast.LENGTH_LONG).show();
                    refreshCode();
                }
                break;
            case R.id.moudle_login_btn_setting:
                Intent intent = new Intent(LoginActivity.this,SettingActivity.class);
                startActivityForResult(intent,SET_IP);
                break;
        }
    }

    private void showCannotNull(final EditText edt) {
        if (!LoginActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    edt.setError("不能为空");
                }
            });
        }
    }

    private void toLogin(String name, String pwd) {
        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(pwd,"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("j_password",p_pwd);
        map.put("j_username",name);
        map.put("androidId",androidId);
        map.put("verCode",vcode);
        map.put("code",code);
        showMsgDialog();
        p.getContract().requestData(LoginActivity.this,map,mServer, MethodURL.Login_Method);
    }


    private boolean judgeString(String st, final String notice) {
        if (st!=null&&!st.isEmpty()){
            return true;
        }else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LoginActivity.this, notice+"不能为空", Toast.LENGTH_SHORT).show();
                }
            });
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            switch (requestCode){
                case SET_IP:
                    init();
                    if (ip_off_site.length() < 2 || ip_in_plant.length() < 2) {
                        showNoIpDialog();
                    } else {
                        setSweetButton();
                    }
                    break;
            }
        }
    }

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