package com.yidianling.user.mine;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.ydl.course.api.ICourseService;
import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydl_image.module.GlideApp;
import com.ydl.ydlcommon.base.BaseFragment;
import com.ydl.ydlcommon.base.config.HttpConfig;
import com.ydl.ydlcommon.data.PlatformRamImpl;
import com.ydl.ydlcommon.data.http.BaseCommand;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.data.http.ThrowableConsumer;
import com.ydl.ydlcommon.modular.ModularServiceManager;
import com.ydl.ydlcommon.utils.BuryPointUtils;
import com.ydl.ydlcommon.utils.Utils;
import com.ydl.ydlcommon.utils.YdlBuryPointUtil;
import com.ydl.ydlcommon.view.JumpTextView;
import com.ydl.ydlcommon.view.dialog.YDLShareDialog;
import com.ydl.ydlcommon.view.widgets.BorderCircleImageView;
import com.yidianling.consultant.api.IConsultantService;
import com.yidianling.dynamic.api.IDynamicService;
import com.yidianling.im.api.service.IImService;
import com.yidianling.im.message.param.MsgListParam;
import com.yidianling.user.BuildConfig;
import com.yidianling.user.R;
import com.yidianling.user.UserHelper;
import com.yidianling.user.api.bean.UserResponseBean;
import com.yidianling.user.api.event.RefreshRecentContactListEvent;
import com.yidianling.user.api.service.IAppService;
import com.yidianling.user.mine.data.AppDataManager;
import com.yidianling.user.mine.http.MineHttpImpl;
import com.yidianling.user.safePrivate.PrivacyActivity;
import com.yidianling.user.ui.login.RegisterAndLoginActivity;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.text.SimpleDateFormat;
import java.util.Date;

import de.greenrobot.event.EventBus;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * 我的Tab
 * Created by softrice on 15/11/23.
 */
public class MineFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {

    String share_title = "壹点灵-专业心理咨询平台";
    String share_context = "帮您解决各种恋爱情感、婚姻、生活烦恼";
    String share_head = "http://static.ydlcdn.com/v1/images/logo320.png";
    String share_url = "http://m.yidianling.com/app";
    UserResponseBean.UserInfo userInfoData;

    ImageView img_bg;
    BorderCircleImageView img_head;
    TextView text_userName;
    JumpTextView jtv_account_setting;
    JumpTextView jtv_account_privacy;
    JumpTextView jtv_account_help;
    JumpTextView jtv_about_us;
    JumpTextView jtv_account_share;
    JumpTextView jtv_account_enter;

    TextView tishi;
    private TextView mAttentionTv;
    private CardView mDurationCardView;
    private TextView mTendNumTv;
    private TextView mDurationTv;
    private TextView mFansNumTv;
    private View mNewCoupon;
    private ImageView mLogoView;
    private TextView mTestRecordNumTv;
    //debug包下切换环境的按钮
    private Button mChangeBtn;
    /**
     * debug包下任意门入口
     * 可在这个按钮点击事件中去到任何你想去的地方
     */
    private JumpTextView jtv_test;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override

    public int layoutResId() {
        return R.layout.user_mine_fragment_mine;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initDataAndEvent() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        swipeRefreshLayout = getRootView().findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(getContext(), R.color.platform_main_theme));
        swipeRefreshLayout.setProgressViewOffset(false, 0, 200);

