package cn.muchinfo.rma.view.base.exposure

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import cn.muchinfo.rma.R
import cn.muchinfo.rma.global.data.FinancialManageData
import cn.muchinfo.rma.global.data.NumberSpotData
import cn.muchinfo.rma.lifecycle.bindOptional
import cn.muchinfo.rma.view.autoWidget.*
import cn.muchinfo.rma.view.base.BaseFragment
import cn.muchinfo.rma.view.base.app.Constant
import cn.muchinfo.rma.view.base.home.financial.FinancialViewholder
import cn.muchinfo.rma.view.base.procurement.TopTabAdpater
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator
import com.qmuiteam.qmui.widget.tab.QMUITabSegment
import mtp.polymer.com.autowidget.adapter.BaseAdapter
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.UI
import org.jetbrains.anko.support.v4.viewPager

/**
 * 敞口
 */

class ExposureFragment : BaseFragment<ExposureViewModel>() {
    companion object {
        fun newInstance() = ExposureFragment()
    }

    lateinit var segment: QMUITabSegment
    var selectedTabIndex: Int = 0
    private lateinit var viewPager: ViewPager

    /** tab标题 ***/
    private val tabsArray: List<String> by lazy { arrayListOf("实时敞口", "现货数量", "期货数量", "历史敞口") }

    /** 实时敞口 **/
    private val realTimeExposureUI by lazy { RealTimeExposureUI(this, viewModel) }

    /** 现货数量 **/
    private val numberSpotUI by lazy { NumberSpotUI(this, viewModel) }

    /** 期货数量 **/
    private val numberFutureUI by lazy { NumberFutureUI(this, viewModel) }

    /** 历史敞口 **/
    private val historyExposureUI by lazy { HistoryExposureUI(this, viewModel) }

