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.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
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.Observer;
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.ruiwenliu.wrapper.weight.refresh.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
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.bean.BeanHomeBanner;
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.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

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

/**
 * 我的
 */
public class MineFragment extends BaseFragment<CommonPresenter> implements SimpleRefreshLayout.OnSimpleRefreshListener {

    @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;
    @BindView(R2.id.refresh)
    SimpleRefreshLayout mSimpleRefreshLayout;

    Unbinder unbinder;

    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) {
        mSimpleRefreshLayout.setHeaderView(new SimpleRefreshView(_mActivity));
        mSimpleRefreshLayout.setOnSimpleRefreshListener(this);
        setBanner();
        initRxBus();
        initRefresh();

        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("查看会员特权");
        }
    }

    private void initRefresh() {

    }

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


    @SuppressLint("CheckResult")
    private void initRxBus() {

        RxBus.tObservable(UserInfoEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<UserInfoEvent>(disposable) {
                    @Override
                    public void onNext(UserInfoEvent info) {
                        getUserData();
                    }
                });

        RxBus.tObservable(LoginSuccessfulEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<LoginSuccessfulEvent>(disposable) {
                    @Override
                    public void onNext(LoginSuccessfulEvent event) {
                        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("会员中心");
            tvMembershipLevel.setText("会员特权");
            tvMemberHint.setText("免费用车7天");
        }
    }

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

    private void bannerData(BeanHomeBanner data) {
        if (data != null) {
            titles.clear();
            images.clear();
            for (int i = 0; i < data.getData().size(); i++) {
                images.add(data.getData().get(i).getCover());
                titles.add("");
            }
        }
        setBanner();
    }


    private void setBanner() {
        mineBanner.isAutoPlay(true)
                .setBannerTitles(titles)
                .setImages(images)
                .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 loadBannerData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("type", "3");
        mPresenter.getData(1, ApiConfig.HTTP_URL_FIND_BANNERLIST, BeanHomeBanner.class, map, false);
    }

    /**
     * 获取用户信息请求
     */
    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);
                mSimpleRefreshLayout.onRefreshComplete();
                break;
            case 1:
                bannerData((BeanHomeBanner) 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(OkGoUtil.application).setSharePreferencesSave(SPConstance.USER_JSON).putString(SPConstance.USER_JSON_USERINFO, JSON.toJSONString(info)).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("会员特权");
                    tvMemberHint.setText("免费用车7天");
                    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);
                    }
                    tvMemberHint.setText("免费用车" + info.getRentFreeDays() + "天");
                }

            }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onRefresh() {
        getUserData();
    }
}
