package com.ydl.confide.home.util

import android.content.Context
import androidx.core.content.ContextCompat
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.view.View
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import com.ydl.confide.R
import com.ydl.confide.home.adapter.ConfideHomeAdapter
import com.ydl.confide.home.bean.ConfideHomeAllFiltersBean
import com.ydl.confide.home.bean.ConfideHomeBodyBean
import com.ydl.confide.home.bean.ConfideHomeDataBean
import com.ydl.confide.home.config.IConfideHomeConfig
import com.ydl.confide.home.contract.IConfideHomeContract
import com.ydl.confide.home.event.IConfideHomeEvent
import com.ydl.confide.home.http.ConfideRecommendParam
import com.ydl.confide.home.listener.ConfideHomeRecycleViewListener
import com.ydl.confide.home.section.*
import com.ydl.confide.home.widget.ConfideHomeFilterView
import com.ydl.confide.home.widget.ConfidePlayerFloatView
import com.ydl.confide.router.PhoneCallIn
import com.ydl.ydlcommon.adapter.section.SectionAdapter
import com.yidianling.common.tools.LogUtil
import java.io.BufferedInputStream
import java.io.IOException
import java.io.InputStream

/**
 * @author yuanwai
 * @描述:倾诉首页工具类
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/8/10
 */