    private val pagerAdapter: PagerAdapter by lazy {
        object : PagerAdapter() {

            override fun getPageTitle(position: Int): CharSequence? = tabsArray[position]

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                if (position == 0) {
                    return realTimeExposureUI.root.apply {
                        container.addView(this, ViewGroup.LayoutParams(matchParent, matchParent))
                    }
                } else if (position == 1) {
                    return numberSpotUI.root.apply {
                        container.addView(this, ViewGroup.LayoutParams(matchParent, matchParent))
                    }
                } else if (position == 2) {
                    return numberFutureUI.root.apply {
                        container.addView(this, ViewGroup.LayoutParams(matchParent, matchParent))
                    }
                } else if (position == 3) {
                    return historyExposureUI.root.apply {
                        container.addView(this, ViewGroup.LayoutParams(matchParent, matchParent))
                    }
                }
                return super.instantiateItem(container, position)
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                (`object` as? View)?.let { container.removeView(it) }
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean = view == `object`

            override fun getCount(): Int = tabsArray.size

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return UI {
            verticalLayout {
                linearLayout {
                    background = resources.getDrawable(R.color.main_title_bg_color)
                    verticalLayout {
                        gravity = Gravity.CENTER_VERTICAL
                        textView {
                            text = "采购"
                            textColorInt = R.color.white
                            textSizeAuto = 36
                        }.lparams(wrapContent, wrapContent) {
                            gravity = Gravity.CENTER_HORIZONTAL
                        }
                    }.lparams(autoSize(620), autoSize(90)) {
                        marginStart = autoSize(140)
                    }

                    imageView {
                        imageResource = R.mipmap.main_search
                    }.lparams(autoSize(45), autoSize(45)) {
                        marginStart = autoSize(32)
                        topMargin = autoSize(20)
                    }
                }.lparams(matchParent, autoSize(100))

                tabSegment {
                    segment = this
                    background = resources.getDrawable(R.color.segtabment_bg_color)
                    addOnTabSelectedListener(object :
                        QMUITabSegment.OnTabSelectedListener {
                        override fun onDoubleTap(index: Int) {}
                        override fun onTabReselected(index: Int) {}
                        override fun onTabUnselected(index: Int) {}
                        override fun onTabSelected(index: Int) {
                            selectedTabIndex = index
                        }
                    })
                    setIndicator(QMUITabIndicator(QMUIDisplayHelper.dp2px(context, 2), false, true))
                    setDefaultTextSize(ConvertUtils.sp2px(16f), ConvertUtils.sp2px(16f))
                }.lparams(matchParent, autoSize(100))

                view {
                    background = resources.getDrawable(R.color.main_hit_bg_color)
                }.lparams(matchParent, autoSize(1)) {
                    marginStart = autoSize(32)
                    marginEnd = autoSize(32)
                }
                viewPager {
                    background = resources.getDrawable(R.color.white)
                    viewPager = this
                    adapter = pagerAdapter
                }.lparams(matchParent, matchParent)

                segment.setupWithViewPager(viewPager)
                segment.selectTab(selectedTabIndex)
            }

        }.view
    }
}

/**
 * 实时敞口
 */
class RealTimeExposureUI(
    private val baseFragment: Fragment,
    private val viewModule: ExposureViewModel
) : ExposureContentAdapter.OnContentScrollListener {
    private lateinit var swipeToLayout: SwipeToLoadLayout
    private lateinit var statusLayout: StatusLayout
    lateinit var horScrollview: CustomHorizontalScrollView
    lateinit var recyclerView: RecyclerView

    val topAdapter by lazy {
        TopTabAdpater(baseFragment.context)
    }

    val exposureContentAdapter by lazy {
        ExposureContentAdapter(baseFragment.context)
    }

    @SuppressLint("RtlHardcoded")
    val root = _FrameLayout(baseFragment.context!!).apply {
        verticalLayout {
            viewModule.queryTitle(Constant.table_mobile_exposure_realtime)
            exposureContentAdapter.setOnContentScrollListener(this@RealTimeExposureUI)
            linearLayout {
                linearLayout {
                    gravity = Gravity.LEFT or Gravity.CENTER_VERTICAL
                    textView {//头部右侧数据
                        viewModule.realTimeExposureTitle.bindOptional(context) {
                            text = it?.get(0)?.columntitle?.replace("\\n", "\n") ?: ""
                        }
                        textColorStr = "#AAAAAA"
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent) {
                        marginStart = autoSize(30)
                    }
                }.lparams(autoSize(SizeUtils.dp2px(90f)), autoSize(100))

                inflateLayout<CustomHorizontalScrollView>(R.layout.scrollview) {
                    horScrollview = this
                    /**
                     * 用来同步内容列表的item左右滑动
                     */
                    setOnCustomScrollChangeListener { listener, scrollX, scrollY, oldScrollX, oldScrollY ->
                        exposureContentAdapter.offestX = scrollX
                        val viewHolderCacheList: List<ExposureContentAdapter.ItemViewHolder> =
                            exposureContentAdapter.viewHolderCacheList
                        if (null != viewHolderCacheList) {
                            val size = viewHolderCacheList.size
                            for (i in 0 until size) {
                                viewHolderCacheList[i].exposure_horItemScrollview.scrollTo(
                                    scrollX,
                                    0
                                )
                            }
                        }
                    }
                    relativeLayout {
                        recyclerView {//头部右侧数据
                            val linearLayoutManager = LinearLayoutManager(context)
                            linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
                            layoutManager = linearLayoutManager
                            background = resources.getDrawable(R.color.white)
                            adapter = topAdapter
                        }
                        viewModule.realTimeExposureTitle.bindOptional(context) {
                            val titleStringList = arrayListOf<String>()
                            it?.subList(1, it.size)?.forEach { data ->
                                titleStringList.add(data.columntitle?.replace("\\n", "\n") ?: "")
                            }
                            topAdapter.setDatas(titleStringList)
                        }
                    }
                }.lparams(matchParent, matchParent)
            }.lparams(matchParent, autoSize(100))

            statusLayout(contentBlock = {
                statusLayout = this
//                bindTaskStatus(viewModule.status)
                swipeToLoadLayout {
                    swipeToLayout = this
                    setEnableRefresh(true)
                    setEnableLoadMore(false)
                    setOnRefreshListener {
                        /**
                         * 下拉刷新
                         */
                        viewModule.queryRealtimeExposure()
                    }
                    setEnableScrollContentWhenLoaded(false)
                    setEnableLoadMoreWhenContentNotFull(false)

                    recyclerView {
                        background = resources.getDrawable(R.color.white)
                        adapter = exposureContentAdapter
                        addOnScrollListener(object : RecyclerView.OnScrollListener() {
                            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                                super.onScrolled(recyclerView, dx, dy)
                                val viewHolderCacheList: List<ExposureContentAdapter.ItemViewHolder> =
                                    exposureContentAdapter.viewHolderCacheList
                                if (null != viewHolderCacheList) {
                                    val size = viewHolderCacheList.size
                                    for (i in 0 until size) {
                                        viewHolderCacheList[i].exposure_horItemScrollview.scrollTo(
                                            exposureContentAdapter.getOffestX(),
                                            0
                                        )
                                    }
                                }
                            }
                        })
                    }
                }
            }, emptyBlock = {
                emptyView(hint = resources.getString(R.string.now_no_data))
            }).lparams(matchParent, matchParent)

            viewModule.realTimeExposureDataList.bindOptional(context) {
                LogUtils.eTag("dajsdhajkhsdsa",it?.size)
                if (it?.isEmpty() == true || it?.size == 0) {
                    statusLayout.showEmpty()
                } else {
                    if (swipeToLayout.getIsRefreshing()) {
                        swipeToLayout.finishRefresh()
//                        mHeadHeaderHSView.scrollTo(scrollXView,scrollYView)
                    }
                    statusLayout.showSuccess()
                    exposureContentAdapter.setDatas(it)
                }
            }
        }
    }

