package com.sheep.gamegroup.module.login.fragments;


import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.sheep.gamegroup.greendao.DDProviderHelper;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.LoginEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.module.login.controller.LoginController;
import com.sheep.gamegroup.greendao.download.Account;
import com.sheep.gamegroup.util.ChannelContent;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.FastJsonUtils;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.PreferenceUtils;
import com.sheep.gamegroup.util.StringUtils;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.view.customview.CountDownButton;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.sheep.gamegroup.util.UMConfigUtils.Event.LOGIN_QQ;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.LOGIN_WX;

/**
 * A simple {@link Fragment} subclass.
 */
public class SignInFgt extends AbsLoginFgt {

    private int loginType = LoginController.PLATFORM_PHONE;

    @BindView(R.id.for_account_pwd_container)
    View forAccountPwdContainer;
    @BindView(R.id.for_phone_container)
    View forPhoneContainer;
    @BindView(R.id.user_name_box)
    EditText userNameBox;
    @BindView(R.id.password_box)
    EditText passwordBox;
    @BindView(R.id.phone_number_box)
    EditText phoneNumberBox;
    @BindView(R.id.captcha_box)
    EditText captchaBox;
    @BindView(R.id.login_type_toggle)
    View loginTypeToggle;
    @BindView(R.id.login_type_toggle_icon)
    ImageView loginTypeToggleIcon;
    @BindView(R.id.login_type_toggle_text)
    TextView loginTypeToggleText;
    @BindView(R.id.send_captcha_btn)
    CountDownButton countDownButton;
    @BindView(R.id.account_menu_btn)
    ImageView accountMenuBtn;

    @BindView(R.id.test_change)
    TextView testChange;
    @BindView(R.id.test_change_user)
    TextView testChangeUser;
    @BindView(R.id.show_hide_pwd_btn)
    ImageView showHidePwdBtn;

    public SignInFgt() {
        // Required empty public constructor
    }

    public static SignInFgt newInstance(LoginController controller) {
        return newInstance(controller, LoginController.PLATFORM_PHONE);
    }

    public static SignInFgt newInstance(LoginController controller, int type) {
        SignInFgt fragment = new SignInFgt();
        fragment.mController = controller;
        fragment.loginType = type;
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_sign_in;
    }

    @Override
    public void onViewCreated() {
        TestUtil.testChange(getActivity(), testChange);
        TestUtil.testChangeUser(getActivity(), testChangeUser);
        if (loginType == LoginController.PLATFORM_PHONE) {
            forAccountPwdContainer.setVisibility(View.GONE);
            forPhoneContainer.setVisibility(View.VISIBLE);
            loginTypeToggle.setSelected(true);
            loginTypeToggleIcon.setImageResource(R.mipmap.login_account);
            loginTypeToggleText.setText("账号登录");
        } else {
            forAccountPwdContainer.setVisibility(View.VISIBLE);
            forPhoneContainer.setVisibility(View.GONE);
            loginTypeToggle.setSelected(false);
            loginTypeToggleIcon.setImageResource(R.mipmap.login_phone);
            loginTypeToggleText.setText("一键登录");
        }
    }

    @OnClick(R.id.login_btn)
    public void doLogin(View v) {
        if (loginTypeToggle.isSelected()) {
            phoneLogin();
        } else {
            accountLogin();
        }
    }

