package com.gingersoft.gsa.cloud.user.login.mvp.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;

import com.billy.cc.core.component.CC;
import com.billy.cc.core.component.CCResult;
import com.billy.cc.core.component.IComponentCallback;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.base.utils.constans.UserConstans;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.base.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.ui.bean.mode.LoginBean;
import com.gingersoft.gsa.cloud.ui.widget.dialog.ChooseRestaurantDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.gingersoft.gsa.cloud.user.login.R;
import com.gingersoft.gsa.cloud.user.login.R2;
import com.gingersoft.gsa.cloud.user.login.di.component.DaggerLoginComponent;
import com.gingersoft.gsa.cloud.user.login.mvp.contract.LoginContract;
import com.gingersoft.gsa.cloud.user.login.mvp.presenter.LoginPresenter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/21/2019 16:23
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View, View.OnClickListener {

    @Inject
    AppManager mAppManager;

    @BindView(R2.id.ed_login_user_account)
    EditText edAccount;
    @BindView(R2.id.ed_login_user_pwd)
    EditText edPwd;
    @BindView(R2.id.iv_clear_pwd)
    ImageView icClear;
    @BindView(R2.id.iv_clear_account)
    ImageView icClearAccount;
    @BindView(R2.id.rb_remember_password)
    CheckBox mRbRememberPwd;
    @BindView(R2.id.ic_look_pwd)
    ImageView mIvSeePwd;

    private boolean passwrodVisibility = false;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLoginComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
//        String token = GsaCloudApplication.getLoginToken(this);
//        if (!TextUtils.isEmpty(token)) {
//            jumpMainActivity();
//        }
        super.onCreate(savedInstanceState);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
        return R.layout.user_login_activity_login; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        findViewById(R.id.tv_gsa_user_login).setOnClickListener(this);
        if (!Objects.equals(SPUtils.get(mContext, UserConstans.LOGIN_USERNAME, ""), "")) {
            edAccount.setText("" + SPUtils.get(mContext, UserConstans.LOGIN_USERNAME, ""));
            mRbRememberPwd.setChecked(true);
        }
        if (!Objects.equals(SPUtils.get(mContext, UserConstans.LOGIN_PASSWORD, ""), "")) {
            edPwd.setText("" + SPUtils.get(mContext, UserConstans.LOGIN_PASSWORD, ""));
        }
//        if(GsaCloudApplication.getLoginToken(mContext).length() > 0){
//            jumpActivity();
//            finish();
//        }
        edPwd.setOnFocusChangeListener(mOnFocusChangeListener);
        edAccount.setOnFocusChangeListener(mOnFocusChangeListener);
        edPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (edPwd.getText() != null && edPwd.getText().toString().equals("")) {
                    icClear.setVisibility(View.GONE);
                    mIvSeePwd.setVisibility(View.GONE);
                } else {
                    icClear.setVisibility(View.VISIBLE);
                    mIvSeePwd.setVisibility(View.VISIBLE);
                }
            }
        });
        edAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (edPwd.getText() != null && edAccount.getText().toString().equals("")) {
                    icClearAccount.setVisibility(View.GONE);
                } else {
                    icClearAccount.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private View.OnFocusChangeListener mOnFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            editFocusChange(v, hasFocus);
            if (v.getId() == R.id.ed_login_user_account && hasFocus) {
                //賬號框獲得焦點
                if (edAccount.getText() != null && edAccount.getText().toString().length() > 0) {
                    icClearAccount.setVisibility(View.VISIBLE);
                } else {
                    icClearAccount.setVisibility(View.GONE);
                }
            } else {
                icClearAccount.setVisibility(View.GONE);
            }
        }
    };

    private void editFocusChange(View v, boolean hasFocus) {
        if (v.getId() == R.id.ed_login_user_pwd && hasFocus) {
            //密碼框獲得焦點
            if (edPwd.getText() != null && edPwd.getText().toString().length() > 0) {
                icClear.setVisibility(View.VISIBLE);
                mIvSeePwd.setVisibility(View.VISIBLE);
            } else {
                icClear.setVisibility(View.GONE);
                mIvSeePwd.setVisibility(View.GONE);
            }
        } else {
            icClear.setVisibility(View.GONE);
            mIvSeePwd.setVisibility(View.GONE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        killBeforeActivty();
    }

    private void killBeforeActivty() {
        List<Activity> activities = mAppManager.getActivityList();
        for (int i = activities.size() - 1; i >= 0; i--) {
            if (i < activities.size()) {
                Activity activity = activities.get(i);
                if (!activity.getClass().getName().equals(getClass().getName())) {
                    LogUtil.d(TAG, "killBeforeActivty: " + i + " - " + activity.getClass().getSimpleName());
                    mAppManager.killActivity(activity.getClass());
                    mAppManager.removeActivity(activity);
                }
            }
        }
    }

    @Override
    public void initIntent() {

    }

    @Override
    public void initTopBar() {

    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {
        if (message != null)
            LoadingDialog.showDialogForLoading(this, message, true);
        else
            LoadingDialog.showDialogForLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    private Dialog dialog1;

    @Override
    public void loginSuccess(LoginBean loginBean) {
        //記住密碼
        RememberPwd();

        GsaCloudApplication.setBrandRestaurantInfos(this, "");
        if (loginBean.getData() != null) {
            GsaCloudApplication.setLoginToken(LoginActivity.this, loginBean.getData().getToken());
            if (loginBean.getData().getUser() != null) {
                GsaCloudApplication.setMemberId(LoginActivity.this, loginBean.getData().getUser().getUserId());
                GsaCloudApplication.setMemberName(LoginActivity.this, loginBean.getData().getUser().getUserName());

                List<LoginBean.DataBean.UserBean.BrandsBean> brands = loginBean.getData().getUser().getBrands();
                if (brands != null) {
                    String brandRestaurantInfos = JsonUtils.toJson(brands);
                    GsaCloudApplication.setBrandRestaurantInfos(this, brandRestaurantInfos);
                }
                int restaurantSize = 0;
                List<LoginBean.DataBean.UserBean.BrandsBean> brandsBeans = new ArrayList<>();
                if (loginBean.getData().getUser().getBrands() != null) {
                    restaurantSize = getRestaurantSize(loginBean.getData().getUser().getBrands());
                    brandsBeans.addAll(loginBean.getData().getUser().getBrands());
                }
                if (restaurantSize == 1) {
                    //只有一個品牌是直接進下載頁面
                    LoginBean.DataBean.UserBean.BrandsBean brandsBean = getOnlyBrand(loginBean.getData().getUser().getBrands());
                    LoginBean.DataBean.UserBean.BrandsBean.RestaurantsBean restaurantsBean = getOnlyRestaurant(loginBean.getData().getUser().getBrands());
                    if (brandsBean != null) {
                        saveBrandAndRestaurantInfo(brandsBean.getBrandId(), brandsBean.getBrandName(), restaurantsBean.getRestaurantId(), restaurantsBean.getRestaurantName());
                    }
                    jumpDownloadActivity();
                } else {
                    if (!isFinishing()) {
                        dialog1 = new ChooseRestaurantDialog.BottomListSheetBuilder(this)
                                .addBrandItems(brandsBeans)
                                .setOnItemClickListener((dialog, item, position) -> {
                                    LoginBean.DataBean.UserBean.BrandsBean brandsBean = getBrandByRestaurantId(brands, item.getId());
                                    if (brandsBean != null) {
                                        saveBrandAndRestaurantInfo(brandsBean.getBrandId(), brandsBean.getBrandName(), item.getId(), item.getText());
                                    }
                                    dialog.dismiss();
                                    jumpDownloadActivity();
//                                    killMyself();
                                }).build();
                        if (!isFinishing() && dialog1 != null && !dialog1.isShowing() && !isDestroy) {
                            dialog1.show();
                        }
                    }
                }
            }
        }
    }

    private boolean isDestroy = false;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("error", "登陸頁面銷毀：onDestroy");
        if (dialog1 != null) {
            dialog1.dismiss();
        }
        isDestroy = true;
    }

    /**
     * 記住密碼
     */
    private void RememberPwd() {
        if (mRbRememberPwd.isChecked()) {
            //登陸成功後，如果選中了記住密碼，則保存密碼
            SPUtils.put(mContext, UserConstans.LOGIN_USERNAME, edAccount.getText().toString());
            SPUtils.put(mContext, UserConstans.LOGIN_PASSWORD, edPwd.getText().toString());
        } else {
            SPUtils.put(mContext, UserConstans.LOGIN_USERNAME, "");
            SPUtils.put(mContext, UserConstans.LOGIN_PASSWORD, "");
        }
    }

    private void saveBrandAndRestaurantInfo(int brandId, String brandName, int restaurantId, String restaurantName) {
        GsaCloudApplication.setBrandId(LoginActivity.this, brandId);
        GsaCloudApplication.setBrandName(LoginActivity.this, brandName);
        GsaCloudApplication.setRestaurantId(LoginActivity.this, restaurantId);
        GsaCloudApplication.setRestaurantName(LoginActivity.this, restaurantName);
    }

    private int getRestaurantSize(List<LoginBean.DataBean.UserBean.BrandsBean> brands) {
        int size = 0;
        for (int i = 0; i < brands.size(); i++) {
            if (brands.get(i).getRestaurants() != null)
                size += brands.get(i).getRestaurants().size();
        }
        return size;
    }

    private LoginBean.DataBean.UserBean.BrandsBean getOnlyBrand(List<LoginBean.DataBean.UserBean.BrandsBean> brands) {
        for (int i = 0; i < brands.size(); i++) {
            if (brands.get(i).getRestaurants() != null) {
                for (int j = 0; j < brands.get(i).getRestaurants().size(); j++) {
                    return brands.get(i);
                }
            }
        }
        return null;
    }

    private LoginBean.DataBean.UserBean.BrandsBean.RestaurantsBean getOnlyRestaurant(List<LoginBean.DataBean.UserBean.BrandsBean> brands) {
        for (int i = 0; i < brands.size(); i++) {
            if (brands.get(i).getRestaurants() != null) {
                for (int j = 0; j < brands.get(i).getRestaurants().size(); j++) {
                    return brands.get(i).getRestaurants().get(j);
                }
            }
        }
        return null;
    }

    private LoginBean.DataBean.UserBean.BrandsBean getBrandByRestaurantId(List<LoginBean.DataBean.UserBean.BrandsBean> brands, int restaurantId) {
        for (int i = 0; i < brands.size(); i++) {
            if (brands.get(i).getRestaurants() != null) {
                for (int j = 0; j < brands.get(i).getRestaurants().size(); j++) {
                    if (brands.get(i).getRestaurants().get(j).getRestaurantId() == restaurantId) {
                        return brands.get(i);
                    }
                }
            }
        }
        return null;
    }

    private void jumpDownloadActivity() {
        CC.obtainBuilder("Component.Download")
                .setActionName("showDownloadActivity")
                .build()
                .call();
        killMyself();
    }

    private void jumpMainActivity() {
        CC.obtainBuilder("Component.Main")
                .setActionName("showMainActivity")
                .build()
                .call();
    }

    @Override
    public void loginOut() {

    }

    @Override
    public void startToSwitchServer() {
        startActivity(new Intent(mContext, SwitchServerActivity.class));
    }


    @OnClick({R2.id.tv_gsa_user_login, R2.id.iv_clear_pwd, R2.id.iv_clear_account, R2.id.tv_remember_pwd_text, R2.id.ic_look_pwd})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ic_look_pwd:
                passwrodVisibility = !passwrodVisibility;
                if (passwrodVisibility) {
                    //如果选中，显示密码
                    mIvSeePwd.setImageDrawable(getResources().getDrawable(R.mipmap.ic_password_show));
                    edPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    edPwd.setSelection(edPwd.getText().toString().length());
                } else {
                    //否则隐藏密码
                    mIvSeePwd.setImageDrawable(getResources().getDrawable(R.mipmap.ic_password_hide));
                    edPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    edPwd.setSelection(edPwd.getText().toString().length());
                }
                edPwd.setSelection(edPwd.getText() == null ? 0 : edPwd.getText().toString().length());
                break;
            case R.id.tv_remember_pwd_text:
                //記住密碼
                mRbRememberPwd.toggle();
                break;
            case R.id.tv_gsa_user_login:
                //登陸
                if (edAccount.getText() != null && edPwd.getText() != null) {
                    mPresenter.login(edAccount.getText().toString(), edPwd.getText().toString());
                }
                break;
            case R.id.iv_clear_account:
                //清空賬號框
                edAccount.setText("");
                icClearAccount.setVisibility(View.GONE);
                break;
            case R.id.iv_clear_pwd:
                //清空密碼框
                edPwd.setText("");
                icClear.setVisibility(View.GONE);
                break;
        }
    }

    public void login() {

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("userName", edAccount.getText().toString())
                .add("passWord", edPwd.getText().toString())
                .build();
        Request request = new Request.Builder()
                .addHeader("apptype", "9")
                .addHeader("mobileId", "1")
                .addHeader("mobielModel", "")
                .addHeader("mobileVersion", "")
                .url("http://gingersoft.tpddns.cn:58201/ricepon-cloud-gsa/api/gsa/login")
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();

                LoginBean loginBean = GsonUtils.GsonToBean(json, LoginBean.class);

                if (loginBean != null) {
                    GsaCloudApplication.setLoginToken(LoginActivity.this, loginBean.getData().getToken());
                    if (loginBean.getData().getUser() != null) {
//                        GsaCloudApplication.setMemberId(LoginActivity.this, loginBean.getData().getUser().getId());
//                        GsaCloudApplication.setRestaurantId(LoginActivity.this, loginBean.getData().getUser().getRestaurantId());
                    }
                    if (loginBean.isSuccess()) {

                        ToastUtils.show(LoginActivity.this, "登錄成功");

                        CC.obtainBuilder("Component.Table")
                                .setActionName("showTableActivity")
                                .build()
                                .call();
                    } else {
                        ToastUtils.show(LoginActivity.this, "登錄失敗");
                    }
                }

            }
        });
    }

}