    override fun onScroll(event: MotionEvent?) {
        //处理单个item滚动时,顶部tab需要联动
        if (null != horScrollview) horScrollview.onTouchEvent(event)
    }
}

/**
 * 现货数量UI
 * @property baseFragment Fragment
 * @property viewModule ExposureViewModel
 * @property root _FrameLayout
 * @constructor
 */
class NumberSpotUI(
    private val baseFragment: Fragment,
    private val viewModule: ExposureViewModel
) {

    private lateinit var swipeToLayout: SwipeToLoadLayout
    private lateinit var statusLayout: StatusLayout

    private val numberSpotAdapter: BaseAdapter<NumberSpotData, ExposureNumberViewHolder> = BaseAdapter { _, _ -> ExposureNumberViewHolder(baseFragment, viewModule,"1") }

    init {
        viewModule.queryExposureSpot()
    }

    val root = _FrameLayout(baseFragment.context!!).apply {
        verticalLayout {
            linearLayout {
                verticalLayout {
                    gravity = Gravity.CENTER
                    textView {
                        text = "现货品种"
                        textColorInt = R.color.hint_text_color
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent)
                    textView {
                        text = "代码"
                        textColorInt = R.color.hint_text_color
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent)
                }.lparams(autoSize(225), autoSize(92))

                verticalLayout {
                    gravity = Gravity.CENTER
                    textView {
                        text = "昨日数量"
                        textColorInt = R.color.hint_text_color
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent)
                }.lparams(autoSize(225), autoSize(92))

                verticalLayout {
                    gravity = Gravity.CENTER
                    textView {
                        text = "增加数量"
                        textColorInt = R.color.hint_text_color
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent)
                    textView {
                        text = "减少数量"
                        textColorInt = R.color.hint_text_color
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent)
                }.lparams(autoSize(225), autoSize(92))

                verticalLayout {
                    gravity = Gravity.RIGHT
                    textView {
                        text = "当前数量"
                        textColorInt = R.color.hint_text_color
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent){
                        marginEnd = autoSize(36)
                        topMargin = autoSize(30)
                    }
                }.lparams(autoSize(225), autoSize(92))
            }.lparams(matchParent, autoSize(92))


            statusLayout(contentBlock = {
                statusLayout = this
//                bindTaskStatus(viewModule.status)
                swipeToLoadLayout {
                    swipeToLayout = this
                    setEnableRefresh(true)
                    setEnableLoadMore(false)
                    setOnRefreshListener {
                        viewModule.queryExposureSpot()
                    }
                    setEnableScrollContentWhenLoaded(false)
                    setEnableLoadMoreWhenContentNotFull(false)
                    recyclerView {
                        background = resources.getDrawable(R.color.white)
                        adapter = numberSpotAdapter
                    }.lparams(matchParent, matchParent)
                }
            }, emptyBlock = {
                emptyView(hint = resources.getString(R.string.now_no_data))
            }).lparams(matchParent, matchParent)

            viewModule.exposureSpotDataList.bindOptional(context){
                if (it?.isEmpty() == true || it?.size == 0){
                    statusLayout.showEmpty()
                }else {
                    if (swipeToLayout.getIsRefreshing()){
                        swipeToLayout.finishRefresh()
                    }
                    numberSpotAdapter.setNewData(it)
                }
            }

        }
    }
}

