package com.yidianling.home.ui.fragment

import android.app.Dialog
import android.os.Build
import android.support.design.widget.CollapsingToolbarLayout
import android.support.design.widget.CoordinatorLayout
import android.support.v4.content.ContextCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import android.widget.RelativeLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_image.module.GlideApp
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydlcommon.base.BaseMvpFragment
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.data.http.BaseResponse
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.utils.*
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.ydl.ydlcommon.view.banner.GlideImageLoader
import com.yidianling.consultant.api.IConsultantService
import com.yidianling.home.R
import com.yidianling.home.adapter.YdlHomeAdapter
import com.yidianling.home.constract.IHomeContract
import com.yidianling.home.constract.YdlHomeViewHolderConstract
import com.yidianling.home.dialog.ActivityDialog
import com.yidianling.home.dialog.ActivityGuideDialog
import com.yidianling.home.event.HomeImpl
import com.yidianling.home.listener.HomeConfideRecyleSuspendListener
import com.yidianling.home.model.bean.*
import com.yidianling.home.presenter.HomePresenterImpl
import com.yidianling.home.ui.view.CouponDialog
import com.yidianling.im.api.service.IImService
import com.yidianling.user.api.service.IUserService
import kotlinx.android.synthetic.xlzx.home_fragment_home_module.*
import kotlinx.android.synthetic.xlzx.home_layout_home_module_content.*
import kotlinx.android.synthetic.xlzx.home_layout_home_module_input.*


/**
 * @author <a href="https://www.jianshu.com/u/c1e5310dd724">xujian</a>
 * @描述: 壹点灵首页fragment
 * @Copyright Copyright (c) 2019
 * @Company 壹点灵
 * @date 2019/02/12
 */
@Route(path = "/home/home")
class YdlHomeFragment : BaseMvpFragment<IHomeContract.View, HomePresenterImpl>(),
    IHomeContract.View,
    SwipeRefreshLayout.OnRefreshListener {


    private var adapter: YdlHomeAdapter? = null
    private var homeEvent: HomeImpl? = null
    private var dialog: CouponDialog? = null

    //双11活动弹窗
    private var aa: Dialog? = null

    /**
     * tablayou上次选中的tab下标
     */
    private var confideLastSelectPosition = 0
    private var confideLastSelectType = ""
    /**
     * 咨询tablayout上次选中的西边
     */
    private var consultLastSelectPosition = 0
    private var consultLastSelectType= ""
    /**
     * 悬浮tablayout监听事件
     */
    private var scrollListner: HomeConfideRecyleSuspendListener? = null

    /**
     * 如果是第一次加载，则调用所有接口进行刷新，否则，只调用咨询和倾诉接口
     */
    private var isFromCreate: Boolean = true

    override fun layoutResId(): Int {
        return R.layout.home_fragment_home_module
    }

    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(isAddStatusView = true, statusBarDarkMode = true)
    }

    override fun initDataAndEvent() {
        homeEvent = HomeImpl(activity, this)
        initView()
        initAdapter()
    }

    private fun initAdapter() {
        mPresenter?.localHomeData(this.context, "home_data_xlzx.json")
        adapter = YdlHomeAdapter(context, homeEvent!!, ArrayList())
        val layoutManager = LinearLayoutManager(context)
        home_module_fragment_recycler.layoutManager = layoutManager
        home_module_fragment_recycler.adapter = adapter

        scrollListner = HomeConfideRecyleSuspendListener()
        home_module_fragment_recycler.addOnScrollListener(scrollListner)
    }

    private fun initView() {


        home_swipe_refresh_layout.setOnRefreshListener(this)
        home_swipe_refresh_layout.setColorSchemeColors(
            ContextCompat.getColor(
                context,
                R.color.platform_main_theme
            )
        )
        home_swipe_refresh_layout.setProgressViewOffset(false, 0, 200)
        home_swipe_refresh_layout.isEnabled = true
        etSearch.setOnClickListener { homeEvent?.searchTvClick("") }

        home_page_xiaoyi.setOnClickListener {
            activity?.let {
                ModularServiceManager.provide(IImService::class.java).startP2PXiaoYi(activity)
            }
        }

//        val inputLayoutParams = ll_search.layoutParams as CoordinatorLayout.LayoutParams
//        val inputOriginMargin = inputLayoutParams.leftMargin
//        var inputOffset = DisplayUtils.dp2px(context, 20).toFloat()
//
//        appbar_layout.addOnOffsetChangedListener { appBarLayout, i ->
//            home_swipe_refresh_layout.isEnabled = i >= 0
//
//            val scale = java.lang.Float.valueOf(Math.abs(i).toFloat())!! / java.lang.Float.valueOf(
//                appBarLayout.totalScrollRange.toFloat()
//            )!!
//            view_search_toolbar_bg.alpha = scale
//            val leftMargin = inputOriginMargin - inputOffset * scale
//            val rightMargin = inputOriginMargin - inputOffset * scale
//            inputLayoutParams.setMargins(leftMargin.toInt(), 0, rightMargin.toInt(), 0)
//            ll_search.layoutParams = inputLayoutParams
//            val zheZhaoAlpha = ((1 - (0.2 * scale)).toFloat())
//            //以下判断是因为toolbar和遮罩层拦截住了点击事件，导致banner不好点击
//            if (zheZhaoAlpha == 1f) {
//                title_layout.visibility = View.GONE
//                toolbar.visibility = View.GONE
//            } else {
//                title_layout.visibility = View.VISIBLE
//                toolbar.visibility = View.VISIBLE
//            }
//            view_search_input_bg.alpha = zheZhaoAlpha
//        }
//        initStatus()

    }

    /**
     * 初始化状态栏位置
     */