class ConfideHomeUtils {
    companion object {
        /**
         * 读取Assets下文本文件
         */
        fun getAssertsFile(context: Context, fileName: String): ByteArray? {
            var inputStream: InputStream? = null
            val assetManager = context.assets
            try {
                inputStream = assetManager.open(fileName)
                if (inputStream == null) {
                    return null
                }

                var bis: BufferedInputStream? = null
                val length: Int
                try {
                    bis = BufferedInputStream(inputStream)
                    length = bis.available()
                    val data = ByteArray(length)
                    bis.read(data)

                    return data
                } catch (e: IOException) {

                } finally {
                    if (bis != null) {
                        try {
                            bis.close()
                        } catch (e: Exception) {

                        }
                    }
                }

                return null
            } catch (e: IOException) {
                e.printStackTrace()
            }

            return null
        }

        /**
         * 数据重组
         */
        fun resetData(list: MutableList<ConfideHomeDataBean>, filterView: ConfideHomeFilterView, listScrollListener: ConfideHomeRecycleViewListener) {
            val recommendList: MutableList<ConfideHomeDataBean> = ArrayList()
            var soundDataBean: ConfideHomeDataBean? = null
            for ((index, dataBean) in list.withIndex().reversed()) {
                //给隐藏的为你推荐筛选view赋值
                if (dataBean.type == IConfideHomeConfig.TYPE_RECOMMEND_FILTER) {
                    listScrollListener.setFilterIndex(index)
                    filterView.initData(dataBean)
                }
                //拆分为你推荐数据
                if (dataBean.type == IConfideHomeConfig.TYPE_RECOMMEND) {
                    //如果是为你推荐数据 则进行筛分
                    recommendList.addAll(getRecommendList(dataBean))
                    //移除当前 为你推荐数据
                    list.removeAt(index)
                }
                //移除听声寻人数据 放在最后
                if (dataBean.type == IConfideHomeConfig.TYPE_SOUND) {
                    soundDataBean = ConfideHomeDataBean(dataBean.type, dataBean.body, dataBean.head, dataBean.footer, dataBean.recommendId, dataBean.diviLine)
                    list.removeAt(index)
                }
            }
            //添加 拆分后的 为你推荐数据
            list.addAll(recommendList)
            //添加 听声寻人 数据
            if (null != soundDataBean) {
                list.add(soundDataBean)
            }
        }

        /**
         * 筛分 为你推荐数据 并返回集合
         */
        fun getRecommendList(dataBean: ConfideHomeDataBean): MutableList<ConfideHomeDataBean> {
            var list: MutableList<ConfideHomeDataBean> = ArrayList()
            if (null == dataBean || null == dataBean.body || dataBean.body.isEmpty()) {
                return list
            }
            for (bodyBean in dataBean.body) {
                val bodyList: MutableList<ConfideHomeBodyBean> = ArrayList()
                bodyList.add(bodyBean)
                val recommendDataBean = ConfideHomeDataBean(dataBean.type, bodyList, dataBean.head, dataBean.footer, dataBean.recommendId, dataBean.diviLine)
                list.add(recommendDataBean)
            }
            return list
        }

        /**
         * 构建section适配器数据
         * @param context 上下文
         * @param view confideHomeActivity view层接口
         * @param list 数据集合
         * @param mConfideAdapter section适配器
         * @param mConfideEvent 首页点击事件处理类
         */
        fun createScetion(context: Context, view: IConfideHomeContract.View, list: List<ConfideHomeDataBean>, mConfideAdapter: SectionAdapter, mConfideEvent: IConfideHomeEvent, filterView: ConfideHomeFilterView, listScrollListener: ConfideHomeRecycleViewListener) {
            for ((index, resultBean) in list.withIndex()) {
                //给隐藏的为你推荐筛选view赋值
                if (resultBean.type == IConfideHomeConfig.TYPE_RECOMMEND_FILTER) {
                    listScrollListener.setFilterIndex(index)
                    filterView.initData(resultBean)
                }
                createScetion(context, view, resultBean, mConfideAdapter, mConfideEvent)
            }
        }

        /**
         * 构建section适配器数据
         * @param context 上下文
         * @param view confideHomeActivity view层接口
         * @param resultBean 数据
         * @param mConfideAdapter section适配器
         * @param mConfideEvent 首页点击事件处理类
         */
        fun createScetion(context: Context, view: IConfideHomeContract.View, resultBean: ConfideHomeDataBean?, mConfideAdapter: SectionAdapter, mConfideEvent: IConfideHomeEvent) {
            if (null == resultBean) {
                return
            }
            when (resultBean!!.type) {
                //banner
                IConfideHomeConfig.TYPE_BANNER -> {
                    var section = ConfideHomeBannerSection(context, mConfideEvent)
                    section.setData(resultBean)
                    mConfideAdapter?.addSection(section)
                }
                //分类
                IConfideHomeConfig.TYPE_CATEGORY -> {
                    var section = ConfideHomeCategorySection(context, mConfideEvent, view)
                    section.setData(resultBean)
                    mConfideAdapter?.addSection(section)
                }
                //最佳倾诉榜单 todo 产品说先隐藏掉
                IConfideHomeConfig.TYPE_CONSULTANT -> {
//                    var section = ConfideHomeRecommendExpertSection(context,mConfideEvent)
//                    section.setData(resultBean)
//                    mConfideAdapter?.addSection(section)
                }
                //为你推荐筛选模块
                IConfideHomeConfig.TYPE_RECOMMEND_FILTER -> {
                    var section = ConfideHomeFilterSection(context, view)
                    section.setData(resultBean)
                    mConfideAdapter?.addSection(section)
                }
                //最近倾诉
                IConfideHomeConfig.TYPE_RECENTLY_CONFIDED -> {
                    var section = ConfideHomeRecentConfideSection(context, mConfideEvent)
                    section.setData(resultBean)
                    mConfideAdapter?.addSection(section)
                }
                //为你推荐
                IConfideHomeConfig.TYPE_RECOMMEND -> {
                    var section = ConfideRecommendSection(context, view, mConfideEvent)
                    section.setData(resultBean)
                    mConfideAdapter?.addSection(section)
                }
                //听声寻人
                IConfideHomeConfig.TYPE_SOUND -> {
                    var section = ConfideHomeListenAndFoundSection(context, view, mConfideEvent)
                    section.setData(resultBean)
                    mConfideAdapter?.addSection(section)
                }
            }
        }

        /**
         * 更新section适配器数据（用于点击某个模块的播放或暂停按钮，重置了各模块的播放状态字段）
         * @param list 数据集合
         * @param mConfideAdapter section适配器
         */
        fun updateSection(list: List<ConfideHomeDataBean>, mConfideAdapter: SectionAdapter) {
            //banner 数据bean
            var bannerData: ConfideHomeDataBean? = null
            //分类 数据bean
            var categoryData: ConfideHomeDataBean? = null
            //最近倾诉 数据bean
            var recentData: ConfideHomeDataBean? = null
            //为你推荐筛选模块 数据bean
            var recommendFilterData: ConfideHomeDataBean? = null
            //为你推荐 数据bean
            var recommendData: ConfideHomeDataBean? = null
            //听声寻人 数据bean
            var listenAndFoundData: ConfideHomeDataBean? = null
            //最佳倾听榜单 数据bean
            var recommendExpertData: ConfideHomeDataBean? = null

            for (resultBean in list) {
                when (resultBean.type) {
                    //banner
                    IConfideHomeConfig.TYPE_BANNER -> {
                        bannerData = resultBean
                    }
                    //最近倾诉
                    IConfideHomeConfig.TYPE_RECENTLY_CONFIDED -> {
                        recentData = resultBean
                    }
                    //分类测评
                    IConfideHomeConfig.TYPE_CATEGORY -> {
                        categoryData = resultBean
                    }
                    //为你推荐筛选模块数据
                    IConfideHomeConfig.TYPE_RECOMMEND_FILTER -> {
                        recommendFilterData = resultBean
                    }
                    //为你推荐
                    IConfideHomeConfig.TYPE_RECOMMEND -> {
                        recommendData = resultBean
                    }
                    //听声寻人
                    IConfideHomeConfig.TYPE_SOUND -> {
                        listenAndFoundData = resultBean
                    }
                    //最佳倾听榜单
                    IConfideHomeConfig.TYPE_CONSULTANT -> {
                        recommendExpertData = resultBean
                    }
                }
            }

            for (section in mConfideAdapter.getmSections()) {
                when (section) {
                    is ConfideHomeBannerSection -> {
                        //banner
                        section.setData(bannerData!!)
                    }
                    is ConfideHomeRecentConfideSection -> {
                        //最近倾诉
                        section.setData(recentData!!)
                    }
                    is ConfideHomeCategorySection -> {
                        //分类倾诉
                        section.setData(categoryData!!)
                    }
                    is ConfideHomeFilterSection -> {
                        //为你推荐筛选模块
                        section.setData(recommendFilterData!!)
                    }
                    is ConfideRecommendSection -> {
                        //为你推荐
                        section.setData(recommendData!!)
                    }
                    is ConfideHomeListenAndFoundSection -> {
                        //听声寻人
                        section.setData(listenAndFoundData!!)
                    }
                    is ConfideHomeRecommendExpertSection -> {
                        //最佳倾听榜单
                        section.setData(recommendExpertData!!)
                    }
                }
            }
        }

        /**
         * 移除为你推荐和听声寻人section
         */
        fun removeRecommendAndSoundSection(mConfideAdapter: SectionAdapter) {
            for (index in (0..(mConfideAdapter.getmSections().size - 1)).reversed()) {
                if (mConfideAdapter.getmSections()[index] is ConfideRecommendSection) {
                    //移除为你推荐section
                    mConfideAdapter.getmSections().removeAt(index)
                } else if (mConfideAdapter.getmSections()[index] is ConfideHomeListenAndFoundSection) {
                    //移除听声寻人section
                    mConfideAdapter.getmSections().removeAt(index)
                }
            }
        }

        /**
         * 同步筛选栏样式状态（因为筛选栏有两个 一个是列表中的，一个是顶部隐藏的）
         */
        fun synchroStyle(context: Context, type: Int, status: Int, filterView: ConfideHomeFilterView, mConfideAdapter: ConfideHomeAdapter) {
            //设置悬浮隐藏的筛选栏样式
            var view = filterView.getTextViewByType(type)
            if (null != view) {
                updateOthersTextStyle(context, view, status)
            }
            //设置列表中的筛选栏样式
            if (null != mConfideAdapter.getFilterViewHolder() && null != mConfideAdapter.getFilterViewHolder()!!.filterView) {
                var list_filterView = mConfideAdapter.getFilterViewHolder()!!.filterView.getTextViewByType(type)
                if (null != list_filterView) {
                    updateOthersTextStyle(context, list_filterView, status)
                }
            }
        }

        /**
         * 同步筛选栏样式状态（因为筛选栏有两个 一个是列表中的，一个是顶部隐藏的）
         */
        fun synchroTextColor(context: Context, type: Int, status: Int, filterView: ConfideHomeFilterView, mConfideAdapter: ConfideHomeAdapter) {
            //设置悬浮隐藏的筛选栏样式
            var view = filterView.getTextViewByType(type)
            if (null != view) {
                updateOthersTextColor(context, view, status)
            }
            //设置列表中的筛选栏样式
            //为你推荐筛选模块
            if (null != mConfideAdapter.getFilterViewHolder() && null != mConfideAdapter.getFilterViewHolder()!!.filterView) {
                var list_filterView = mConfideAdapter.getFilterViewHolder()!!.filterView.getTextViewByType(type)
                if (null != list_filterView) {
                    updateOthersTextColor(context, list_filterView, status)
                }
            }
        }

        /**
         * 同步筛选栏样式状态（因为筛选栏有两个 一个是列表中的，一个是顶部隐藏的）
         */
        fun synchroTextDrawable(mContext: Context, type: Int, status: Int, filterView: ConfideHomeFilterView, mConfideAdapter: ConfideHomeAdapter) {
            //设置悬浮隐藏的筛选栏样式
            var view = filterView.getTextViewByType(type)
            if (null != view) {
                updateOthersTextDrawable(mContext, view, status)
            }
            //设置列表中的筛选栏样式
            //为你推荐筛选模块
            if (null != mConfideAdapter.getFilterViewHolder() && null != mConfideAdapter.getFilterViewHolder()!!.filterView) {
                var list_filterView = mConfideAdapter.getFilterViewHolder()!!.filterView.getTextViewByType(type)
                if (null != list_filterView) {
                    updateOthersTextDrawable(mContext, list_filterView, status)
                }
            }
        }

        /**
         * 获取滑动的距离
         */
        fun getScollYDistance(recyclerview: RecyclerView): Int {
            val layoutManager = recyclerview.layoutManager as LinearLayoutManager
            val position = layoutManager.findFirstVisibleItemPosition()
            val firstVisiableChildView = layoutManager.findViewByPosition(position)
            val itemHeight = firstVisiableChildView!!.height
            var yDistance = position * itemHeight - firstVisiableChildView.top
            if (yDistance <= 50 && position > 1) {
                //position滑动到2和3之间的时候 滑动距离 会变成 小于10的距离
                //先这样解决吧
                return 200
            }
            return yDistance
        }

        /**
         * 跳转个人中心
         */
        fun buildJumpMine(context: Context) {
//            val intent = Intent()
//            intent.putExtra(MainUtils.ACTION_TAG, MainUtils.JUMP_MAIN_TAB_CHANGE)
//            intent.putExtra(MainUtils.MAIN_TAB_INDEX, 4)
//            intent.setClassName(context, "com.cxzapp.yidianling.MainActivity")
//            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
//            context.startActivity(intent)

            PhoneCallIn.getAppService().mainIntent(context,4,false)
        }

        /**
         * 根据点击播放的位置，重置所有数据播放状态
         * @param cacheList 缓存数据
         * @param type 点击的数据类型
         * @param index 一级数据索引
         * @param recommendId 为你推荐区域Id 用于区分播放的区域 因为为你推荐是多个section
         */
        fun changeCacheDataPlay(cacheList: MutableList<ConfideHomeDataBean>?, type: Int?, index: Int?, recommendId: Int?) {
            if (null == cacheList) {
                return
            }
            for ((itemIndex, item) in cacheList!!.withIndex()) {
                if (null == item) {
                    break
                }
                //循环查找点击的类型
                if (item.type == type) {
                    if (type == IConfideHomeConfig.TYPE_RECOMMEND && null != item.body && !item.body.isEmpty()) {
                        // 为你推荐
                        // 当ID匹配的时候 在去查找对应的索引位置
                        if (item.recommendId == recommendId) {
                            item.body[0].confideIsPlay = itemIndex == index
                        } else {
                            item.body[0].confideIsPlay = false
                        }
                    } else {
                        for ((i, bodyItem) in item.body!!.withIndex()) {
                            bodyItem.confideIsPlay = index == i
                        }
                    }
                } else {
                    for (bodyItem in item.body!!) {
                        bodyItem.confideIsPlay = false
                    }
                }
            }
        }

        /**
         * 更新播放状态
         */
        fun updateFMStatu(mPlayerFloatView: ConfidePlayerFloatView, isPlaying: Boolean) {
            if (null == mPlayerFloatView) {
                return
            }
            if (isPlaying) {
                mPlayerFloatView.visibility = View.VISIBLE
            } else {
                mPlayerFloatView.visibility = View.GONE
            }
            mPlayerFloatView.updatePlayState(isPlaying)
        }

        //更改筛选选项的按钮 文字颜色和图标
        private fun updateOthersTextStyle(mContext: Context, tv: AppCompatTextView, status: Int) {
            LogUtil.e("http-----------------updateOthersTextStyle")
            when (status) {
                IConfideHomeConfig.FILTER_STATUS_NORMAL -> {
                    tv.setTextColor(ContextCompat.getColor(mContext, R.color._6))
                    tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.platform_arrow_drop_down_un, 0)
                }
                IConfideHomeConfig.FILTER_STATUS_FILTERED, IConfideHomeConfig.FILTER_STATUS_OPEN -> {
                    tv.setTextColor(ContextCompat.getColor(mContext, R.color.platform_main_theme))
                    tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.platform_arrow_drop_down_en, 0)
                }
            }
        }

        //设置筛选选项的按钮文字颜色
        private fun updateOthersTextColor(mContext: Context, tv: AppCompatTextView, status: Int) {
            LogUtil.e("http-----------------updateOthersTextColor")
            when (status) {
                IConfideHomeConfig.FILTER_STATUS_NORMAL -> {
                    tv.setTextColor(ContextCompat.getColor(mContext, R.color._6))
                }
                IConfideHomeConfig.FILTER_STATUS_FILTERED, IConfideHomeConfig.FILTER_STATUS_OPEN -> {
                    tv.setTextColor(ContextCompat.getColor(mContext, R.color.platform_main_theme))
                }
            }
            tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.platform_arrow_drop_down_un, 0)
        }

        //更改筛选选项的按钮 图标
        private fun updateOthersTextDrawable(mContext: Context, tv: AppCompatTextView, status: Int) {
            when (status) {
                IConfideHomeConfig.FILTER_STATUS_NORMAL -> {
                    tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.platform_arrow_drop_down_un, 0)
                }
                IConfideHomeConfig.FILTER_STATUS_FILTERED, IConfideHomeConfig.FILTER_STATUS_OPEN -> {
                    tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.platform_arrow_drop_down_en, 0)
                }
            }
        }

        /**
         * 启动 播放动画
         */
        fun startPlayAnim(context: Context, imageView: ImageView) {
            var animation = AnimationUtils.loadAnimation(context, R.anim.confide_play_anim)
            var lin = LinearInterpolator()//设置动画匀速运动
            animation.interpolator = lin
            imageView.startAnimation(animation)
        }

        /**
         * 停止 播放动画
         */
        fun stopPlayAnim(imageView: ImageView) {
            imageView.clearAnimation()
        }

        /**
         * 构建为你推荐接口入参
         * @param  allFiltersBean          筛选参数缓存
         * @return ConfideRecommendParam  为你推荐参数bean
         */
        fun createParam(allFiltersBean: ConfideHomeAllFiltersBean): ConfideRecommendParam {
            var param = ConfideRecommendParam.Builder()
            param.notInUid = allFiltersBean.notInUid
            //页码
            if (-1 != allFiltersBean.page) {
                param.page(allFiltersBean.page)
            }
            //综合排序
            if (null != allFiltersBean.selectSort && !TextUtils.isEmpty(allFiltersBean.selectSort!!.id) && "-1" != allFiltersBean.selectSort!!.id) {
                param.sortType(allFiltersBean.selectSort!!.id!!)
            }
            //性别
            if (null != allFiltersBean.selectSex && !TextUtils.isEmpty(allFiltersBean.selectSex!!.id) && "-1" != allFiltersBean.selectSex!!.id) {
                param.sexType(allFiltersBean.selectSex!!.id!!)
            }
            //年龄
            if (null != allFiltersBean.selectAgeData && !allFiltersBean.selectAgeData.isEmpty()) {
                param.ageType(allFiltersBean.selectAgeData.map { it.id }.joinToString("-"))
            }
            //擅长方向
            if (null != allFiltersBean.selectGoodData && !allFiltersBean.selectGoodData.isEmpty()) {
                param.goodType(allFiltersBean.selectGoodData.map { it.id }.joinToString("-"))
            }
            return param.build()
        }
    }
}