package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.kfzs.appstore.utils.adapter.recyclerview.RecyclerViewAdapter;
import com.kfzs.appstore.utils.adapter.recyclerview.ViewHolder;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.greendao.DDProviderHelper;
import com.sheep.gamegroup.greendao.download.SdkLoginUser;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.util.CertificationUtil;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.customview.TextProgressBar;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * 认证登录界面
 * Created by ljy on 2018/9/11.
 */

public class GameCertificationActivity extends BaseActivity {

    @BindView(R.id.sdk_arrow)
    ImageView sdk_arrow;
    @BindView(R.id.icon_iv)
    ImageView icon_iv;
    @BindView(R.id.app_name_tv)
    TextView app_name_tv;
    @BindView(R.id.sdk_user_name)
    TextView sdk_user_name;
    @BindView(R.id.sdk_user_code)
    TextView sdk_user_code;
    @BindView(R.id.sdk_user_iv)
    ImageView sdk_user_iv;
    @BindView(R.id.sdk_change_user_list)
    RecyclerView sdk_change_user_list;
    @BindView(R.id.loading_view_img)
    View loading_view_img;
    @BindView(R.id.change_account_tv)
    TextView change_account_tv;
    @BindView(R.id.change_commit)
    TextView change_commit;

    private Activity activity;
    private Bundle extras;
    private UserEntity userEntity;
    private String packageName;
    private TextProgressBar textProgressBar;
    private boolean isChangeAccount;

    @Override
    protected int getLayoutId() {
        return R.layout.act_game_certification;
    }

    @Override
    public void initView() {
        activity = this;
        textProgressBar = new TextProgressBar(activity);
        textProgressBar.setVisibility(View.VISIBLE);
        TitleBarUtils.getInstance()
//                .setShowOrHide(this, true)
                .setTitle(activity, "授权登录")
                .setTitleListen(activity, 0, null);
        sdk_change_user_list.setVisibility(View.GONE);
    }

    private List<SdkLoginUser> userList = ListUtil.emptyList();

    @Override
    public void initListener() {
        sdk_change_user_list.setLayoutManager(new LinearLayoutManager(this));
        sdk_change_user_list.setHasFixedSize(true);
        sdk_change_user_list.setNestedScrollingEnabled(false);
        sdk_change_user_list.setAdapter(new RecyclerViewAdapter<SdkLoginUser>(this, R.layout.include_item_sdk_user, userList) {
            @Override
            public void convert(ViewHolder viewHolder, final SdkLoginUser item, final int position) {
                ImageView item_sdk_arrow = viewHolder.itemView.findViewById(R.id.item_sdk_arrow);
                ImageView item_sdk_user_iv = viewHolder.itemView.findViewById(R.id.item_sdk_user_iv);
                TextView item_sdk_user_name = viewHolder.itemView.findViewById(R.id.item_sdk_user_name);
                TextView item_sdk_user_code = viewHolder.itemView.findViewById(R.id.item_sdk_user_code);
                View item_sdk_user_line = viewHolder.itemView.findViewById(R.id.item_sdk_user_line);
                ViewUtil.setVisibility2(item_sdk_user_line, position != 0);
                ViewUtil.setText(item_sdk_user_name, item.getNickname());
                ViewUtil.setText(item_sdk_user_code, item.getInvitation_code());
                GlideImageLoader.setAvatar(item_sdk_user_iv, item.getAvatar());
                item_sdk_arrow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        DDProviderHelper.getInstance().deleteSdkLoginUser(item);
                        try {
                            userList.remove(position);
                            sdk_change_user_list.getAdapter().notifyDataSetChanged();
                            ViewUtil.setVisibility(sdk_change_user_list, !userList.isEmpty() && isUserListOpen);
                            ViewUtil.setVisibility2(sdk_arrow, !userList.isEmpty());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CertificationUtil.newInstance().authCertificationCode(activity, item.getToken());
                    }
                });
            }
        });
    }

    public void initData() {
        extras = getIntent().getExtras();
        userEntity = DataUtil.getInstance().getUserEntity();
        if (extras != null) {
            SheepApp.getInstance().setGameCode(extras.getString(getString(R.string.kfzs_duanduan_datashare_game_code), ""));
            packageName = extras.getString(getString(R.string.kfzs_duanduan_datashare_package_name), "");
            SheepApp.getInstance().setGamePackgeName(packageName);
            if (TextUtils.isEmpty(SheepApp.getInstance().getGameCode()) || TextUtils.isEmpty(packageName)) {
                CertificationUtil.newInstance().showCertificationErrorAndExitApp("", 2000);
                return;
            }
            hasToken();
        } else {
            CertificationUtil.newInstance().showCertificationErrorAndExitApp("", 2000);
        }
        //获取登录过的用户列表
        userList.addAll(DDProviderHelper.getInstance().getSdkLoginUserList(SheepApp.getInstance().getConnectAddress().name()));
        sdk_change_user_list.getAdapter().notifyDataSetChanged();
        ViewUtil.setVisibility2(sdk_arrow, !userList.isEmpty());
    }

    //是否展开登录用户列表
    private boolean isUserListOpen = false;

    @OnClick({R.id.icon_iv, R.id.change_account_tv, R.id.change_commit, R.id.sdk_arrow})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sdk_arrow:
                if (isUserListOpen) {//展开
                    sdk_arrow.setRotation(0);
                } else {
                    sdk_arrow.setRotation(180);
                }
                isUserListOpen = !isUserListOpen;
                ViewUtil.setVisibility(sdk_change_user_list, isUserListOpen);
                break;
            case R.id.icon_iv:
                textProgressBar.setVisibility(View.GONE);
                break;
            case R.id.change_account_tv:
                isChangeAccount = true;
                Jump2View.getInstance().goLoginView(activity, SheepApp.getInstance().getGameCode());
                break;
            case R.id.change_commit:
                commitChange();
                break;
        }
    }

    private void commitChange() {
        loading_view_img.setVisibility(View.VISIBLE);
        change_commit.setText(R.string.change_login_ing);
        change_commit.setEnabled(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isChangeAccount)
                    CertificationUtil.newInstance().authCertificationCode(activity, SpUtils.getToken(SheepApp.getInstance()));
            }
        }, 3000);
    }

    /**
     * 是否登录
     * 请求授权
     */
    private void hasToken() {
        String token = SpUtils.getToken(SheepApp.getInstance());
        if (TextUtils.isEmpty(token)) {
            Jump2View.getInstance().goLoginView(activity, SheepApp.getInstance().getGameCode());
        } else {
            if (userEntity == null) {
                CommonUtil.getInstance().updateUserInfo(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity userEntity) {
                        if (userEntity == null) {
                            Jump2View.getInstance().goLoginView(activity, SheepApp.getInstance().getGameCode());
                        } else {
                            initWidget();
                        }
                    }
                });
            } else {
                initWidget();
            }

        }
    }

    /**
     * 赋值
     */
    private void initWidget() {
        ViewUtil.setText(sdk_user_name, userEntity.getNickname());
        ViewUtil.setText(sdk_user_code, userEntity.getInvitation_code());
        GlideImageLoader.setAvatar(sdk_user_iv, userEntity.getAvatar());
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (!TextUtils.isEmpty(SheepApp.getInstance().getGamePackgeName())) {
            SheepApp.getInstance().setGameFlag(true);
        }
    }
}