//    private fun initStatus() {
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4以下不支持状态栏变色
//            val statusBarHeight = StatusBarUtils.getStatusBarHeight(activity)
//            var homeTitleBarHeight = resources.getDimension(R.dimen.home_home_title_bar_height)
//            val lp1 = view_search_toolbar_bg.layoutParams as RelativeLayout.LayoutParams
//            lp1.height = (homeTitleBarHeight + statusBarHeight).toInt()
//            view_search_toolbar_bg.layoutParams = lp1
//
//            val lp2 = toolbar.layoutParams as CollapsingToolbarLayout.LayoutParams
//            lp2.topMargin = statusBarHeight
//            toolbar.layoutParams = lp2
//        }
//    }

    override fun initDataAndEventLazy() {
    }

    override fun createPresenter(): HomePresenterImpl {
        return HomePresenterImpl()
    }

    override fun onRefresh() {
        home_swipe_refresh_layout.isRefreshing = true
        mPresenter?.refreshHomeData()
    }

    override fun resetModuleTabPosition() {
        adapter?.confideSelectPosition = 0
        adapter?.consultSelectPosition = 0
    }

    /**
     * 获取倾述列表数据
     * @param type 倾述类型
     * @param selectPosition 选中的position
     */
    override fun getConfideData(type: String, selectPosition: Int) {
        confideLastSelectPosition = selectPosition
        confideLastSelectType = type
        mPresenter?.getConfideData(type, selectPosition)
    }

    override fun getConsultData(type: String, selectPosition: Int) {
        consultLastSelectPosition = selectPosition
        consultLastSelectType = type
        mPresenter?.getConsultData(type, selectPosition)
    }

    override fun homeHeadResponse(homeHeaderBean: HomeHeaderBean) {
        //展示活动数据
        val act = homeHeaderBean.activityResponse

        if (act != null) {
            if (!TextUtils.isEmpty(act.imageUrl)) {
                img_ad.visibility = View.VISIBLE
                img_ad_card.visibility = View.VISIBLE
                GlideApp.with(this).load(act.imageUrl).into(img_ad)
                img_ad.setOnClickListener {
                    if (Utils.isFastClick()) {
                        //防止连击
                        return@setOnClickListener
                    }
                    if (act.btnLinkurl != null && act.btnLinkurl!!.startsWith("http")) {
                        NewH5Activity.start(activity, H5Params(act.btnLinkurl!!, null))
                    } else {
                        YDLRouterManager.router(act.btnLinkurl)
                    }
                }
            } else {
                img_ad.visibility = View.GONE
                img_ad_card.visibility = View.GONE
            }
            if (!TextUtils.isEmpty(act.imageBanner)) {
                val va = SharedPreferencesEditor.getString(act.imageBanner)
                if (TextUtils.equals("yes", va)) {
                    //已经显示过，不再弹出
                    return
                }
            }

            if (!ModularServiceManager.provide(IUserService::class.java).isLogin()||!ModularServiceManager.provide(IUserService::class.java).isFirstLogin()) {
                //未登录/首次登录 不显示
                return
            }

            if (!TextUtils.isEmpty(act.imageBanner)) {
                //展示弹窗
                if (aa == null) {
                    aa = ActivityDialog(activity, act.imageBanner, act.linkUrl, act.title)
                    aa?.show()
                    aa?.setOnDismissListener {
                        if (!TextUtils.isEmpty(act.title)) {
                            img_ad.post {
                                val heig = StatusBarUtils.getStatusBarHeight(context)
                                var location = IntArray(2)
                                img_ad.getLocationInWindow(location)
                                ActivityGuideDialog(
                                    activity,
                                    act.imageUrl,
                                    act.title,
                                    location[1] - heig,
                                    location[0]
                                ).show()
                            }
                        }
                    }
                }
                //仅展示一次，以后不再展示
                SharedPreferencesEditor.putString(act.imageBanner, "yes")
            }
        }
    }

    override fun homeDataResponse(list: MutableList<HomePagerDataBean>) {
        home_swipe_refresh_layout.isRefreshing = false
        //更新首页数据
        if (list.size > 0) {
            list[0].type = YdlHomeViewHolderConstract.HOME_IMAGE_BANNER
        }
        adapter?.updateItems(list)
        //每次全局更新后重置下标位
        confideLastSelectPosition = 0
        consultLastSelectPosition = 0

        for (bean in list) {
            //咨询模块
            if (bean.type == YdlHomeViewHolderConstract.BUTTON_BANNER_VIEW) {
                consultLastSelectType = bean.headerBean!!.consultCategoryData!![0].id.toString()
            }
        }
    }

    override fun confideDataResponse(data: HomeConfideBean, selectPosition: Int) {
        //更新倾述列表数据
        adapter?.updateConfideData(data, selectPosition)
    }

    override fun consultDataResponse(data: HomeConsultBean, selectPosition: Int) {
        //更新咨询列表数据
        adapter?.updateConsultData(data, selectPosition)
    }

    override fun askDataResponse(data: HomeAskBean, position: Int) {
        //更新问答模块数据
        adapter?.updateAskData(data, position)
    }

    override fun homeDataFail(msg: String) {
        if (home_swipe_refresh_layout != null) {
            home_swipe_refresh_layout.isRefreshing = false
        }
        if (!TextUtils.isEmpty(msg)){
            ToastHelper.show(msg)
        }
    }

    override fun couponDataResponse(data: List<CouponBean>) {
        showCouponDialog(data)
    }

    private fun showCouponDialog(data: List<CouponBean>) {
        if (dialog == null) {
            dialog = CouponDialog(activity, data, homeEvent?.clickEnsure(data))
        }

        if (!dialog!!.isShowing) {
            dialog?.show()
        }

    }

    override fun receiveCoupon(data: List<CouponBean>) {
        mPresenter?.receiveCoupon(data)
    }

    override fun receiveCouponResponse(data: BaseResponse<Any>) {
        if (data.code == 200) {
            dialog?.updateStatus(CouponDialog.STATUS_GET)
        } else {
            ToastHelper.show(data.msg)
        }
    }

    override fun askZan(position: Int, index: Int, id: String) {
        mPresenter?.askZan(position, index, id)
    }

    override fun askFocus(position: Int, id: String) {
        mPresenter?.askFocus(position, id)
    }

    override fun showHomeProgress() {
        showHomeProgress()
    }

    override fun showRefreshLayout() {
        home_swipe_refresh_layout.isRefreshing = true
    }

    override fun dismissHomeProgress() {
        dismissHomeProgress()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser && isResumed) {
            showConsultAssistantDialog()
        } else {
            hideConsultAssistantDialog()
        }
        if (isVisibleToUser && isResumed) {
            onResume()
        }
    }

    private fun showConsultAssistantDialog() {
        ModularServiceManager.provide(IConsultantService::class.java)
            .showConsultAssistantDialog(activity)
    }

    private fun hideConsultAssistantDialog() {
        ModularServiceManager.provide(IConsultantService::class.java).hideConsultAssistantDialog()
    }

    override fun onResume() {
        super.onResume()
        if (userVisibleHint) {

            if (isFromCreate) {
                isFromCreate = false
                mPresenter?.loadHomeData()
            }else {
                mPresenter?.getConsultData(consultLastSelectType, consultLastSelectPosition)
                mPresenter?.getConfideData(confideLastSelectType, confideLastSelectPosition)

            }
            mPresenter?.prepareCoupon(activity)

            //走咨询助理浮层展示逻辑，是否展示由内部条件与接口判断
            showConsultAssistantDialog()
        }
    }
}