    private boolean validateAccountPwd() {
        String username = userNameBox.getText().toString().trim();
        String password = passwordBox.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            G.shortToast("请输入用户名");
            return false;
        }
        if (TextUtils.isEmpty(password)) {
            G.shortToast("密码不能为空");
            return false;
        }
        if (!StringUtils.isUserName(username)) {
            G.shortToast("用户名只能包含英文、数字、._-@符号，长度4-20");
            return false;
        }
        if (!StringUtils.isPassword(password)) {
            G.shortToast("密码只能包含英文、数字、_.-@$!*%符号，长度6-16");
            return false;
        }
        return true;
    }

    private void accountLogin() {
        if (!validateAccountPwd()) return;
        showProgress();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user_name", userNameBox.getText().toString().trim());
        jsonObject.put("password", passwordBox.getText().toString().trim());
//        jsonObject.put("invitation_code", scope);
        PreferenceUtils.setPrefString(SheepApp.getInstance(), UMConfigUtils.LOGIN_TYPE, UMConfigUtils.Source.SHEEP);
        SheepApp.getInstance().getNetComponent().getApiService().loginByUserName(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        hideProgress();
                        G.shortToast(baseMessage);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        hideProgress();
                        if (baseMessage == null) {
                            return;
                        }
                        LoginEntity loginEty = null;
                        try {
                            loginEty = JSONObject.parseObject(JSONObject.toJSONString(baseMessage.getData()), LoginEntity.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (loginEty != null) {
                            SpUtils.saveToken(getActivity(), loginEty.getToken());
                            DataUtil.getInstance().initUserEntity(loginEty.getUser());
                            mController.whenLoginSuccess(LoginController.PLATFORM_ACCOUNT, loginEty);
                        }
                    }
                });
    }

    private boolean validatePhoneCaptcha() {
        String etCode = captchaBox.getText().toString().trim();
        if (TextUtils.isEmpty(etCode)) {
            G.shortToast(getString(R.string.input_your_captcha));
            return false;
        }
        if (etCode.length() != 6) {
            G.shortToast(getString(R.string.toast_warning_phone_captcha_image_code_size));
            return false;
        }
        return true;
    }

    private void phoneLogin() {
        if (!validatePhoneCaptcha()) return;
        showProgress();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", phoneNumberBox.getText().toString().trim());
        jsonObject.put("sec_code", captchaBox.getText().toString().trim());
//        jsonObject.put("invitation_code", scope);
        PreferenceUtils.setPrefString(SheepApp.getInstance(), UMConfigUtils.LOGIN_TYPE, UMConfigUtils.Source.SHEEP);
        SheepApp.getInstance().getNetComponent().getApiService().loginByCaptcha(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        hideProgress();
                        G.shortToast(baseMessage);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        hideProgress();
                        if (baseMessage == null) {
                            return;
                        }
                        LoginEntity loginEty = null;
                        try {
                            loginEty = JSONObject.parseObject(JSONObject.toJSONString(baseMessage.getData()), LoginEntity.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (loginEty != null) {
                            SpUtils.saveToken(getActivity(), loginEty.getToken());
                            DataUtil.getInstance().initUserEntity(loginEty.getUser());
                            mController.whenLoginSuccess(LoginController.PLATFORM_PHONE, loginEty);
                        }
                    }
                });
    }

    @OnClick(R.id.send_captcha_btn)
    public void doSendCaptcha(View v) {
        String phoneNum = phoneNumberBox.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNum)) {
            G.shortToast("请输入手机号");
            return;
        }
        if (!StringUtils.isMobile(phoneNum)) {
            G.shortToast("手机号有误");
            return;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", phoneNum);
        SheepApp.getInstance().getNetComponent().getApiService().getCaptcha(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        Snackbar.make(v, "验证码已发送", Snackbar.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        Snackbar.make(v, "发生错误", Snackbar.LENGTH_SHORT).show();
                    }
                });
    }

    @OnClick(R.id.login_type_toggle)
    public void doToggleLoginType(View v) {
        loginTypeToggle.setSelected(!loginTypeToggle.isSelected());
        loginTypeToggleText.setText(loginTypeToggle.isSelected() ? "账号登录" : "一键登录");
        loginTypeToggleIcon.setImageResource(loginTypeToggle.isSelected() ? R.mipmap.login_account : R.mipmap.login_phone);
        forPhoneContainer.setVisibility(v.isSelected() ? View.VISIBLE : View.GONE);
        forAccountPwdContainer.setVisibility(!v.isSelected() ? View.VISIBLE : View.GONE);
    }

    @OnClick(R.id.register_btn)
    public void doRegister(View v) {
        mController.whenToRegister();
    }

    @OnClick(R.id.trouble_btn)
    public void doTrouble(View v) {
        mController.whenGoFindAccount();
    }

    @OnClick(R.id.account_menu_btn)
    public void doSelectAccount(View v) {
        final List<Account> listData = DDProviderHelper.getInstance().getAccountList();
        View flagView = findViewById(R.id.login_btn);
        RecyclerView listView = new RecyclerView(getContext());
        listView.setBackgroundResource(R.drawable.screenshot_panel);
        listView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        final PopupWindow popupWindow = new PopupWindow(listView,
                flagView.getMeasuredWidth(),
                ViewGroup.LayoutParams.WRAP_CONTENT);
        listView.setAdapter(new RecyclerView.Adapter() {
            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                View itemView = LayoutInflater.from(getContext()).inflate(R.layout.account_select_item, viewGroup, false);
                return new RecyclerView.ViewHolder(itemView) {
                };
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
                Account account = listData.get(i);
                ImageView accountAvatar = viewHolder.itemView.findViewById(R.id.account_avatar_view);
                TextView accountName = viewHolder.itemView.findViewById(R.id.account_name_view);
                View accountDelete = viewHolder.itemView.findViewById(R.id.account_delete_btn);
                if (!TextUtils.isEmpty(account.getAvatar())) {
                    GlideImageLoader.setAvatar(accountAvatar, account.getAvatar());
                }
                if (!TextUtils.isEmpty(account.getLoginname())) {
                    accountName.setText(account.getLoginname());
                }
                accountDelete.setOnClickListener(v -> {
                    listData.remove(account);
                    notifyDataSetChanged();
                    DDProviderHelper.getInstance().deleteAccount(account);
                });
                viewHolder.itemView.setOnClickListener(v -> {
                    if (loginTypeToggle.isSelected()) {
                        phoneNumberBox.setText(account.getLoginname());
                    } else {
                        userNameBox.setText(account.getLoginname());
                    }
                    popupWindow.dismiss();
                });
            }

            @Override
            public int getItemCount() {
                return listData.size();
            }
        });

        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        if (loginTypeToggle.isSelected()) {
            popupWindow.showAsDropDown(phoneNumberBox, 0, 5);
        } else {
            popupWindow.showAsDropDown(userNameBox, 0, 5);
        }
        popupWindow.setOnDismissListener(() -> {
            accountMenuBtn.setRotation(0);
        });
        accountMenuBtn.setRotation(180);
    }

    @Override
    public void onDestroy() {
        if (countDownButton != null) {
            countDownButton.onDestroy();
        }
        super.onDestroy();
    }

    @OnClick(R.id.show_hide_pwd_btn)
    public void doShowHidePwd(View v) {
        showHidePwdBtn.setSelected(!showHidePwdBtn.isSelected());
        showHidePwdBtn.setImageResource(showHidePwdBtn.isSelected() ? R.mipmap.pwd_show : R.mipmap.pwd_hide);
        if (showHidePwdBtn.isSelected()) {
            //如果选中，显示密码
            passwordBox.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            //否则隐藏密码
            passwordBox.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        passwordBox.setSelection(passwordBox.getText().toString().length());
    }

}
