package cn.muchinfo.rma.view.base.sale

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.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.procurement.*
import com.blankj.utilcode.util.ConvertUtils
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 org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.UI
import org.jetbrains.anko.support.v4.viewPager

/**
 * 销售
 */
class SaleFragment : BaseFragment<SaleViewModel>() {

    companion object {
        fun newInstance() = SaleFragment()
    }

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

    private val priceUI by lazy { SalePriceUI(this, viewModel) }
    private val settlementUI by lazy { SaleSettlementUI(this, viewModel) }
    private val allUI by lazy { SalenewAllUI(this, viewModel) }

    private val tabsArray: List<String> by lazy { arrayListOf("待点价", "履约结算", "全部") }
//    inflater.inflate(R.layout.fragment_init, container, false)

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

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

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                // return container.addView(LayoutInflater.from(context).inflate(R.layout.activity_main, container, false),ViewGroup.LayoutParams(matchParent, matchParent))
                if (position == 0) {
                    return priceUI.root.apply {
                        container.addView(this, ViewGroup.LayoutParams(matchParent, matchParent))
                    }
                } else if (position == 1) {
                    return settlementUI.root.apply {
                        container.addView(this, ViewGroup.LayoutParams(matchParent, matchParent))
                    }
                } else if (position == 2) {
                    return allUI.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 SalePriceUI(private val baseFragment: Fragment, private val viewModule: SaleViewModel) : ContentAdapter.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 contentAdapter by lazy {
        ContentAdapter(baseFragment.context,"1")
    }

    @SuppressLint("RtlHardcoded")
    val root = _FrameLayout(baseFragment.context!!).apply {
        verticalLayout {
            viewModule.queryTitle(Constant.table_mobile_purchase_pointprice,"-1")
            contentAdapter.setOnContentScrollListener(this@SalePriceUI)
            linearLayout {
                linearLayout {
                    gravity = Gravity.LEFT or Gravity.CENTER_VERTICAL
                    textView {//待点价头部左侧数据
                        viewModule.forSomePriceTitle.bindOptional(context) {
                            text = it?.get(0)?.columntitle?.replace("\\n", "\n") ?: ""
                        }
                        textColorStr = "#AAAAAA"
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent){
                        marginStart = autoSize(30)
                    }
                }.lparams(autoSize(SizeUtils.dp2px(135f)), autoSize(100))

                inflateLayout<CustomHorizontalScrollView>(R.layout.scrollview) {
                    horScrollview = this
                    setOnCustomScrollChangeListener { listener, scrollX, scrollY, oldScrollX, oldScrollY -> //代码重复,可以抽取/////
                        contentAdapter.offestX = scrollX
                        val viewHolderCacheList: List<ContentAdapter.ItemViewHolder> =
                            contentAdapter.viewHolderCacheList

                        if (null != viewHolderCacheList) {
                            val size = viewHolderCacheList.size
                            for (i in 0 until size) {
                                viewHolderCacheList[i].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.forSomePriceTitle.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 {
                        /**
                         * 下拉刷新
                         * contracttype 1-采购, -1-销售
                         * type  1-全部 2-待点价 3-履约结算
                         */
                        viewModule.queryContract("2","-1")
                    }
                    setEnableScrollContentWhenLoaded(false)
                    setEnableLoadMoreWhenContentNotFull(false)

                    recyclerView {//待点价列表
                        background = resources.getDrawable(R.color.white)
                        adapter = contentAdapter
                        addOnScrollListener(object : RecyclerView.OnScrollListener() {
                            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                                super.onScrolled(recyclerView, dx, dy)
                                val viewHolderCacheList: List<ContentAdapter.ItemViewHolder> =
                                    contentAdapter.viewHolderCacheList
                                if (null != viewHolderCacheList) {
                                    val size = viewHolderCacheList.size
                                    for (i in 0 until size) {
                                        viewHolderCacheList[i].horItemScrollview.scrollTo(
                                            contentAdapter.getOffestX(),
                                            0
                                        )
                                    }
                                }
                            }
                        })
                    }


                }
            }, emptyBlock = {
                emptyView(hint = resources.getString(R.string.now_no_data))
            }).lparams(matchParent, matchParent)

            viewModule.forSomePriceDataList.bindOptional(context) {
                if (it?.isEmpty() == true || it?.size == 0) {
                    statusLayout.showEmpty()
                } else {
                    if (swipeToLayout.getIsRefreshing()) {
                        swipeToLayout.finishRefresh()
//                        mHeadHeaderHSView.scrollTo(scrollXView,scrollYView)
                    }
                    contentAdapter.setDatas(it)
                }
            }
        }
    }

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

}



/**
 * 履约结算
 */
@Suppress("INACCESSIBLE_TYPE")
class SaleSettlementUI(
    private val baseFragment: Fragment,
    private val viewModule: SaleViewModel
) : ContentAdapter.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 contentAdapter by lazy {//Listtype 用来判断列表的tab
        ContentAdapter(baseFragment.context,"2")
    }

    @SuppressLint("RtlHardcoded")
    val root = _FrameLayout(baseFragment.context!!).apply {
        verticalLayout {
            viewModule.queryTitle(Constant.table_mobile_purchase_settle,"-1")
            contentAdapter.setOnContentScrollListener(this@SaleSettlementUI)
            linearLayout {
                linearLayout {
                    gravity = Gravity.LEFT or Gravity.CENTER_VERTICAL
                    textView {
                        viewModule.settlementTitle.bindOptional(context) {
                            text = it?.get(0)?.columntitle?.replace("\\n", "\n") ?: ""
                        }
                        textColorStr = "#AAAAAA"
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent){
                        marginStart = autoSize(30)
                    }
                }.lparams(autoSize(SizeUtils.dp2px(135f)), autoSize(100))

                inflateLayout<CustomHorizontalScrollView>(R.layout.scrollview) {
                    horScrollview = this
                    setOnCustomScrollChangeListener { listener, scrollX, scrollY, oldScrollX, oldScrollY -> //代码重复,可以抽取/////
                        contentAdapter.offestX = scrollX
                        val viewHolderCacheList: List<ContentAdapter.ItemViewHolder> =
                            contentAdapter.viewHolderCacheList

                        if (null != viewHolderCacheList) {
                            val size = viewHolderCacheList.size
                            for (i in 0 until size) {
                                viewHolderCacheList[i].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.settlementTitle.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 {
                        /**
                         * 下拉刷新
                         * contracttype 1-采购, -1-销售
                         * type  1-全部 2-待点价 3-履约结算
                         */
                        viewModule.queryContract("3","-1")
                    }
                    setEnableScrollContentWhenLoaded(false)
                    setEnableLoadMoreWhenContentNotFull(false)

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

            viewModule.settlementDataList.bindOptional(context) {
                if (it?.isEmpty() == true || it?.size == 0) {
                    statusLayout.showEmpty()
                } else {
                    if (swipeToLayout.getIsRefreshing()) {
                        swipeToLayout.finishRefresh()
//                        mHeadHeaderHSView.scrollTo(scrollXView,scrollYView)
                    }
                    contentAdapter.setDatas(it)
                }
            }
        }
    }

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


/**
 * 全部
 * @property baseFragment Fragment
 * @property viewModule SaleViewModel
 * @property swipeToLayout SwipeToLoadLayout
 * @property statusLayout StatusLayout
 * @property horScrollview CustomHorizontalScrollView
 * @property recyclerView RecyclerView
 * @property topAdapter TopTabAdpater
 * @property contentAdapter ContentAdapter
 * @property root _FrameLayout
 * @constructor
 */
class SalenewAllUI(private val baseFragment: Fragment, private val viewModule: SaleViewModel) : ContentAdapter.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 contentAdapter by lazy {
        ContentAdapter(baseFragment.context,"3")
    }

    @SuppressLint("RtlHardcoded")
    val root = _FrameLayout(baseFragment.context!!).apply {
        verticalLayout {
            viewModule.queryTitle(Constant.table_mobile_purchase_all,"-1")
            contentAdapter.setOnContentScrollListener(this@SalenewAllUI)
            linearLayout {
                linearLayout {
                    gravity = Gravity.LEFT or Gravity.CENTER_VERTICAL
                    textView {
                        viewModule.allTitle.bindOptional(context) {
                            text = it?.get(0)?.columntitle?.replace("\\n", "\n") ?: ""
                        }
                        textColorStr = "#AAAAAA"
                        textSizeAuto = 24
                    }.lparams(wrapContent, wrapContent){
                        marginStart = autoSize(30)
                    }
                }.lparams(autoSize(SizeUtils.dp2px(135f)), autoSize(100))

                inflateLayout<CustomHorizontalScrollView>(R.layout.scrollview) {
                    horScrollview = this
                    setOnCustomScrollChangeListener { listener, scrollX, scrollY, oldScrollX, oldScrollY -> //代码重复,可以抽取/////
                        contentAdapter.offestX = scrollX
                        val viewHolderCacheList: List<ContentAdapter.ItemViewHolder> =
                            contentAdapter.viewHolderCacheList

                        if (null != viewHolderCacheList) {
                            val size = viewHolderCacheList.size
                            for (i in 0 until size) {
                                viewHolderCacheList[i].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.allTitle.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 {
                        /**
                         * 下拉刷新
                         * contracttype 1-采购, -1-销售
                         * type  1-全部 2-待点价 3-履约结算
                         */
                        viewModule.queryContract("1","-1")
                    }
                    setEnableScrollContentWhenLoaded(false)
                    setEnableLoadMoreWhenContentNotFull(false)

                    recyclerView {
                        background = resources.getDrawable(R.color.white)
                        adapter = contentAdapter
                        addOnScrollListener(object : RecyclerView.OnScrollListener() {
                            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                                super.onScrolled(recyclerView, dx, dy)
                                val viewHolderCacheList: List<ContentAdapter.ItemViewHolder> =
                                    contentAdapter.viewHolderCacheList
                                if (null != viewHolderCacheList) {
                                    val size = viewHolderCacheList.size
                                    for (i in 0 until size) {
                                        viewHolderCacheList[i].horItemScrollview.scrollTo(
                                            contentAdapter.getOffestX(),
                                            0
                                        )
                                    }
                                }
                            }
                        })
                    }


                }
            }, emptyBlock = {
                emptyView(hint = resources.getString(R.string.now_no_data))
            }).lparams(matchParent, matchParent)

            viewModule.allDataList.bindOptional(context) {
                if (it?.isEmpty() == true || it?.size == 0) {
                    statusLayout.showEmpty()
                } else {
                    if (swipeToLayout.getIsRefreshing()) {
                        swipeToLayout.finishRefresh()
//                        mHeadHeaderHSView.scrollTo(scrollXView,scrollYView)
                    }
                    contentAdapter.setDatas(it)
                }
            }
        }
    }

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

