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.TextUtils;
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.JsonUtils;
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.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.utils.ArmsUtils;

import java.io.IOException;
import java.util.ArrayList;
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
    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) {
        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) {
        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) {
        if (message != null)
            ArmsUtils.makeText(this, message);
    }

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

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

    @Override
    public void loginSuccess(LoginBean loginBean) {

        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 {
                    new ChooseRestaurantDialog.BottomListSheetBuilder(this)
                            .addBrandItems(brandsBeans)
                            .setOnItemClickListener(new ChooseRestaurantDialog.BottomListSheetBuilder.OnItemClickListener() {

                                @Override
                                public void onItemClick(ChooseRestaurantDialog dialog, SectionTextItem item, int position) {

                                    LoginBean.DataBean.UserBean.BrandsBean brandsBean = getBrandByRestaurantId(brands, item.getId());
                                    if (brandsBean != null) {
                                        saveBrandAndRestaurantInfo(brandsBean.getBrandId(), brandsBean.getBrandName(), item.getId(), item.getText());
                                    }

                                    jumpDownloadActivity();
                                    killMyself();
//                                    dialog.dismiss();
                                }
                            })
                            .build()
                            .show();
                }
            }
        }

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

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

    @Override
    public void loginOut() {

    }

    @Override
    @OnClick({R2.id.tv_gsa_user_login, R2.id.iv_clear_pwd, R2.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();
        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, "登錄失敗");
                    }
                }

            }
        });
    }

}
