package com.rv.rvmine;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.base.utils.tools.android.IntentUtil;
import com.base.utils.ui.image.round.RoundImageView;
import com.frame.base.browse.ActivityImageBrowseInt;
import com.frame.base.glide.GlideManager;
import com.frame.rv.config.RvFrameConfig;
import com.frame.rv.widget.BaseTabLayout;
import com.frame.rv.ModuleEventUtil;
import com.frame.rv.OnModuleEventListener;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.util.UtilsManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.login.LoginRvActivity;
import com.rv.home.rv.module.ui.main.home.ConfirmOrderActivity;
import com.rv.home.rv.module.ui.main.home.bean.OrderPayBean;
import com.rv.home.rv.module.ui.main.home.order.OrderListActivity;
import com.rv.home.rv.module.ui.main.home.order.bean.OrderListBean;
import com.rv.home.rv.until.bus.PaymentFailedEvent;
import com.rv.home.rv.until.bus.PaymentSuccessfulEvent;
import com.rv.home.rv.until.bus.RxBus;
import com.rv.rvmine.bean.UserInfo;
import com.rv.rvmine.personal.IDCardCertificationActivity;
import com.rv.rvmine.rxbusevent.UserInfoEvent;
import com.rv.rvmine.traveler.PersonalInformationActivity;
import com.rv.rvmine.traveler.SettingActivity;
import com.yuyife.banner.Banner;
import com.yuyife.banner.BannerConfig;
import com.yuyife.banner.listener.OnBannerListener;
import com.yuyife.banner.loader.ImageLoader;
import com.yuyife.okgo.OkGoUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 我的
 */
public class MineActivity extends BaseStatusActivity<CommonPresenter> {

    @BindView(R2.id.travel_tab_layout)
    BaseTabLayout travelTabLayout;
    @BindView(R2.id.iv_avatar)
    RoundImageView ivAvatar;
    @BindView(R2.id.tv_nickname)
    TextView tvNickname;
    @BindView(R2.id.iv_member)
    ImageView ivMember;
    @BindView(R2.id.tv_login)
    TextView tvLogin;
    @BindView(R2.id.tv_verified)
    TextView tvVerified;
    @BindView(R2.id.iv_notification)
    ImageView ivNotification;
    @BindView(R2.id.tv_membership_level)
    TextView tvMembershipLevel;
    @BindView(R2.id.tv_member_hint)
    TextView tvMemberHint;
    @BindView(R2.id.tv_view_privileges)
    TextView tvViewPrivileges;
    @BindView(R2.id.rl_item_to_be_paid)
    RelativeLayout rlItemToBePaid;
    @BindView(R2.id.rl_item_staying)
    RelativeLayout rlItemStaying;
    @BindView(R2.id.rl_item_traveling)
    RelativeLayout rlItemTraveling;
    @BindView(R2.id.rl_item_completed)
    RelativeLayout rlItemCompleted;
    @BindView(R2.id.rl_item_all)
    RelativeLayout rlItemAll;
    @BindView(R2.id.rl_item_collection)
    RelativeLayout rlItemCollection;
    @BindView(R2.id.rl_item_personal_information)
    RelativeLayout rlItemPersonalInformation;
    @BindView(R2.id.rl_item_information)
    RelativeLayout rlItemInformation;
    @BindView(R2.id.rl_item_setting)
    RelativeLayout rlItemSetting;
    @BindView(R2.id.travel_fragment_layout)
    LinearLayout travelFragmentLayout;
    @BindView(R2.id.mine_banner)
    Banner mineBanner;

    @Override
    protected int setLayout() {
        return R.layout.activity_mine;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        ModuleEventUtil.currentActivity = this;

        showTitle(false);
        travelTabLayout.setCurrent(OnModuleEventListener.MODULE_MINE);
        setBanner();
        if (TextUtils.isEmpty(OkGoUtil.getToken())) {
            tvNickname.setVisibility(View.GONE);
            ivMember.setVisibility(View.GONE);
            tvLogin.setVisibility(View.VISIBLE);
            tvVerified.setVisibility(View.GONE);
        } else {
            tvNickname.setVisibility(View.VISIBLE);
            ivMember.setVisibility(View.VISIBLE);
            tvLogin.setVisibility(View.GONE);
            tvVerified.setVisibility(View.VISIBLE);
//            Log.i("Mineactivityty", "initView: " + UtilsManager.getInstance(mActivity).getSPStringCode("city_json", "headerurl"));
        }

        initRxBus();
    }


    @SuppressLint("CheckResult")
    private void initRxBus() {
        RxBus.tObservable(UserInfoEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Consumer<UserInfoEvent>() {
                    @Override
                    public void accept(UserInfoEvent info) throws Exception {
                        getUserData();
                    }
                });

    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        getUserData();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        ModuleEventUtil.currentActivity = this;

    }