        img_bg = getRootView().findViewById(R.id.img_bg);
        img_head = getRootView().findViewById(R.id.img_head);
        text_userName = getRootView().findViewById(R.id.text_userName);
        mDurationTv = getRootView().findViewById(R.id.tv_duration);
        mDurationCardView = getRootView().findViewById(R.id.cv_duration);
        mAttentionTv = getRootView().findViewById(R.id.tv_attention_num);
        mChangeBtn = getRootView().findViewById(R.id.btn_change);
        mTendNumTv = getRootView().findViewById(R.id.tv_trend_num);
        mFansNumTv = getRootView().findViewById(R.id.tv_fans_tv);
        mTestRecordNumTv = getRootView().findViewById(R.id.tv_test_record_num);
        jtv_account_setting = getRootView().findViewById(R.id.jtv_account_setting);
        jtv_account_privacy = getRootView().findViewById(R.id.jtv_account_privacy);
        jtv_account_help = getRootView().findViewById(R.id.jtv_account_help);
        jtv_about_us = getRootView().findViewById(R.id.jtv_about_us);
        jtv_account_share = getRootView().findViewById(R.id.jtv_account_share);
        jtv_account_enter = getRootView().findViewById(R.id.jtv_account_enter);
        jtv_test = getRootView().findViewById(R.id.jtv_test);
        tishi = getRootView().findViewById(R.id.tishi);
        mNewCoupon = getRootView().findViewById(R.id.view_new_coupon);
        mLogoView = getRootView().findViewById(R.id.iv_mine_logo);
        img_head.setOnClickListener(this);
        mChangeBtn.setOnClickListener(this);
        jtv_account_setting.setOnClickListener(this);
        jtv_account_privacy.setOnClickListener(this);
        jtv_account_help.setOnClickListener(this);
        jtv_about_us.setOnClickListener(this);
        jtv_account_enter.setOnClickListener(this);
        jtv_account_share.setOnClickListener(this);
        mDurationCardView.setOnClickListener(this);
        text_userName.setOnClickListener(this);
        jtv_test.setOnClickListener(this);
        swipeRefreshLayout.setOnRefreshListener(this);
        getRootView().findViewById(R.id.ll_trade_order).setOnClickListener(this);
        getRootView().findViewById(R.id.jtv_introduce).setOnClickListener(this);
        getRootView().findViewById(R.id.iv_edit_info).setOnClickListener(this);
        getRootView().findViewById(R.id.ll_reward).setOnClickListener(this);
        getRootView().findViewById(R.id.ll_my_courses).setOnClickListener(this);
        getRootView().findViewById(R.id.ll_red_packet).setOnClickListener(this);
        getRootView().findViewById(R.id.ll_call_order).setOnClickListener(this);
        getRootView().findViewById(R.id.ll_account).setOnClickListener(this);
        getRootView().findViewById(R.id.ll_guanzhu).setOnClickListener(this);
        getRootView().findViewById(R.id.ll_my_trends).setOnClickListener(this);
        getRootView().findViewById(R.id.ll_fans).setOnClickListener(this);
        getRootView().findViewById(R.id.ll_my_test_log).setOnClickListener(this);
        init();


        GlideApp.with(this).load("https://static.yidianling.com/banner/bottombanner@2x.png").into(mLogoView);

//        jtv_test.setVisibility(BuildConfig.DEBUG ? View.VISIBLE : View.GONE);

