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

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
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.GlobalDataCollection
import cn.muchinfo.rma.global.data.AmountLogData
import cn.muchinfo.rma.lifecycle.bindOptional
import cn.muchinfo.rma.view.autoWidget.*
import cn.muchinfo.rma.view.base.BaseActivity
import cn.muchinfo.rma.view.base.home.contract.emptyView
import cn.muchinfo.rma.view.base.home.contract.viewItemUI
import cn.muchinfo.rma.view.base.home.financial.InvoiceRegisterActivity
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.TimeUtils
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 mtp.polymer.com.autowidget.dialog.showDataSelectDialog
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.viewPager
import java.text.SimpleDateFormat

class TradingQueryActivity : BaseActivity<TradingQueryViewModel>() {


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

    /** tab标题 **/
    private val tabsArray: List<String> by lazy {
        arrayListOf("历史委托", "历史成交", "资金流水")
    }

    /**历史委托UI**/
    private val historyCommissionedUI by lazy { HistoryCommissionedUI(this, viewModel) }

    /**历史成交UI**/
    private val historyDealUI by lazy { HistoryDealUI(this, viewModel) }

    /**资金流水UI**/
    private val moneyFlowingUI by lazy { MoneyFlowingUI(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 {
                when (position) {
                    0 -> {
                        return historyCommissionedUI.root.apply {//历史委托UI
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    1 -> {
                        return historyDealUI.root.apply {//历史成交UI
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    2 -> {
                        return moneyFlowingUI.root.apply {//资金流水UI
                            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 onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        verticalLayout {
            topBar {
                commonLeftButton()
                commonTitle {
                    text = "交易查询"
                }
                commonMenuButton(R.mipmap.rma_search) {
                    val intent = Intent()
                    intent.setClass(context, InvoiceRegisterActivity::class.java)
                    ActivityUtils.startActivity(intent)
                }
            }

            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)
        }
    }

}

/**
 * 历史委托UI
 * @property activity AppCompatActivity
 * @property viewModel FinancialViewModel
 * @constructor
 */
class HistoryCommissionedUI(
    private val activity: AppCompatActivity,
    private val viewModel: TradingQueryViewModel
) {

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

    private val historyCommissionedAdapter: BaseAdapter<String, TradingHistoryViewHolder> =
        BaseAdapter { _, _ -> TradingHistoryViewHolder(activity, viewModel) }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            linearLayout {
                gravity = Gravity.CENTER_VERTICAL
                //起始日期选择
                linearLayout {
                    backgroundResource = R.drawable.rma_time_click_bg
                    gravity = Gravity.CENTER_VERTICAL
                    textView {
                        text = "起始日期"
                        textColorInt = R.color.rma_hint_text_color_ccc
                        textSizeAuto = 31
                    }.lparams(wrapContent, wrapContent) {
                        marginStart = autoSize(18)
                    }

                    emptyView()

                    imageView {
                        imageResource = R.mipmap.rma_search_by_time
                    }.lparams(autoSize(38), autoSize(38))

                }.lparams(autoSize(324), autoSize(67)) {
                    marginStart = autoSize(36)
                }

                //结束日期选择
                linearLayout {
                    backgroundResource = R.drawable.rma_time_click_bg
                    gravity = Gravity.CENTER_VERTICAL
                    textView {
                        text = "结束日期"
                        textColorInt = R.color.rma_hint_text_color_ccc
                        textSizeAuto = 31
                    }.lparams(wrapContent, wrapContent) {
                        marginStart = autoSize(18)
                    }

                    emptyView()

                    imageView {
                        imageResource = R.mipmap.rma_search_by_time
                    }.lparams(autoSize(38), autoSize(38))
                }.lparams(autoSize(324), autoSize(67)) {
                    marginStart = autoSize(12)
                }

                textView {
                    gravity = Gravity.CENTER
                    backgroundDrawable = createCommonBottomRoundBg(color = "#2481DD", corner = 5)
                    text = "查询"
                    textSizeAuto = 31
                    textColorInt = R.color.white
                }.lparams(autoSize(144), autoSize(67)) {
                    marginStart = autoSize(12)
                }
            }.lparams(matchParent, autoSize(110))

            viewItemUI()

            linearLayout {
                verticalLayout {
                    gravity = Gravity.LEFT
                    textView {
                        text = "名称"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent)
                    textView {
                        text = "类型"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent)
                }.lparams(autoSize(300), autoSize(97))

                verticalLayout {
                    gravity = Gravity.CENTER
                    textView {
                        text = "委托数量"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent)
                    textView {
                        text = "价格"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent)
                }.lparams(autoSize(300), autoSize(97))

                verticalLayout {
                    gravity = Gravity.RIGHT
                    textView {
                        text = "状态"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent)
                    textView {
                        text = "时间"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent)
                }.lparams(autoSize(300), autoSize(97))
            }.lparams(matchParent, autoSize(97))

            statusLayout(contentBlock = {
                statusLayout = this
//                bindTaskStatus(viewModule.status)
                swipeToLoadLayout {
                    swipeToLayout = this
                    setEnableRefresh(true)
                    setEnableLoadMore(false)
                    setOnRefreshListener {

                    }
                    setEnableScrollContentWhenLoaded(false)
                    setEnableLoadMoreWhenContentNotFull(false)
                    recyclerView {
                        background = resources.getDrawable(R.color.white)
                        adapter = historyCommissionedAdapter
                    }.lparams(matchParent, matchParent)
                }
            }, emptyBlock = {
                emptyView(hint = resources.getString(R.string.now_no_data))
            }).lparams(matchParent, matchParent)
        }
    }
}


/**
 * 历史成交UI
 * @property activity AppCompatActivity
 * @property viewModel TradingQueryViewModel
 * @constructor
 */
class HistoryDealUI(
    private val activity: AppCompatActivity,
    private val viewModel: TradingQueryViewModel
) {

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

    private val historyCommissionedAdapter: BaseAdapter<String, TradingHistoryViewHolder> =
        BaseAdapter { _, _ -> TradingHistoryViewHolder(activity, viewModel) }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            linearLayout {
                gravity = Gravity.CENTER_VERTICAL
                //起始日期选择
                linearLayout {
                    backgroundResource = R.drawable.rma_time_click_bg
                    gravity = Gravity.CENTER_VERTICAL
                    textView {
                        text = "起始日期"
                        textColorInt = R.color.rma_hint_text_color_ccc
                        textSizeAuto = 31
                    }.lparams(wrapContent, wrapContent) {
                        marginStart = autoSize(18)
                    }

                    emptyView()

                    imageView {
                        imageResource = R.mipmap.rma_search_by_time
                    }.lparams(autoSize(38), autoSize(38))

                }.lparams(autoSize(324), autoSize(67)) {
                    marginStart = autoSize(36)
                }

                //结束日期选择
                linearLayout {
                    backgroundResource = R.drawable.rma_time_click_bg
                    gravity = Gravity.CENTER_VERTICAL
                    textView {
                        text = "结束日期"
                        textColorInt = R.color.rma_hint_text_color_ccc
                        textSizeAuto = 31
                    }.lparams(wrapContent, wrapContent) {
                        marginStart = autoSize(18)
                    }

                    emptyView()

                    imageView {
                        imageResource = R.mipmap.rma_search_by_time
                    }.lparams(autoSize(38), autoSize(38))
                }.lparams(autoSize(324), autoSize(67)) {
                    marginStart = autoSize(12)
                }

                textView {
                    gravity = Gravity.CENTER
                    backgroundDrawable = createCommonBottomRoundBg(color = "#2481DD", corner = 5)
                    text = "查询"
                    textSizeAuto = 31
                    textColorInt = R.color.white
                }.lparams(autoSize(144), autoSize(67)) {
                    marginStart = autoSize(12)
                }
            }.lparams(matchParent, autoSize(110))

            viewItemUI()

            linearLayout {
                verticalLayout {
                    gravity = Gravity.LEFT
                    textView {
                        text = "名称"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent)
                    textView {
                        text = "类型"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent)
                }.lparams(autoSize(300), autoSize(97))

                verticalLayout {
                    gravity = Gravity.CENTER
                    textView {
                        text = "委托数量"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent)
                    textView {
                        text = "价格"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent)
                }.lparams(autoSize(300), autoSize(97))

                verticalLayout {
                    gravity = Gravity.RIGHT
                    textView {
                        text = "状态"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent)
                    textView {
                        text = "时间"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent)
                }.lparams(autoSize(300), autoSize(97))
            }.lparams(matchParent, autoSize(97))

            statusLayout(contentBlock = {
                statusLayout = this
//                bindTaskStatus(viewModule.status)
                swipeToLoadLayout {
                    swipeToLayout = this
                    setEnableRefresh(true)
                    setEnableLoadMore(false)
                    setOnRefreshListener {

                    }
                    setEnableScrollContentWhenLoaded(false)
                    setEnableLoadMoreWhenContentNotFull(false)
                    recyclerView {
                        background = resources.getDrawable(R.color.white)
                        adapter = historyCommissionedAdapter
                    }.lparams(matchParent, matchParent)
                }
            }, emptyBlock = {
                emptyView(hint = resources.getString(R.string.now_no_data))
            }).lparams(matchParent, matchParent)
        }
    }
}

/**
 * 资金流水UI
 * @property activity AppCompatActivity
 * @property viewModel TradingQueryViewModel
 * @constructor
 */
class MoneyFlowingUI(
    private val activity: AppCompatActivity,
    private val viewModel: TradingQueryViewModel
) {

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

    var startTime: String = GlobalDataCollection.instance?.oneMonth() ?: ""//历史资金流水查询起始日期
    var endTime: String = TimeUtils.getNowString(SimpleDateFormat("yyyy-MM-dd"))//历史资金流水查询结束日期


    private val moneyFlowingdAdapter: BaseAdapter<AmountLogData, MoneyFlowingViewHolder> =
        BaseAdapter { _, _ -> MoneyFlowingViewHolder(activity, viewModel) }

    @RequiresApi(Build.VERSION_CODES.N)
    val root = _FrameLayout(activity).apply {
        verticalLayout {
            linearLayout {
                viewModel.queryHisAmountLog(startDate = startTime,endDate = endTime)
                gravity = Gravity.CENTER_VERTICAL
                //起始日期选择
                linearLayout {
                    onThrottleFirstClick {
                        activity.showDataSelectDialog {
                            startTime = this
                        }
                    }
                    backgroundResource = R.drawable.rma_time_click_bg
                    gravity = Gravity.CENTER_VERTICAL
                    textView {
                        text = "起始日期"
                        textColorInt = R.color.rma_hint_text_color_ccc
                        textSizeAuto = 31
                    }.lparams(wrapContent, wrapContent) {
                        marginStart = autoSize(18)
                    }

                    emptyView()

                    imageView {
                        imageResource = R.mipmap.rma_search_by_time
                    }.lparams(autoSize(38), autoSize(38))

                }.lparams(autoSize(324), autoSize(67)) {
                    marginStart = autoSize(36)
                }

                //结束日期选择
                linearLayout {
                    onThrottleFirstClick {
                        activity.showDataSelectDialog {
                            endTime = this
                        }
                    }
                    backgroundResource = R.drawable.rma_time_click_bg
                    gravity = Gravity.CENTER_VERTICAL
                    textView {
                        text = "结束日期"
                        textColorInt = R.color.rma_hint_text_color_ccc
                        textSizeAuto = 31
                    }.lparams(wrapContent, wrapContent) {
                        marginStart = autoSize(18)
                    }

                    emptyView()

                    imageView {
                        imageResource = R.mipmap.rma_search_by_time
                    }.lparams(autoSize(38), autoSize(38))
                }.lparams(autoSize(324), autoSize(67)) {
                    marginStart = autoSize(12)
                }

                textView {
                    onThrottleFirstClick {
                        viewModel.queryHisAmountLog(startDate = startTime, endDate = endTime)
                    }
                    gravity = Gravity.CENTER
                    backgroundDrawable = createCommonBottomRoundBg(color = "#2481DD", corner = 5)
                    text = "查询"
                    textSizeAuto = 31
                    textColorInt = R.color.white
                }.lparams(autoSize(144), autoSize(67)) {
                    marginStart = autoSize(12)
                }
            }.lparams(matchParent, autoSize(110))

            viewItemUI()

            linearLayout {
                verticalLayout {
                    gravity = Gravity.LEFT
                    textView {
                        text = "时间"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent){
                        marginStart = autoSize(36)
                        topMargin = autoSize(30)
                    }

                }.lparams(autoSize(300), autoSize(97))

                verticalLayout {
                    gravity = Gravity.CENTER
                    textView {
                        text = "操作类型"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent)

                }.lparams(autoSize(300), autoSize(97))

                verticalLayout {
                    gravity = Gravity.RIGHT
                    textView {
                        text = "金额"
                        textSizeAuto = 24
                        textColorInt = R.color.hint_text_color
                    }.lparams(wrapContent, wrapContent){
                        marginStart = autoSize(36)
                        topMargin = autoSize(30)
                    }
                }.lparams(autoSize(300), autoSize(97))
            }.lparams(matchParent, autoSize(97))

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

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