/**
 * 期货数量UI
 * @property baseFragment Fragment
 * @property viewModule ExposureViewModel
 * @property root _FrameLayout
 * @constructor
 */
class NumberFutureUI(
    private val baseFragment: Fragment,
    private val viewModule: ExposureViewModel
) {

    private lateinit var swipeToLayout: SwipeToLoadLayout
    private lateinit var statusLayout: StatusLayout

    private val numberFutureAdapter: BaseAdapter<NumberSpotData, ExposureNumberViewHolder> = BaseAdapter { _, _ -> ExposureNumberViewHolder(baseFragment, viewModule,"2") }

    init {
        viewModule.queryExposureHedgePosition()
    }

    val root = _FrameLayout(baseFragment.context!!).apply {
        verticalLayout {
            linearLayout {
                verticalLayout {
                    gravity = Gravity.CENTER
                    textView {
                        text = "期货合约"
                        textColorInt = R.color.hint_text_color
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent)
                    textView {
                        text = "代码"
                        textColorInt = R.color.hint_text_color
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent)
                }.lparams(autoSize(225), autoSize(92))

                verticalLayout {
                    gravity = Gravity.CENTER
                    textView {
                        text = "昨日数量"
                        textColorInt = R.color.hint_text_color
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent)
                }.lparams(autoSize(225), autoSize(92))

                verticalLayout {
                    gravity = Gravity.CENTER
                    textView {
                        text = "增加数量"
                        textColorInt = R.color.hint_text_color
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent)
                    textView {
                        text = "减少数量"
                        textColorInt = R.color.hint_text_color
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent)
                }.lparams(autoSize(225), autoSize(92))

                verticalLayout {
                    gravity = Gravity.RIGHT
                    textView {
                        text = "当前数量"
                        textColorInt = R.color.hint_text_color
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent){
                        marginEnd = autoSize(36)
                        topMargin = autoSize(30)
                    }
                }.lparams(autoSize(225), autoSize(92))
            }.lparams(matchParent, autoSize(92))

            statusLayout(contentBlock = {
                statusLayout = this
//                bindTaskStatus(viewModule.status)
                swipeToLoadLayout {
                    swipeToLayout = this
                    setEnableRefresh(true)
                    setEnableLoadMore(false)
                    setOnRefreshListener {
                        viewModule.queryExposureHedgePosition()
                    }
                    setEnableScrollContentWhenLoaded(false)
                    setEnableLoadMoreWhenContentNotFull(false)
                    recyclerView {
                        background = resources.getDrawable(R.color.white)
                        adapter = numberFutureAdapter
                    }.lparams(matchParent, matchParent)
                }
            }, emptyBlock = {
                emptyView(hint = resources.getString(R.string.now_no_data))
            }).lparams(matchParent, matchParent)

            viewModule.exposurePositionDataList.bindOptional(context){
                if (it?.isEmpty() == true || it?.size == 0){
                    statusLayout.showEmpty()
                }else {
                    if (swipeToLayout.getIsRefreshing()){
                        swipeToLayout.finishRefresh()
                    }
                    numberFutureAdapter.setNewData(it)
                }
            }
        }
    }
}

/**
 * 历史敞口UI
 * @property baseFragment Fragment
 * @property viewModule ExposureViewModel
 * @property root _FrameLayout
 * @constructor
 */
class HistoryExposureUI(
    private val baseFragment: Fragment,
    private val viewModule: ExposureViewModel
) {
    val root = _FrameLayout(baseFragment.context!!).apply {
        verticalLayout {

        }
    }
}