package com.yidianling.user.mine

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.core.content.ContextCompat
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
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.Companion.H5_URL
import com.ydl.ydlcommon.base.config.HttpConfig.Companion.MH5_URL
import com.ydl.ydlcommon.base.config.HttpConfig.Companion.YDL_H5
import com.ydl.ydlcommon.data.PlatformRamImpl
import com.ydl.ydlcommon.data.http.BaseCommand
import com.ydl.ydlcommon.data.http.BaseResponse
import com.ydl.ydlcommon.data.http.RxUtils.netCheck
import com.ydl.ydlcommon.data.http.RxUtils.resultJavaData
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.modular.ModularServiceManager.provide
import com.ydl.ydlcommon.utils.BuryPointUtils
import com.ydl.ydlcommon.utils.Utils
import com.ydl.ydlcommon.utils.YdlBuryPointUtil
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils.Companion.count
import com.ydl.ydlcommon.view.dialog.YDLShareDialog
import com.ydl.ydlcommon.view.dialog.YDLShareDialog.Companion.style4
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.getUserInfo
import com.yidianling.user.UserHelper.getUsetSetting
import com.yidianling.user.UserHelper.isLogin
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.constants.UserBIConstants.UserMyPageEvent
import com.yidianling.user.mine.bean.CouponNumBean
import com.yidianling.user.mine.data.AppDataManager.getHttp
import com.yidianling.user.mine.data.AppDataManager.getLocal
import com.yidianling.user.mine.http.MineHttpImpl
import com.yidianling.user.route.UserIn.getImService
import com.yidianling.user.safePrivate.PrivacyActivity
import com.yidianling.user.ui.login.OneKeyLoginHelp.startLoginByStatus
import de.greenrobot.event.EventBus
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.user_mine_fragment_mine.*
import java.util.*

/**
 * 我的Tab
 * Created by softrice on 15/11/23.
 */
