package com.rv.rvmine;

import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
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.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.base.utils.tools.android.IntentUtil;
import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.base.utils.ui.image.round.RoundImageView;
import com.frame.base.bus.LoginSuccessfulEvent;
import com.frame.base.bus.Observer;
import com.frame.base.bus.PaymentFailedEvent;
import com.frame.base.bus.PaymentSuccessfulEvent;
import com.frame.base.bus.RxBus;
import com.frame.base.bus.WithdrawSuccessEvent;
import com.frame.base.url.Constance;
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.bean.UserInfoBean;
import com.ruiwenliu.wrapper.browse.ActivityImageBrowseInt;
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.component.utils.RvCache;
import com.rv.component.utils.CacheEnum;
import com.rv.home.rv.module.ApiConfig;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.login.LoginRvActivity;
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.points.Actions;
import com.rv.points.PointsActivity;
import com.rv.rvmine.bean.InfoProfitBean;
import com.rv.rvmine.personal.IDCardCertificationActivity;
import com.rv.rvmine.personal.IDCardCertificationShowActivity;
import com.rv.rvmine.rxbusevent.UserInfoEvent;
import com.rv.rvmine.traveler.CollectionActivity;
import com.rv.rvmine.traveler.MyReleaseActivity;
import com.rv.rvmine.traveler.PersonalInformationActivity;
import com.rv.rvmine.traveler.SettingActivity;
import com.rv.rvmine.traveler.TravelSettingsActivity;
import com.rv.share.ShareActivity;
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.OnClick;
import butterknife.Unbinder;
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_member)
    TextView tvMember;
    @BindView(R2.id.tv_login)
    TextView tvLogin;
    @BindView(R2.id.tv_verified)
    TextView tvVerified;
    @BindView(R2.id.tv_membership_level)
    TextView tvMembershipLevel;
    @BindView(R2.id.tv_member_hint)
    TextView tvMemberHint;
    @BindView(R2.id.tv_item_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_collection)
    RelativeLayout rlItemCollection;
    @BindView(R2.id.travel_fragment_layout)
    LinearLayout travelFragmentLayout;
    @BindView(R2.id.mine_banner)
    Banner mineBanner;
    @BindView(R2.id.refresh)
    SimpleRefreshLayout mSimpleRefreshLayout;
    @BindView(R2.id.tv_user_identity)
    TextView tvUserIdentity;
    @BindView(R2.id.tv_integral)
    TextView tvIntegral;
    @BindView(R2.id.tv_wallet)
    TextView tvWallet;
    @BindView(R2.id.tv_coupon)
    TextView tvCoupon;

    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);
            ((View) ivMember.getParent()).setVisibility(View.GONE);
            tvLogin.setVisibility(View.VISIBLE);
            tvVerified.setVisibility(View.GONE);
            tvViewPrivileges.setText("会员中心");
            mSimpleRefreshLayout.setPullDownEnable(false);
        } else {
            tvNickname.setVisibility(View.VISIBLE);
            ((View) ivMember.getParent()).setVisibility(View.VISIBLE);
//            ivMember.setVisibility(View.VISIBLE);
            tvLogin.setVisibility(View.GONE);
            tvVerified.setVisibility(View.VISIBLE);
            tvViewPrivileges.setText("查看会员特权");
            mSimpleRefreshLayout.setPullDownEnable(true);
        }

        String spStringCode = UtilsManager.getInstance(OkGoUtil.application).getSPStringCode(SPConstance.USER_JSON, SPConstance.USER_JSON_USERINFO);
        if (!TextUtil.isEmpty(spStringCode)) {
            UserInfoBean.UserInfo userInfo = JSON.parseObject(spStringCode, UserInfoBean.UserInfo.class);
            GlideManager.getInstance(_mActivity).loadImage(userInfo.getHeadimgurl(), ivAvatar);
            tvNickname.setText(userInfo.getNickname());
            setMember(userInfo);
        }


    }

    private void initRefresh() {

    }

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


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

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

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

        RxBus.tObservable(WithdrawSuccessEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<WithdrawSuccessEvent>(disposable) {
                    @Override
                    public void onNext(WithdrawSuccessEvent event) {
                        loadProfit();
                    }
                });
    }


    @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.iv_item_message,
            R2.id.rl_item_traveling, R2.id.rl_item_completed, R2.id.rl_item_collection, R2.id.rl_item_my_release,
            R2.id.iv_item_setting, R2.id.tv_item_view_privileges, R2.id.rl_item_order_all, R2.id.ll_item_integral, R2.id.ll_item_wallet,
            R2.id.ll_item_coupon, R2.id.ll_item_promotion, R2.id.rl_item_check_in, R2.id.rl_item_travel_management})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.iv_item_setting) {
            //设置
            if (isLogin()) return;
            startActivityForResult(SettingActivity.getIntent(_mActivity), 101);
        } else if (id == R.id.iv_item_message) {
            //消息通知
            if (isLogin()) return;
            showToast("该功能还在开发中。。。");

        } else if (id == R.id.iv_avatar) {
            //头像
            if (isLogin()) return;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                startActivity(PersonalInformationActivity.getIntent(_mActivity, info), ActivityOptions.makeSceneTransitionAnimation(_mActivity, ivAvatar, "sharedView").toBundle());
            } else {
                startActivity(PersonalInformationActivity.getIntent(_mActivity, info));
            }

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

        } else if (id == R.id.tv_verified) {
            //实名认证
            if (isLogin()) return;
            if (info == null) return;

            if (info.getCertificationStatus() == 0) { //实名认证状态:0-未认证，1-已认证
                startActivity(IDCardCertificationActivity.getIntent(_mActivity));
            } else {
                startActivity(IDCardCertificationShowActivity.getIntent(_mActivity, info.getRealname(), info.getIdNumber()));
            }

        } else if (id == R.id.ll_item_integral) {
            //积分
            if (isLogin()) return;
            startActivity(new Intent(_mActivity, PointsActivity.class));

        } else if (id == R.id.ll_item_wallet) {
            //钱包
            if (isLogin()) return;
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_WALLET)
                    .navigation();

        } else if (id == R.id.ll_item_coupon) {
            //优惠券
            if (isLogin()) return;
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_COUPONALL)
                    .navigation();

        } else if (id == R.id.ll_item_promotion) {
            //推广有奖
            if (isLogin()) return;
            startActivity(new Intent(_mActivity, ShareActivity.class));

        } else if (id == R.id.tv_item_view_privileges) {
            //会员中心
            if (isLogin()) return;
            startActivity(MemberCenterActivity.getIntent(_mActivity));

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

        } 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_my_release) {
            //我的发布
            if (isLogin()) return;
            startActivity(MyReleaseActivity.getIntent(_mActivity));

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

        } else if (id == R.id.rl_item_check_in) {
            //签到
            if (isLogin()) return;
            Actions.sign(_mActivity);

        } else if (id == R.id.rl_item_travel_management) {
            //出游管理
            if (isLogin()) return;
            startActivity(new Intent(_mActivity, TravelSettingsActivity.class));
        }

