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.bus.LoginSuccessfulEvent;
import com.frame.base.bus.RxBus;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.SPConstance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseFragment;
import com.ruiwenliu.wrapper.util.UtilsManager;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
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.DrivingListActivity;
import com.rv.home.rv.module.ui.main.home.order.OrderListActivity;
import com.rv.member.MemberCenterActivity;
import com.rv.rvmine.bean.UserInfoBean;
import com.rv.rvmine.personal.IDCardCertificationActivity;
import com.rv.rvmine.rxbusevent.UserInfoEvent;
import com.rv.rvmine.traveler.ChooseAVisitorActivity;
import com.rv.rvmine.traveler.CollectionActivity;
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 MineFragment extends BaseFragment<CommonPresenter> {

    @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_setting)
    RelativeLayout rlItemSetting;
    @BindView(R2.id.travel_fragment_layout)
    LinearLayout travelFragmentLayout;
    @BindView(R2.id.mine_banner)
    Banner mineBanner;

    private UserInfoBean.UserInfo info;

    public static MineFragment getInstance(int type) {
        Bundle bundl = new Bundle();
        bundl.putInt("type", type);
        MineFragment fragment = new MineFragment();
        fragment.setArguments(bundl);
        return fragment;
    }

    @Override
    public int getViewLayout() {
        return R.layout.activity_mine;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setBanner();
        initRxBus();

        if (TextUtils.isEmpty(OkGoUtil.getToken())) {
            tvNickname.setVisibility(View.GONE);
            ivMember.setVisibility(View.GONE);
            tvLogin.setVisibility(View.VISIBLE);
            tvVerified.setVisibility(View.GONE);
            tvViewPrivileges.setText("会员中心");
        } else {
            tvNickname.setVisibility(View.VISIBLE);
            ivMember.setVisibility(View.VISIBLE);
            tvLogin.setVisibility(View.GONE);
            tvVerified.setVisibility(View.VISIBLE);
            tvViewPrivileges.setText("查看会员特权");
        }
    }

    @Override
    protected void loadData(Bundle savedInstanceState) {
        getUserData();
    }


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

        RxBus.tObservable(LoginSuccessfulEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Consumer<LoginSuccessfulEvent>() {
                    @Override
                    public void accept(LoginSuccessfulEvent event) throws Exception {
                        getUserData();
                    }
                });

    }


    @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_setting, R2.id.rl_item_driver, R2.id.rl_item_traveler, R2.id.rl_item_my_pat, R2.id.tv_view_privileges})
    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_my_release) {
            //我的发布
            if (isLogin()) return;

        } else if (id == R.id.rl_item_collection) {
            //收藏
            if (isLogin()) return;
            startActivity(CollectionActivity.getIntent(_mActivity));

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

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

        } else if (id == R.id.rl_item_driver) {
            //驾驶人
            if (isLogin()) return;
            startActivity(DrivingListActivity.getIntent(_mActivity, null));
        } else if (id == R.id.rl_item_traveler) {
            //出游人
            if (isLogin()) return;
            startActivity(ChooseAVisitorActivity.getIntent(_mActivity));
        } else if (id == R.id.rl_item_my_pat) {
            //我的拍拍
        } else if (id == R.id.tv_view_privileges) {
            startActivity(MemberCenterActivity.getIntent(_mActivity));
        }
    }

    @Override
    public 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);
            tvViewPrivileges.setText("会员中心");
        }
    }

    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).loadImage2(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.getDataHead(RvFrameConfig.ADMIN_POST, 0, ApiConfig.HTTP_URL_APP_USER_INFO, UserInfoBean.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((UserInfoBean) result);
                break;
        }
    }

    private void userInfoData(UserInfoBean infoBean) {
        if (infoBean != null) {
            info = infoBean.getData();
            if (info != null) {
                GlideManager.getInstance(_mActivity).loadImage(info.getHeadimgurl(), ivAvatar);
                tvNickname.setText(info.getUsername());
                //更新实名信息
                UtilsManager.getInstance(_mActivity).setSharePreferencesSave(SPConstance.USER_JSON).putString(SPConstance.USER_JSON_ISCERTIFICATIONSTATUS, String.valueOf(info.getCertificationStatus())).commit();
                if (info.getCertificationStatus() == 0) { //实名认证状态:0-未认证，1-已认证
                    tvVerified.setText("未实名认证");
                    tvVerified.setEnabled(true);
                } else if (info.getCertificationStatus() == 1) {
                    tvVerified.setText("已实名认证");
                    tvVerified.setEnabled(false);
                }

                if (0 == info.getIsMember()) {
                    tvMembershipLevel.setText("会员特权");
                    ivMember.setImageResource(R.drawable.mycenter_icon_type_general_user);
                } else if (1 == info.getIsMember()) {
                    if (1 == info.getMemberLevel()) { //1 普通会员 2 黄金会员 3 钻石会员
                        tvMembershipLevel.setText(" 普通会员特权");
                        ivMember.setImageResource(R.drawable.mycenter_icon_type_ordinary_member);
                    } else if (2 == info.getMemberLevel()) {
                        tvMembershipLevel.setText("黄金会员特权");
                        ivMember.setImageResource(R.drawable.mycenter_icon_type_gold_member);
                    } else if (3 == info.getMemberLevel()) {
                        tvMembershipLevel.setText("钻石会员特权");
                        ivMember.setImageResource(R.drawable.mycenter_icon_type_diamond_membership);
                    }
                }

            }

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

}