class MineFragment : BaseFragment(), SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
    private var mActivity: Activity? = null
    var share_title = "壹点灵-专业心理咨询平台"
    var share_context = "帮您解决各种恋爱情感、婚姻、生活烦恼"
    var share_head = "http://static.ydlcdn.com/v1/images/logo320.png"
    var share_url = "http://m.yidianling.com/app"
    var userInfoData: UserResponseBean.UserInfo? = null
    private var mShareDialog: YDLShareDialog? = null
    private var startTime: Long = 0
    private var endTime: Long = 0
    override fun layoutResId(): Int {
        return R.layout.user_mine_fragment_mine
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mActivity = requireActivity()
    }

    override fun initDataAndEvent() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        swipe_refresh_layout?.setColorSchemeColors(
            ContextCompat.getColor(
                requireContext(),
                R.color.platform_main_theme
            )
        )
        swipe_refresh_layout.setProgressViewOffset(false, 0, 200)
        img_head.setOnClickListener(this)
        //debug包下切换环境的按钮
        btn_change.setOnClickListener(this)
        jtv_account_privacy.setOnClickListener(this)
        jtv_account_help.setOnClickListener(this)
        jtv_about_us.setOnClickListener(this)
        jtv_account_enter.setOnClickListener(this)
        cv_duration.setOnClickListener(this)
        text_userName.setOnClickListener(this)
        jtv_test.setOnClickListener(this)
        swipe_refresh_layout.setOnRefreshListener(this)
        rootView.findViewById<View>(R.id.csl_trade_order).setOnClickListener(this)
        rootView.findViewById<View>(R.id.jtv_introduce).setOnClickListener(this)
        rootView.findViewById<View>(R.id.iv_edit_info).setOnClickListener(this)
        //分享
        rootView.findViewById<View>(R.id.iv_share).setOnClickListener(this)
        rootView.findViewById<View>(R.id.ll_my_courses).setOnClickListener(this)
        rootView.findViewById<View>(R.id.ll_red_packet).setOnClickListener(this)
        rootView.findViewById<View>(R.id.csl_call_order).setOnClickListener(this)
        rootView.findViewById<View>(R.id.ll_account).setOnClickListener(this)
        rootView.findViewById<View>(R.id.ll_guanzhu).setOnClickListener(this)
        rootView.findViewById<View>(R.id.ll_my_trends).setOnClickListener(this)
        rootView.findViewById<View>(R.id.ll_fans).setOnClickListener(this)
        rootView.findViewById<View>(R.id.ll_my_test_log).setOnClickListener(this)
        //客服
        rootView.findViewById<View>(R.id.ll_service).setOnClickListener(this)
        //冥想
        rootView.findViewById<View>(R.id.ll_meditation).setOnClickListener(this)

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

        refreshCouponData()


    }

    override fun initDataAndEventLazy() {}
    fun init() {
        if (null != PlatformRamImpl.getInstance()
                .getGlobalInfo() && null != PlatformRamImpl.getInstance()
                .getGlobalInfo()?.info && null != PlatformRamImpl.getInstance()
                .getGlobalInfo()?.info?.app_share
        ) {
            share_title = PlatformRamImpl.getInstance().getGlobalInfo()?.info?.app_share?.title.toString()
            share_context = PlatformRamImpl.getInstance().getGlobalInfo()?.info?.app_share?.descrip.toString()
            share_head = PlatformRamImpl.getInstance().getGlobalInfo()?.info?.app_share?.cover_url.toString()
            share_url = PlatformRamImpl.getInstance().getGlobalInfo()?.info?.app_share?.dl_url.toString()
        }
    }

    override fun onResume() {
        super.onResume()
        updateUI()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser && isResumed) {
            startTime = System.currentTimeMillis()
            count(UserMyPageEvent.YDL_USER_MY_PAGE_VISIT)
            showConsultAssistantDialog()
        } else {
            if (startTime != 0L) {
                endTime = System.currentTimeMillis()
                count(UserMyPageEvent.YDL_USER_MY_PAGE_STAY_VISIT, (endTime - startTime).toString())
            }
        }
        if (isVisibleToUser && isResumed) {
            onResume()
        }
    }

    override fun onPause() {
        super.onPause()
        if (startTime != 0L) {
            endTime = System.currentTimeMillis()
            count(UserMyPageEvent.YDL_USER_MY_PAGE_STAY_VISIT, (endTime - startTime).toString())
        }
    }

    private fun showConsultAssistantDialog() {
        count("daoyi_advertisement_page|daoyi_advertisement_visit", "4")
    }

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

    override fun onRefresh() {
        updateUserInfo()
        refreshCouponData()
    }

    private fun getConfideOrder(uid: String) {
        MineHttpImpl.getInstance().getHasConfideOrder(uid)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ response ->
                if ("200" == response.code) {
                    if (response.data != null) {
                        if (response.data.listenOrder == true) {
                            iv_confide_tip.visibility = View.VISIBLE
                            getLocal().setConfide(true)
                        } else {
                            iv_confide_tip.visibility = View.GONE
                            getLocal().setConfide(false)
                        }

                        if (response.data.consultOrder == true) {
                            iv_order_tip.visibility = View.VISIBLE
                            getLocal().setConsult(true)
                        } else {
                            iv_order_tip.visibility = View.GONE
                            getLocal().setConsult(false)
                        }
                    }else{
                        getLocal().setConfide(false)
                        getLocal().setConsult(false)
                    }
                }else{
                    getLocal().setConfide(false)
                    getLocal().setConsult(false)
                }

            },{
                getLocal().setConfide(false)
                getLocal().setConsult(false)
            })
    }


    /**
     * 更新优惠券信息
     */
    @SuppressLint("CheckResult")
    private fun refreshCouponData() {
        getLocal().setCoupon(false)
        getLocal().setConfide(false)
        getLocal().setConsult(false)

        val userInfo = getUserInfo()

        userInfo?.uid?.let { uid ->
            getConfideOrder(uid)
            //获取用户信息
            MineHttpImpl.getInstance().getNewCoupon(BaseCommand())
                .compose(netCheck())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ response: BaseResponse<CouponNumBean> ->
                    if (response.data != null) {
                        if (response.data?.count ?: 0 > 0) {
                            view_new_coupon.visibility = View.VISIBLE
                            getLocal().setCoupon(true)
                        } else {
                            view_new_coupon.visibility = View.GONE
                            getLocal().setCoupon(false)
                        }
                    } else {
                        getLocal().setCoupon(false)
                    }
                }) { throwable: Throwable? ->
                    getLocal().setCoupon(false)
                }
        }
    }

    /**
     * 更新用户信息
     */
    @SuppressLint("CheckResult")
    private fun updateUserInfo() {
        val userInfo = getUserInfo()
        //获取用户信息
        if (userInfo == null) {
            swipe_refresh_layout.isRefreshing = false
            return
        }
        if (userInfo.uid == null || userInfo.accessToken == null) {
            swipe_refresh_layout.isRefreshing = false
            return
        }
        getHttp().getUserInfo()
            .compose(resultJavaData())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer { response: UserResponseBean ->
                swipe_refresh_layout.isRefreshing = false
                try {
                    //此处后端返回信息，只有userinfo，其它数据为空，切勿整体赋值
                    getUserInfo()?.userInfo = response.userInfo
                    updateUI()
                } catch (e: Exception) {
                }
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    swipe_refresh_layout.isRefreshing = false
                }
            })
    }

    /**
     * 获取用户信息成功后调用此方法更新 ui
     */
    fun updateUI() {
        initdata()
        if (getLocal().hasUpdate()) {
            jtv_about_us?.setLeftRedDotVisibility(View.VISIBLE)
        } else {
            jtv_about_us?.setLeftRedDotVisibility(View.GONE)
        }
        //切换环境按钮逻辑
        debugChangeEnvironment()
    }

    private fun initdata() {
        if (isLogin()) {
            setUserInfo(getUserInfo()?.userInfo)
        } else {
            text_userName?.text = "未登录"
            tv_duration?.text = "点击登录/注册"
            img_head?.setImageResource(R.drawable.platform_head_place_hold_pic)
            tv_attention_num?.text = "0"
            tv_trend_num?.text = "0"
            tv_fans_tv?.text = "0"
            tv_test_record_num?.text = "0"
            view_new_coupon?.visibility = View.INVISIBLE
        }
    }

    private fun setUserInfo(userInfo: UserResponseBean.UserInfo?) {
        userInfoData = userInfo
        if (userInfo == null) {
            return
        }
        val nick_name = userInfo.nick_name
        if (!TextUtils.isEmpty(nick_name)) {
            text_userName?.text = nick_name
        } else {
            text_userName?.text = "昵称未设置"
        }
        tv_attention_num?.text = userInfo.attentionNum.toString()
        tv_trend_num?.text = userInfo.trendNum.toString()
        tv_fans_tv?.text = userInfo.fansNum.toString()
        tv_test_record_num?.text = userInfo.testRecordNum.toString()
        tv_duration?.text = userInfo.registTime
        cv_duration?.visibility = View.VISIBLE
        if (userInfo.head != null) {
            GlideApp.with(this)
                .load(userInfo.head)
                .dontAnimate()
                .placeholder(R.drawable.platform_head_place_hold_pic)
                .error(R.drawable.platform_head_place_hold_pic)
                .into(img_head)
        }
    }

    override fun onClick(v: View) {
        val id = v.id //切换环境逻辑按钮
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        if (id == R.id.text_userName || id == R.id.cv_duration) {
            mActivity?.let { startLoginByStatus(it, true) }
        } else if (id == R.id.iv_edit_info) {
            //账号设置
            count(UserMyPageEvent.YDL_USER_MY_BOTTOM_TYPE_CLICK, "设置")
            //点击消息 未登录请先登录
            mActivity?.let { activity ->
                if (!startLoginByStatus(activity, true)) {
                    return
                }
                startActivity(Intent(activity, AccountSettingActivity::class.java))
            }
        } else if (id == R.id.img_head) { //头像
            mActivity?.let { activity ->
                if (!startLoginByStatus(activity, true)) {
                    return
                }
                count(UserMyPageEvent.YDL_USER_MY_TOP_TYPE_CLICK, "头像")
                if (userInfoData != null) {
                    val intentuser = Intent(activity, PersonalInfoActivity::class.java)
                    startActivity(intentuser)
                }
            }

        } else if (id == R.id.ll_account) { //账户余额
            count(UserMyPageEvent.YDL_USER_MY_MIDDLE_TYPE_CLICK, "账号余额")
            mActivity?.let { activity ->
                if (!startLoginByStatus(activity, true)) {
                    return
                }
                startActivity(Intent(activity, AccountHistoryActivity::class.java))
            }

        } else if (id == R.id.ll_red_packet) { //我的红包
            count(UserMyPageEvent.YDL_USER_MY_MIDDLE_TYPE_CLICK, "红包卡券")
            mActivity?.let { activity ->
                if (!startLoginByStatus(activity, true)) {
                    return
                }
                clearCouponStatus()
                provide(IAppService::class.java).myRedPockIntent(activity)
            }

        } else if (id == R.id.ll_fans) { //粉丝
            count(UserMyPageEvent.YDL_USER_MY_TOP_TYPE_CLICK, "我的粉丝")
            mActivity?.let { activity ->
                if (!startLoginByStatus(activity, true)) {
                    return
                }
                val h5Params = H5Params(H5_URL + "mine/fans-list", null)
                NewH5Activity.start(activity, h5Params)
            }

        } else if (id == R.id.ll_guanzhu) { //我关注的
            count(UserMyPageEvent.YDL_USER_MY_TOP_TYPE_CLICK, "我的关注")
            mActivity?.let { activity ->
                if (!startLoginByStatus(activity, true)) {
                    return
                }
                val h5Params1 = H5Params(H5_URL + "mine/follow-per", null)
                NewH5Activity.start(activity, h5Params1)
            }

        } else if (id == R.id.ll_my_trends) {
            count(UserMyPageEvent.YDL_USER_MY_TOP_TYPE_CLICK, "我的动态")
            mActivity?.let { activity ->
                if (!startLoginByStatus(activity, true)) {
                    return
                }
                BuryPointUtils.getInstance().createMap()
                    .put("mine_name", "我的动态")
                    .burryPoint("mine")
                try {
                    val intentm = provide(IDynamicService::class.java).getMyTrendsActivityIntent(activity)
                    startActivity(intentm)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

        } else if (id == R.id.jtv_account_privacy) { // 未登录请先登录
            count(UserMyPageEvent.YDL_USER_MY_BOTTOM_TYPE_CLICK, "帮助中心")
            mActivity?.let { activity ->
                if (!startLoginByStatus(activity, true)) {
                    return
                }
                getUsetSetting()?.meSafePrivateIsClick = true
                jtv_account_privacy?.setLeftRedDotVisibility(View.GONE)
                startActivity(Intent(activity, PrivacyActivity::class.java))
            }

        } else if (id == R.id.csl_trade_order) { //预约
            count(UserMyPageEvent.YDL_USER_MY_MIDDLE_TYPE_CLICK, "预约订单")
            mActivity?.let { activity ->
                if (!startLoginByStatus(activity, true)) {
                    return
                }
                BuryPointUtils.getInstance().createMap()
                    .put("mine_name", "预约订单")
                    .burryPoint("mine")
                val h5Params3 = H5Params(MH5_URL + "wb/user/order/list?needOrderHelperAlert=1", null)
                NewH5Activity.start(activity, h5Params3)
            }

        } else if (id == R.id.ll_my_courses) { //我的课程
            count(UserMyPageEvent.YDL_USER_MY_MIDDLE_TYPE_CLICK, "我的课程")
            mActivity?.let { activity ->
                if (!startLoginByStatus(activity, true)) {
                    return
                }
                provide(ICourseService::class.java).startMyCourseActivity(activity)
            }

        } else if (id == R.id.csl_call_order) { //倾诉
            count(UserMyPageEvent.YDL_USER_MY_MIDDLE_TYPE_CLICK, "倾诉记录")
            mActivity?.let { activity ->
                if (!startLoginByStatus(activity, true)) {
                    return
                }
                BuryPointUtils.getInstance().createMap()
                    .put("mine_name", "倾诉记录")
                    .burryPoint("mine")
                val h5Paramsqing = H5Params(YDL_H5 + "confideOrderList", null)
                NewH5Activity.start(activity, h5Paramsqing)
            }

        } else if (id == R.id.jtv_account_help) { //帮助
            count(UserMyPageEvent.YDL_USER_MY_BOTTOM_TYPE_CLICK, "帮助中心")
            val params = H5Params(H5_URL + "help/", "")
            params.isShowMenu = true
            NewH5Activity.start(activity, params)
        } else if (id == R.id.jtv_account_enter) { //专家入驻
            count(UserMyPageEvent.YDL_USER_MY_BOTTOM_TYPE_CLICK, "专家入驻")
            var joinDoctorUrl = PlatformRamImpl.getInstance().getGlobalInfo()?.info?.join_doctor_url
            if (joinDoctorUrl.isNullOrEmpty()) {
                joinDoctorUrl = "http://m.yidianling.com/enter?"
            }
            val h5Paramzhuan = H5Params(joinDoctorUrl, null)
            NewH5Activity.start(activity, h5Paramzhuan)
        } else if (id == R.id.ll_my_test_log) { //测试记录
            count(UserMyPageEvent.YDL_USER_MY_TOP_TYPE_CLICK, "测试记录")
            mActivity?.let { activity ->
                if (!startLoginByStatus(activity, true)) {
                    return
                }
                BuryPointUtils.getInstance().createMap()
                    .put("mine_name", "测试记录")
                    .burryPoint("mine")
                val testParam = H5Params(MH5_URL + "ceshi/my-test", "测试记录")
                NewH5Activity.start(activity, testParam)
            }

        } else if (id == R.id.iv_share) { //分享
            count(UserMyPageEvent.YDL_USER_MY_BOTTOM_TYPE_CLICK, "分享")
            share()
        } else if (id == R.id.jtv_about_us) {
            startActivity(Intent(activity, AboutUsActivity::class.java))
        } else if (id == R.id.ll_service) {
            mActivity?.let { activity ->
                if (!startLoginByStatus(activity, true)) {
                    return
                }
                getImService().startP2PXiaoYi(activity)
            }

        } else if (id == R.id.jtv_introduce) {
            count(UserMyPageEvent.YDL_USER_MY_BOTTOM_TYPE_CLICK, "壹点灵介绍")
            val params1 = H5Params("https://m.yidianling.com/about", "网站介绍")
            NewH5Activity.start(activity, params1)
        } else if (id == R.id.btn_change) {
        } else if (id == R.id.jtv_test) { //debug下任意门入口
            jtv_test?.postDelayed({ YdlBuryPointUtil.sendPv("PvEvent") }, 300)
            jtv_test?.postDelayed({ YdlBuryPointUtil.sendClick("ClickEvent") }, 500)
        } else if (id == R.id.ll_meditation) { //冥想
            count(UserMyPageEvent.YDL_USER_MY_MIDDLE_TYPE_CLICK, "冥想")
            mActivity?.let {
                if (!startLoginByStatus(it, true)) {
                    return
                }
                val h5Params3 = H5Params(MH5_URL + "meditation/list?hideNavBar=1", null)
                NewH5Activity.start(it, h5Params3)
            }

        }
    }

    @SuppressLint("CheckResult")
    private fun clearCouponStatus() {
        MineHttpImpl.getInstance().getSysMsgList(MsgListParam(1.toString() + "", 1))
            .compose(netCheck())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ response: BaseResponse<String>? ->
                if (response != null && response.code == 0) {
                    view_new_coupon.visibility = View.INVISIBLE
                }
            }) { throwable: Throwable? -> }
    }

    private fun share() {
        if (mShareDialog  == null) {
            mShareDialog = mActivity?.let { activity ->
                style4(activity, share_title, share_url, share_context, share_head)
            }
        }
        mShareDialog?.show(activity?.fragmentManager, "lose")
    }

    /**
     * 收到照片选取事件
     */
    fun onEventBackgroundThread(event: UserResponseBean?) {
        if (event?.userInfo != null) {
            userInfoData = event.userInfo
        }
    }

    fun onEvent(event: RefreshRecentContactListEvent?) {
        refreshCouponData()
    }

    fun onEvent(event: UserChangeEvent) {
        val changeFlag = event.isChange_flag
        if (changeFlag) {
            initdata()
            try {
                provide(
                    IImService::class.java
                ).updateUserHead(getUserInfo()?.userInfo?.head)
            } catch (e: Exception) {
            }
        }
    }
}