    @OnClick({R2.id.iv_avatar, R2.id.tv_login, R2.id.tv_verified, R2.id.rl_item_to_be_paid, R2.id.rl_item_staying, R2.id.rl_item_traveling, R2.id.rl_item_completed, R2.id.rl_item_all, R2.id.rl_item_collection, R2.id.rl_item_personal_information, R2.id.rl_item_information, R2.id.rl_item_setting})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.iv_avatar) {
            //头像
            if (isLogin()) return;

        } else if (id == R.id.tv_login) {
            //登录
            startActivity(LoginRvActivity.getIntent(mActivity));

        } else if (id == R.id.tv_verified) {
            //实名认证
            if (isLogin()) return;
            startActivity(IDCardCertificationActivity.getIntent(mActivity));

        } else if (id == R.id.rl_item_to_be_paid) {
            //待支付
            if (isLogin()) return;
            startActivity(OrderListActivity.getIntent(mActivity, 0));

        } else if (id == R.id.rl_item_staying) {
            //待出行
            if (isLogin()) return;
            startActivity(OrderListActivity.getIntent(mActivity, 1));

        } else if (id == R.id.rl_item_traveling) {
            //出行中
            if (isLogin()) return;
            startActivity(OrderListActivity.getIntent(mActivity, 2));

        } else if (id == R.id.rl_item_completed) {
            //已完成
            if (isLogin()) return;
            startActivity(OrderListActivity.getIntent(mActivity, 3));

        } else if (id == R.id.rl_item_all) {
            //全部
            if (isLogin()) return;
            startActivity(OrderListActivity.getIntent(mActivity, 4));

        } else if (id == R.id.rl_item_collection) {
            //收藏
            if (isLogin()) return;
            showToast("该功能还在开发中");

        } else if (id == R.id.rl_item_personal_information) {
            //个人资料
            if (isLogin()) return;
            startActivity(PersonalInformationActivity.getIntent(mActivity));

        } else if (id == R.id.rl_item_information) {
            //信息
            if (isLogin()) return;
            showToast("该功能还在开发中");

        } else if (id == R.id.rl_item_setting) {
            //设置
            startActivityForResult(SettingActivity.getIntent(mActivity), 101);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == 201) {
            ivAvatar.setImageResource(R.drawable.common_icon_avatar_default);
            tvNickname.setVisibility(View.GONE);
            ivMember.setVisibility(View.GONE);
            tvLogin.setVisibility(View.VISIBLE);
            tvVerified.setVisibility(View.GONE);
        }
    }

    private ArrayList<String> images = new ArrayList<>();    //图片(默认采用网络地址)
    private List<String> titles = new ArrayList<>();         //图片标题
    private List<Integer> localImages = new ArrayList<>();   //图片(本地资源)

    private void setBanner() {
        titles.clear();
        images.clear();
        localImages.clear();

        localImages.add(R.drawable.abanner);
        localImages.add(R.drawable.abanner);

        mineBanner.setImages(localImages);
        for (int i = 0; i < localImages.size(); i++) {
            titles.add("");
        }
        mineBanner.isAutoPlay(true)
                .setBannerTitles(titles)
                .setDelayTime(3000)
                .setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {

                        GlideManager.getInstance(context).loadImage(path, imageView);
                    }
                })
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {
                        if (localImages != null && localImages.size() > 0) {
                            Bundle bundle = new Bundle();
                            bundle.putInt(ActivityImageBrowseInt.KEY_BACKGROUND, R.color.colorPrimary);
                            bundle.putIntegerArrayList(ActivityImageBrowseInt.KEY_IMAGE, (ArrayList<Integer>) localImages);
                            IntentUtil.startActivity(mActivity, ActivityImageBrowseInt.class, bundle);
                        }
                    }
                })
                .start();

        mineBanner.updateBannerStyle(BannerConfig.CIRCLE_INDICATOR);
    }

    /**
     * 获取用户信息请求
     */
    private void getUserData() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null) {
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.getData(RvFrameConfig.ADMIN_POST, 0, ApiConfig.HTTP_URL_APP_USER_INFO, UserInfo.class, headMap, false);
        }
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    private boolean isLogin() {
        if (TextUtils.isEmpty(OkGoUtil.getToken())) {
            startActivity(LoginRvActivity.getIntent(mActivity));
            return true;
        }
        return false;
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                userInfoData((UserInfo) result);
                break;
        }
    }

    private void userInfoData(UserInfo info) {
        if (info !=null) {
            GlideManager.getInstance(mActivity).loadImage(info.getHeadimgurl(), ivAvatar);
            tvNickname.setText(info.getUsername());
            if (info.getCertificationStatus() ==0){ //实名认证状态:0-未认证，1-已认证
                 tvVerified.setText("未实名认证");
                 tvVerified.setEnabled(true);
            }else if (info.getCertificationStatus() == 1){
                tvVerified.setText("已实名认证");
                tvVerified.setEnabled(false);
            }
        }
    }

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