package com.beanpodtech.allinone.fragment;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.activity.ChangePasswordActivity;
import com.beanpodtech.allinone.activity.LoginActivity;
import com.beanpodtech.allinone.bean.ChangePassword;
import com.beanpodtech.allinone.http.UrlConfig;
import com.beanpodtech.allinone.utils.BoxUtil;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.OkGoUtil;
import com.beanpodtech.allinone.utils.SpUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.zyyoona7.popup.EasyPopup;

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

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import okhttp3.MediaType;
import okhttp3.RequestBody;


public class MineFragment extends BaseFragment implements View.OnClickListener {
    private EasyPopup mPopup; //修改密码弹窗
    private TextView mTvChangePsw, mTvName, mTvSchool, mTvPhone, mTvProvince;
    private String oldpassword_MD5;
    private String newpassword_MD5;
    private TextView tvLogout;

    @Override
    public int setLayout() {
        return R.layout.fragment_mine;
    }

    @Override
    public void initView(View view) {
        mTvChangePsw = view.findViewById(R.id.tv_change_psw);
        mTvName = view.findViewById(R.id.tv_name);
        mTvSchool = view.findViewById(R.id.tv_school);
        mTvPhone = view.findViewById(R.id.tv_phone);
        mTvProvince = view.findViewById(R.id.tv_province);
        mTvChangePsw.setOnClickListener(this);
        tvLogout = view.findViewById(R.id.tv_logout);
        tvLogout.setOnClickListener(this);
    }

    @Override
    public void initData() {
        initPop();
        mTvName.setText(getResources().getString(R.string.myaccount_name) + SpUtil.getInstace().getString(Contants.USER_NICKNAME, "- -"));
        mTvSchool.setText(getResources().getString(R.string.myaccount_school) + SpUtil.getInstace().getString(Contants.USER_SCHOOLNAME, "- -"));
        mTvPhone.setText(getResources().getString(R.string.myaccount_phone) + SpUtil.getInstace().getString(Contants.USER_NAME, "- -"));
    }

    private void initPop() {  //初始化协议弹窗
        mPopup = EasyPopup.create()
                .setContext(getActivity())
                .setContentView(R.layout.pop_change_psw)
                .setWidth(WindowManager.LayoutParams.WRAP_CONTENT)
                .setHeight(WindowManager.LayoutParams.WRAP_CONTENT)
                .setOutsideTouchable(true)
                .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
                .setBackgroundDimEnable(true)
                .setDimValue(0.3f)
                .setDimColor(Color.BLACK)
                .apply();

        TextView agreeBtn = mPopup.findViewById(R.id.tv_agree_btn);
        ImageView closeIv = mPopup.findViewById(R.id.pop_close);
        EditText mEtOldPsw = mPopup.findViewById(R.id.et_old_psw);
        EditText mEtNewPsw = mPopup.findViewById(R.id.et_new_psw);
        EditText mEtSurePsw = mPopup.findViewById(R.id.et_sure_psw);
        agreeBtn.setOnClickListener(v -> {
            String oldPassword = mEtOldPsw.getText().toString();
            String newPassword = mEtNewPsw.getText().toString();
            String againPassword = mEtSurePsw.getText().toString();
            if (oldPassword.length() == 0) {
                Toast.makeText(getActivity(), "请输入原密码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (newPassword.length() == 0) {
                Toast.makeText(getActivity(), "请输入新密码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (againPassword.length() == 0) {
                Toast.makeText(getActivity(), "没有输入确认新密码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (oldPassword.equals(newPassword) == true) {
                Toast.makeText(getActivity(), "原密码和新密码不能相同", Toast.LENGTH_SHORT).show();
                return;
            }
            if (againPassword.equals(newPassword) == false) {
                Toast.makeText(getActivity(), "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
                return;
            }
            if (oldPassword.length() != 0 && newPassword.length() != 0 && againPassword.length() != 0) {
                try {
                    oldpassword_MD5 = getMD5(oldPassword);
                    newpassword_MD5 = getMD5(newPassword);
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                String userName = SpUtil.getInstace().getString(Contants.USER_NAME, null);
                String userId = SpUtil.getInstace().getString(Contants.USER_ID, null);
                String boxId = BoxUtil.getDeviceSN();
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), initJson(userName, userId, boxId, oldpassword_MD5, newpassword_MD5));
                OkGo.<ChangePassword>post(UrlConfig.CHANGE_PASSWORD).upRequestBody(requestBody).execute(new OkGoUtil<ChangePassword>(ChangePassword.class) {
                    @Override
                    public void onSuccess(Response<ChangePassword> response) {
                        ChangePassword body = response.body();
                        if (body.getstatus() == 0) {
                            Toast.makeText(getActivity(), "密码修改成功", Toast.LENGTH_SHORT).show();
                            mPopup.dismiss();
                        } else if (body.getstatus() == -1) {
                            //添加"Yes"按钮
                            AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                    .setMessage("该账号在其他设备上登录,请重新登录")
                                    .setPositiveButton("确定", (dialogInterface, i) -> {
                                        SpUtil.getInstace().clear();
                                        startActivity(new Intent(getActivity(), LoginActivity.class));
                                        getActivity().finish();
                                    })
                                    .create();
                            alertDialog.show();
                        } else if (body.getstatus() == -2) {
                            Toast.makeText(getActivity(), "密码错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
        closeIv.setOnClickListener(v -> mPopup.dismiss());

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_change_psw:
//                mPopup.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER, 0, 0);
                SpUtil.getInstace().clear();
                startActivity(new Intent(getActivity(), LoginActivity.class));
                getActivity().finish();
                break;


                //新增退出账号功能 测试用
            case R.id.tv_logout:
                startActivity (new Intent(getActivity(), LoginActivity.class));
                SpUtil.getInstace().clear();
                getActivity().finish();
                break;
        }
    }

    public static String getMD5(String val) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(val.getBytes());
        byte[] bytearray = md5.digest();// 加密
        StringBuffer sb = new StringBuffer();
        for (byte b : bytearray) {
            int i = (b & 0xFF);
            if (i < 0x10) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(i));
        }
        return sb.toString();
    }

    private String initJson(String userName, String userId, String boxId, String oldPassWord, String newPassWord) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userId", userId);
            jsonObject.put("boxId", boxId);
            jsonObject.put("userName", userName);
            jsonObject.put("oldPassword", oldPassWord);
            jsonObject.put("newPassword", newPassWord);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPopup.dismiss();
    }
}