        refreshCouponData();
    }

    @Override
    public void initDataAndEventLazy() {

    }

    void init() {
        if (null != PlatformRamImpl.Companion.getInstance().getGlobalInfo() && null != PlatformRamImpl.Companion.getInstance().getGlobalInfo().info && null != PlatformRamImpl.Companion.getInstance().getGlobalInfo().info.app_share) {
            share_title = PlatformRamImpl.Companion.getInstance().getGlobalInfo().info.app_share.title;
            share_context = PlatformRamImpl.Companion.getInstance().getGlobalInfo().info.app_share.descrip;
            share_head = PlatformRamImpl.Companion.getInstance().getGlobalInfo().info.app_share.cover_url;
            share_url = PlatformRamImpl.Companion.getInstance().getGlobalInfo().info.app_share.dl_url;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isResumed()) {
            showConsultAssistantDialog();
        } else {
            hideConsultAssistantDialog();
        }
        if (isVisibleToUser && isResumed()) {
            onResume();
        }
    }

    private void showConsultAssistantDialog() {
        ModularServiceManager.INSTANCE.provide(IConsultantService.class).showConsultAssistantMineDialog(getActivity());
    }

    private void hideConsultAssistantDialog() {
        ModularServiceManager.INSTANCE.provide(IConsultantService.class).hideConsultAssistantMineDialog();
    }

    /**
     * DEBUG包中：增加切换环境功能，线上包会自动隐藏此按钮
     */
    private void debugChangeEnvironment() {
        //debug包、未登录前提下才能切换环境
        if (BuildConfig.DEBUG && !UserHelper.INSTANCE.isLogin()) {
            mChangeBtn.setVisibility(View.VISIBLE);
        } else {
            mChangeBtn.setVisibility(View.GONE);
        }
    }


    @Override
    public void onRefresh() {
        updateUserInfo();

        refreshCouponData();
    }

    /**
     * 更新优惠券信息
     */
    @SuppressLint("CheckResult")
    private void refreshCouponData() {
        UserResponseBean userInfo = UserHelper.INSTANCE.getUserInfo();
        //获取用户信息
        if (userInfo == null) {
            return;
        }
        MineHttpImpl.Companion.getInstance().getNewCoupon(new BaseCommand())
                .compose(RxUtils.netCheck())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.data != null) {
                        if (response.data.count > 0) {
                            mNewCoupon.setVisibility(View.VISIBLE);
                        } else {
                            mNewCoupon.setVisibility(View.INVISIBLE);
                        }
                    }
                }, throwable -> {
                });
    }

    /**
     * 更新用户信息
     */
    @SuppressLint("CheckResult")
    private void updateUserInfo() {
        UserResponseBean userInfo = UserHelper.INSTANCE.getUserInfo();
        //获取用户信息
        if (userInfo == null) {
            swipeRefreshLayout.setRefreshing(false);
            return;
        }
        if (userInfo.getUid() == null || userInfo.getAccessToken() == null) {
            swipeRefreshLayout.setRefreshing(false);
            return;
        }
        AppDataManager.INSTANCE.getHttp().getUserInfo()
                .compose(RxUtils.resultJavaData())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    swipeRefreshLayout.setRefreshing(false);
                    try {
                        //此处后端返回信息，只有userinfo，其它数据为空，切勿整体赋值
                        UserHelper.INSTANCE.getUserInfo().setUserInfo(response.getUserInfo());
                        updateUI();
                    } catch (Exception e) {
                    }
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }


    /**
     * 获取用户信息成功后调用此方法更新 ui
     */
    public void updateUI() {
        initdata();
        if (AppDataManager.INSTANCE.getLocal().hasUpdate()) {
            jtv_about_us.setLeftRedDotVisibility(View.VISIBLE);
        } else {
            jtv_about_us.setLeftRedDotVisibility(View.GONE);
        }

        //切换环境按钮逻辑
        debugChangeEnvironment();
    }


    private void initdata() {
        if (UserHelper.INSTANCE.isLogin()) {
            setUserInfo(UserHelper.INSTANCE.getUserInfo().getUserInfo());
        } else {
            text_userName.setText("未登录");
            mDurationTv.setText("点击登录/注册");
            img_head.setImageResource(R.drawable.platform_head_place_hold_pic);
            mAttentionTv.setText("0");
            mTendNumTv.setText("0");
            mFansNumTv.setText("0");
            mTestRecordNumTv.setText("0");

            mNewCoupon.setVisibility(View.INVISIBLE);
        }
    }

    private void setUserInfo(UserResponseBean.UserInfo userInfo) {
        this.userInfoData = userInfo;

        if (userInfo == null) return;

        String nick_name = userInfo.getNick_name();
        if (!TextUtils.isEmpty(nick_name))
            text_userName.setText(nick_name);
        else
            text_userName.setText("昵称未设置");

        mAttentionTv.setText(String.valueOf(userInfo.getAttentionNum()));
        mTendNumTv.setText(String.valueOf(userInfo.getTrendNum()));
        mFansNumTv.setText(String.valueOf(userInfo.getFansNum()));
        mTestRecordNumTv.setText(String.valueOf(userInfo.getTestRecordNum()));
        mDurationTv.setText(userInfo.getRegistTime());
        mDurationCardView.setVisibility(View.VISIBLE);

        if (userInfo.getHead() != null) {
            GlideApp.with(this)
                    .load(userInfo.getHead())
                    .dontAnimate()
                    .placeholder(R.drawable.platform_head_place_hold_pic)
                    .error(R.drawable.platform_head_place_hold_pic)
                    .into(img_head);

        }
        //33说去掉
//        if (!TextUtils.isEmpty(userInfo.getHome_bg())) {
//            GlideApp.with(this).load(userInfo.getHome_bg()).error(R.drawable.profile_bg_11).into(img_bg);//设置封面
//        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();//切换环境逻辑按钮
        if (id == R.id.text_userName || id == R.id.cv_duration) {
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
            }
        } else if (id == R.id.iv_edit_info) {//修改资料
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }
            if (userInfoData != null) {
                Intent intentuser = new Intent(getActivity(), PersonalInfoActivity.class);
                startActivity(intentuser);
            }
        } else if (id == R.id.img_head) {//头像
            if (Utils.isFastClick()) {
                return;
            }
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }
            if (userInfoData != null) {
                Intent intentuser = new Intent(getActivity(), PersonalInfoActivity.class);
                startActivity(intentuser);
            }
        } else if (id == R.id.ll_account) {//账户余额
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }
            startActivity(new Intent(getActivity(), AccountHistoryActivity.class));
        } else if (id == R.id.ll_red_packet) {//我的红包
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }
            clearCouponStatus();
            ModularServiceManager.INSTANCE.provide(IAppService.class).myRedPockIntent(getActivity());
        } else if (id == R.id.ll_fans) {//粉丝
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }

            H5Params h5Params = new H5Params(HttpConfig.Companion.getH5_URL() + "mine/fans-list", null);
            NewH5Activity.start(getActivity(), h5Params);
        } else if (id == R.id.ll_guanzhu) {//我关注的
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }

            H5Params h5Params1 = new H5Params(HttpConfig.Companion.getH5_URL() + "mine/follow-per", null);
            NewH5Activity.start(getActivity(), h5Params1);
        } else if (id == R.id.ll_my_trends) {
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }
            BuryPointUtils.getInstance().createMap()
                    .put("mine_name", "我的动态")
                    .burryPoint("mine");
            try {
                Intent intentm = ModularServiceManager.INSTANCE.provide(IDynamicService.class).getMyTrendsActivityIntent(getActivity());
                startActivity(intentm);
            } catch (Exception e) {
            }
        } else if (id == R.id.jtv_account_setting) {//账号设置
            //点击消息 未登录请先登录
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }
            startActivity(new Intent(getActivity(), AccountSettingActivity.class));
        } else if (id == R.id.jtv_account_privacy) {// 未登录请先登录
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }
            UserHelper.INSTANCE.getUsetSetting().setMeSafePrivateIsClick(true);
            jtv_account_privacy.setLeftRedDotVisibility(View.GONE);
            startActivity(new Intent(getActivity(), PrivacyActivity.class));
        } else if (id == R.id.ll_trade_order) {//预约
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }
            BuryPointUtils.getInstance().createMap()
                    .put("mine_name", "预约订单")
                    .burryPoint("mine");
            H5Params h5Params3 = new H5Params(HttpConfig.Companion.getH5_URL() + "order", null);
            h5Params3.setShowMenu(true);
            NewH5Activity.start(getActivity(), h5Params3);
        } else if (id == R.id.ll_my_courses) {//我的课程
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }
            ModularServiceManager.INSTANCE.provide(ICourseService.class).startMyCourseActivity(getActivity());
        } else if (id == R.id.ll_call_order) {//倾诉
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }
            BuryPointUtils.getInstance().createMap()
                    .put("mine_name", "倾诉记录")
                    .burryPoint("mine");
            H5Params h5Paramsqing = new H5Params(HttpConfig.Companion.getYDL_H5() + "confideOrderList", null);
            NewH5Activity.start(getActivity(), h5Paramsqing);
        } else if (id == R.id.jtv_account_help) {//帮助
            H5Params params = new H5Params(HttpConfig.Companion.getH5_URL() + "help/", "");
            params.setShowMenu(true);
            NewH5Activity.start(getActivity(), params);
        } else if (id == R.id.jtv_account_enter) {//专家入驻
            if (PlatformRamImpl.Companion.getInstance().getGlobalInfo() != null &&
                    PlatformRamImpl.Companion.getInstance().getGlobalInfo().info != null &&
                    !TextUtils.isEmpty(PlatformRamImpl.Companion.getInstance().getGlobalInfo().info.join_doctor_url)) {
                H5Params h5Paramzhuan = new H5Params(PlatformRamImpl.Companion.getInstance().getGlobalInfo().info.join_doctor_url, null);
                NewH5Activity.start(getActivity(), h5Paramzhuan);
            } else {
                H5Params h5Paramzhuan = new H5Params("http://m.yidianling.com/enter?", null);
                NewH5Activity.start(getActivity(), h5Paramzhuan);
            }
        } else if (id == R.id.ll_my_test_log) {//测试记录
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }
            BuryPointUtils.getInstance().createMap()
                    .put("mine_name", "测试记录")
                    .burryPoint("mine");
            H5Params testParam = new H5Params(HttpConfig.Companion.getMH5_URL() + "ceshi/my-test", "测试记录");
            NewH5Activity.start(getActivity(), testParam);
        } else if (id == R.id.jtv_account_share) {//分享
            share();
        } else if (id == R.id.jtv_about_us) {
            startActivity(new Intent(getActivity(), AboutUsActivity.class));
        } else if (id == R.id.jtv_introduce) {
            H5Params params1 = new H5Params("https://m.yidianling.com/about", "网站介绍");
            NewH5Activity.start(getActivity(), params1);
        } else if (id == R.id.ll_reward) {
            if (!UserHelper.INSTANCE.isLogin()) {
                RegisterAndLoginActivity.Companion.start(getActivity());
                return;
            }
            H5Params h5Param = new H5Params(HttpConfig.Companion.getH5_URL() + "course/invite-record", null);
            NewH5Activity.start(getActivity(), h5Param);
        } else if (id == R.id.btn_change) {
        } else if (id == R.id.jtv_test) {//debug下任意门入口
            SimpleDateFormat sdf = new SimpleDateFormat();
            sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            jtv_test.postDelayed(new Runnable() {
                @Override
                public void run() {
                    YdlBuryPointUtil.sendPv("PvEvent");
                }
            }, 300);
            jtv_test.postDelayed(new Runnable() {
                @Override
                public void run() {
                    YdlBuryPointUtil.sendClick("ClickEvent");
                }
            }, 500);
        }
    }

    @SuppressLint("CheckResult")
    private void clearCouponStatus() {
        MineHttpImpl.Companion.getInstance().getSysMsgList(new MsgListParam(1 + "", 1))
                .compose(RxUtils.netCheck())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response != null && response.code == 0) {
                        mNewCoupon.setVisibility(View.INVISIBLE);
                    }
                }, throwable -> {
                });
    }

    private void share() {
        YDLShareDialog dialog = YDLShareDialog.Companion.style4(getActivity(), share_title, share_url, share_context, share_head);
        dialog.show(getActivity().getFragmentManager(), "lose");
    }

    /**
     * 收到照片选取事件
     */
    public void onEventBackgroundThread(UserResponseBean event) {
        if (event != null && event.getUserInfo() != null) {
            userInfoData = event.getUserInfo();
        }
    }

    public void onEvent(RefreshRecentContactListEvent event) {
        refreshCouponData();
    }

    public void onEvent(UserChangeEvent event) {
        boolean change_flag = event.isChange_flag();
        if (change_flag) {
            initdata();
            try {
                ModularServiceManager.INSTANCE.provide(IImService.class).updateUserHead(UserHelper.INSTANCE.getUserInfo().getUserInfo().getHead());
            } catch (Exception e) {
            }
        }
    }
}