//        } else if (id == R.id.rl_item_driver) {
//            //驾驶人
//            if (isLogin()) return;
//            startActivity(DrivingListActivity.getIntent(_mActivity, null));

    }

    @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);
            ((View) ivMember.getParent()).setVisibility(View.GONE);
//            ivMember.setVisibility(View.GONE);
            tvLogin.setVisibility(View.VISIBLE);
            tvVerified.setVisibility(View.GONE);
            tvUserIdentity.setVisibility(View.GONE);
            tvViewPrivileges.setText("会员中心");
            tvMembershipLevel.setText("会员特权");
            tvMemberHint.setText("免费用车- -天");
            tvIntegral.setText("0");
            tvWallet.setText("0");
            tvCoupon.setText("0");
            mSimpleRefreshLayout.setPullDownEnable(false);
        }
    }

    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() {
        if (images != null && images.size() > 0) {
            mineBanner.setVisibility(View.VISIBLE);
        } else {
            mineBanner.setVisibility(View.GONE);
        }

        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).loadRoundImage2(path, imageView, 8);
                    }
                })
                .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 loadProfit() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null) {
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.getDataHead(RvFrameConfig.HOST, 2, ApiConfig.HTTP_URL_USER_PROFIT, InfoProfitBean.class, headMap, false);
        }
    }

    /**
     * 获取轮播图
     */
    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() {
        String token = OkGoUtil.getToken();
        if (TextUtils.isEmpty(token)) {
            startActivity(LoginRvActivity.getIntent(_mActivity,0));
            return true;
        }
        return false;
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        mSimpleRefreshLayout.onRefreshComplete();
        switch (requestType) {
            case 0:
                if (result != null) {
                    RvCache.getInstance(getContext()).save((UserInfoBean) result, CacheEnum.USER);
                }
                userInfoData((UserInfoBean) result);
                break;
            case 1:
                bannerData((BeanHomeBanner) result);
                break;
            case 2:
                profitData((InfoProfitBean) result);
                break;
        }
    }

    /**
     * 用户收益
     *
     * @param bean
     */
    private void profitData(InfoProfitBean bean) {
        if (bean != null && bean.getData() != null) {
            tvIntegral.setText(bean.getData().getTotalPoint());
            tvWallet.setText(bean.getData().getBalance());
            tvCoupon.setText(bean.getData().getCouponNumber());
        }
    }


    private void userInfoData(UserInfoBean infoBean) {
        if (infoBean != null) {
            info = infoBean.getData();
            if (info != null) {
                GlideManager.getInstance(_mActivity).loadImage(info.getHeadimgurl(), ivAvatar);
                tvNickname.setText(info.getNickname());
                //更新实名信息
                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("未实名认证");
                } else if (info.getCertificationStatus() == 1) {
                    tvVerified.setText("已实名认证");
                }

                if (!TextUtils.isEmpty(info.getIcon())) {
                    ivMember.setVisibility(View.VISIBLE);
                    GlideManager.getInstance(getContext()).loadImage(info.getIcon(), ivMember);
                } else {
                    ivMember.setVisibility(View.GONE);
                }
                if (TextUtils.isEmpty(info.getPositionName())) {
                    tvUserIdentity.setVisibility(View.GONE);
                } else {
                    tvUserIdentity.setText(info.getPositionName());
                    tvUserIdentity.setVisibility(View.VISIBLE);

                }

                setMember(info);
            }

            if (TextUtils.isEmpty(OkGoUtil.getToken())) {
                tvNickname.setVisibility(View.GONE);
                ((View) ivMember.getParent()).setVisibility(View.GONE);
//                ivMember.setVisibility(View.GONE);
                tvLogin.setVisibility(View.VISIBLE);
                tvVerified.setVisibility(View.GONE);
            } else {
                tvNickname.setVisibility(View.VISIBLE);
                ((View) ivMember.getParent()).setVisibility(View.VISIBLE);
//                ivMember.setVisibility(View.VISIBLE);
                tvLogin.setVisibility(View.GONE);
                tvVerified.setVisibility(View.VISIBLE);
            }
            mSimpleRefreshLayout.setPullDownEnable(true);
        }
    }

    private void setMember(UserInfoBean.UserInfo infos) {
        if (0 == infos.getIsMember()) {
            tvMembershipLevel.setText("会员特权");
            tvMemberHint.setText("免费用车- -天");
            tvMember.setText("普通用户");
        } else if (1 == infos.getIsMember()) {
            if (1 == infos.getMemberLevel()) { //1 普通会员 2 黄金会员 3 钻石会员
                tvMembershipLevel.setText(" 普通会员特权");
                tvMember.setText("普通会员");
            } else if (2 == infos.getMemberLevel()) {
                tvMembershipLevel.setText("黄金会员特权");
                tvMember.setText("黄金会员");
            } else if (3 == infos.getMemberLevel()) {
                tvMembershipLevel.setText("钻石会员特权");
                tvMember.setText("钻石会员");
            }
            tvMemberHint.setText("免费用车" + infos.getRentFreeDays() + "天");
        }
    }


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