package cn.muchinfo.rma.view.base.home.hedge

import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import cn.muchinfo.rma.R
import cn.muchinfo.rma.global.data.HedgePlanData
import cn.muchinfo.rma.lifecycle.bindOptional
import cn.muchinfo.rma.view.autoWidget.*
import cn.muchinfo.rma.view.base.BaseActivity
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.ToastUtils
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.viewPager

/**
 * 套保计划
 */
class HedgePlanActivity : BaseActivity<HedgePlanViewModel>() {

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

    private val tabsArray: List<String> by lazy {
        arrayListOf("未提交", "待审核", "执行中")
    }

    private val unSubmitUI by lazy { UnSubmitUI(this, viewModel, "0") }
    private val toAuditUI by lazy { ToAuditUI(this, viewModel, "1") }
    private val executionUI by lazy { ExecutionUI(this, viewModel, "2") }

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

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

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                when (position) {
                    0 -> {
                        return unSubmitUI.root.apply {
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    1 -> {
                        return toAuditUI.root.apply {
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    2 -> {
                        return executionUI.root.apply {
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }

                    else -> 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 onResume() {
        super.onResume()
        if (selectedTabIndex == 0){
            viewModel.queryHedegList("0")
        }else if (selectedTabIndex == 1){
            viewModel.queryHedegList("1")
        }else if (selectedTabIndex == 2){
            viewModel.queryHedegList("2")
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        verticalLayout {
            frameLayout {
                background = resources.getDrawable(R.color.main_title_bg_color)
                linearLayout {
                    gravity = Gravity.CENTER
                    textView {
                        text = "套保计划"
                        textSizeAuto = 41
                        textColorInt = R.color.white
                    }.lparams(wrapContent, wrapContent)
                }.lparams(matchParent, autoSize(120))

                linearLayout {
                    gravity = Gravity.CENTER_VERTICAL

                    imageView {
                        onThrottleFirstClick {
                            finish()
                        }
                        imageResource = R.mipmap.back
                    }.lparams(autoSize(48), autoSize(48)) {
                        gravity = Gravity.CENTER
                        marginStart = autoSize(40)
                    }

                    view { }.lparams(0, autoSize(1), 1f)

                    imageView {
                        onThrottleFirstClick {
                            ToastUtils.showLong("查询")
                        }
                        imageResource = R.mipmap.rma_search
                    }.lparams(autoSize(43), autoSize(43)) {
                        marginEnd = autoSize(36)
                    }

                    imageView {
                        onThrottleFirstClick {
                            val intent = Intent()
                            intent.putExtra("type","1")
                            intent.putExtra("data",HedgePlanData())
                            intent.setClass(context, AddHedgePlanActivity::class.java)
                            ActivityUtils.startActivity(intent)
                        }
                        imageResource = R.mipmap.rma_contract_add
                    }.lparams(autoSize(43), autoSize(43)) {
                        marginEnd = autoSize(36)
                    }

                }.lparams(matchParent, autoSize(120))

            }.lparams(matchParent, autoSize(120))

            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, autoSize(2000))

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

}

/**
 * 未提交
 */
class UnSubmitUI(
    private val activity: AppCompatActivity,
    private val viewModel: HedgePlanViewModel,
    private val type: String
) {
    private lateinit var swipeToLayout: SwipeToLoadLayout
    private lateinit var statusLayout: StatusLayout

    private val unSubmitAdapter: BaseAdapter<HedgePlanData, HedgePlanViewHolder> =
        BaseAdapter { _, _ -> HedgePlanViewHolder(activity, viewModel, type) }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            viewModel.queryHedegList(type)
            creatHedgeHeadUI()

            view {
                background = resources.getDrawable(R.color.line_hint_color)
            }.lparams(matchParent, autoSize(1))

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

            viewModel.unSubmitList.bindOptional(context) {
                if (it?.isEmpty() == true || it?.size == 0) {
                    statusLayout.showEmpty()
                } else {
                    if (swipeToLayout.getIsRefreshing()) {
                        swipeToLayout.finishRefresh()
                    }
                    unSubmitAdapter.setNewData(it)
                }
            }
        }
    }

}


/**
 * 待审核
 */
class ToAuditUI(
    private val activity: AppCompatActivity,
    private val viewModel: HedgePlanViewModel,
    private val type: String
) {

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

    private val unSubmitAdapter: BaseAdapter<HedgePlanData, HedgePlanViewHolder> =
        BaseAdapter { _, _ -> HedgePlanViewHolder(activity, viewModel, type) }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            viewModel.queryHedegList(type)
            creatHedgeHeadUI()

            view {
                background = resources.getDrawable(R.color.line_hint_color)
            }.lparams(matchParent, autoSize(1))

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

            viewModel.toAuditList.bindOptional(context) {
                if (it?.isEmpty() == true || it?.size == 0) {
                    statusLayout.showEmpty()
                } else {
                    if (swipeToLayout.getIsRefreshing()) {
                        swipeToLayout.finishRefresh()
                    }
                    unSubmitAdapter.setNewData(it)
                }
            }
        }
    }
}

class ExecutionUI(
    private val activity: AppCompatActivity,
    private val viewModel: HedgePlanViewModel,
    private val type: String
) {


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

    private val unSubmitAdapter: BaseAdapter<HedgePlanData, HedgePlanViewHolder> =
        BaseAdapter { _, _ -> HedgePlanViewHolder(activity, viewModel, type) }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            viewModel.queryHedegList(type)
            creatHedgeHeadUI()

            view {
                background = resources.getDrawable(R.color.line_hint_color)
            }.lparams(matchParent, autoSize(1))

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

            viewModel.executionList.bindOptional(context) {
                if (it?.isEmpty() == true || it?.size == 0) {
                    statusLayout.showEmpty()
                } else {
                    if (swipeToLayout.getIsRefreshing()) {
                        swipeToLayout.finishRefresh()
                    }
                    unSubmitAdapter.setNewData(it)
                }
            }
        }
    }

}


fun _LinearLayout.creatHedgeHeadUI() {
    linearLayout {
        gravity = Gravity.CENTER_VERTICAL
        verticalLayout {
            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(wrapContent, wrapContent) {
            marginStart = autoSize(37)
        }

        verticalLayout {
            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(wrapContent, wrapContent) {
            marginStart = autoSize(200)
        }

        verticalLayout {
            gravity = Gravity.CENTER_VERTICAL
            textView {
                text = "计划量"
                textColorInt = R.color.hint_text_color
                textSizeAuto = 24
            }.lparams(wrapContent, wrapContent)

        }.lparams(wrapContent, autoSize(92)) {
            marginStart = autoSize(125)
        }

        verticalLayout {
            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(wrapContent, wrapContent) {
            marginStart = autoSize(125)
        }
    }.lparams(matchParent, autoSize(92))
}