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

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.ui.bean.mode.LoginBean;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem;
import com.gingersoft.gsa.cloud.ui.widget.dialog.ChooseRestaurantDialog;
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.utils.ArmsUtils;

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

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 {
    @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;

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

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        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(GsaCloudApplication.getLoginToken(mContext).length() > 0){
//            jumpActivity();
//            finish();
//        }
        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().equals("")) {
                    icClear.setVisibility(View.GONE);
                } else {
                    icClear.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 (edAccount.getText().equals("")) {
                    icClearAccount.setVisibility(View.GONE);
                } else {
                    icClearAccount.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @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) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
//        ArmsUtils.snackbarText(message);
        ToastUtils.show(mContext, message);
    }

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

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

    @Override
    public void loginSuccess(LoginBean loginBean) {
        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());

                if (loginBean.getData().getUser().getBrands() != null) {
                    int restaurantSize = getRestaurantSize(loginBean.getData().getUser().getBrands());
//                if (restaurantSize > 1) {
                    new ChooseRestaurantDialog.BottomListSheetBuilder(this)
                            .addBrandItems(loginBean.getData().getUser().getBrands())
                            .setOnItemClickListener(new ChooseRestaurantDialog.BottomListSheetBuilder.OnItemClickListener() {

                                @Override
                                public void onItemClick(ChooseRestaurantDialog dialog, SectionTextItem item, int position) {
                                    GsaCloudApplication.setRestaurantId(LoginActivity.this, item.getId());
                                    GsaCloudApplication.setRestaurantName(LoginActivity.this, item.getText());
                                    jumpActivity();
//                                    killMyself();
//                                    dialog.dismiss();
                                }
                            })
                            .build()
                            .show();
//                } else if (restaurantSize == 1) {
//                    LoginBean.DataBean.UserBean.BrandsBean.RestaurantsBean restaurantsBean = getOnlyRestaurant(loginBean.getData().getUser().getBrands());
//                    if (restaurantsBean != null) {
//                        GsaCloudApplication.setRestaurantId(LoginActivity.this, restaurantsBean.getRestaurantId());
//                    }
//                }
                }
            }
        }

//        if (loginBean.getData().getUser() != null) {
//            GsaCloudApplication.setMemberId(LoginActivity.this, loginBean.getData().getUser().getUserId());
////            GsaCloudApplication.setRestaurantId(LoginActivity.this, loginBean.getData().getUser().getRestaurants().get(0).getRestaurantId());
//        }

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

//        jumpActivity();
    }

    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.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 void jumpActivity() {
        CC.obtainBuilder("Component.Download")
                .setActionName("showDownloadActivity")
                .build()
                .call();
    }

    @Override
    public void loginOut() {

    }

    @Override
    @OnClick({R.id.tv_gsa_user_login, R.id.iv_clear_pwd, R.id.iv_clear_account})
    public void onClick(View v) {
        switch (v.getId()) {
            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();
        Log.e("aaa", "登錄");
        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, "登錄失敗");
                    }
                }

            }
        });
    }

}
