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

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.FinancialManageData
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.customerdata.AddCustomerDataActivity
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ConvertUtils
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 FinancialActivity : BaseActivity<FinancialViewModel>(){


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

    private val tabsArray: List<String> by lazy {
        arrayListOf("款项", "发票")
    }

    private val paymentUI by lazy {
        PaymentUI(this,viewModel)
    }
    private val invoiceUI by lazy { InvoiceUI(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 paymentUI.root.apply {//款项
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    1 -> {
                        return invoiceUI.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()
        when (selectedTabIndex) {
            0 -> {
                viewModel.queryBusinessKx()
            }
            1 -> {
                viewModel.queryBusinessFp()
            }
        }
    }


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

}

/**
 * 款项
 * @property activity AppCompatActivity
 * @property viewModel FinancialViewModel
 * @property swipeToLayout SwipeToLoadLayout
 * @property statusLayout StatusLayout
 * @property paymentAdapter BaseAdapter<FinancialData, FinancialViewholder>
 * @property root _FrameLayout
 * @constructor
 */
class PaymentUI(
    private val activity: AppCompatActivity,
    private val viewModel : FinancialViewModel
){

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

    private val paymentAdapter: BaseAdapter<FinancialManageData, FinancialViewholder> = BaseAdapter { _, _ -> FinancialViewholder(activity, viewModel,"1") }

    init {
        viewModel.queryBusinessKx()
    }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            creatFinancialUI("1")

            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.queryBusinessKx()
                    }
                    setEnableScrollContentWhenLoaded(false)
                    setEnableLoadMoreWhenContentNotFull(false)
                    recyclerView {
                        background = resources.getDrawable(R.color.white)
                        adapter = paymentAdapter
                    }.lparams(matchParent, matchParent)
                }
            }, emptyBlock = {
                emptyView(hint = resources.getString(R.string.now_no_data))
            }).lparams(matchParent, matchParent)

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

/**
 * 发票
 * @property activity AppCompatActivity
 * @property viewModel FinancialViewModel
 * @property swipeToLayout SwipeToLoadLayout
 * @property statusLayout StatusLayout
 * @property invoiceAdapter BaseAdapter<FinancialData, FinancialViewholder>
 * @property root _FrameLayout
 * @constructor
 */
class InvoiceUI(
    private val activity: AppCompatActivity,
    private val viewModel : FinancialViewModel
){
    private lateinit var swipeToLayout: SwipeToLoadLayout
    private lateinit var statusLayout: StatusLayout

    init {
        viewModel.queryBusinessFp()
    }

    private val invoiceAdapter: BaseAdapter<FinancialManageData, FinancialViewholder> = BaseAdapter { _, _ -> FinancialViewholder(activity, viewModel,"2") }

    val root = _FrameLayout(activity).apply {
        verticalLayout {

            creatFinancialUI("2")

            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.queryBusinessFp()
                    }
                    setEnableScrollContentWhenLoaded(false)
                    setEnableLoadMoreWhenContentNotFull(false)
                    recyclerView {
                        background = resources.getDrawable(R.color.white)
                        adapter = invoiceAdapter
                    }.lparams(matchParent, matchParent)
                }
            }, emptyBlock = {
                emptyView(hint = resources.getString(R.string.now_no_data))
            }).lparams(matchParent, matchParent)

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


/**
 * 列表头部信息 type 为1是款项 为2是发票
 * @receiver _LinearLayout
 * @param type String
 */
fun _LinearLayout.creatFinancialUI(type : String){
    linearLayout {
        gravity = Gravity.CENTER_VERTICAL
        verticalLayout {
            textView {
                text = if (type == "1"){
                    "款项登记时间"
                }else{
                    "发票登记时间"
                }
                textColorInt = R.color.hint_text_color
                textSizeAuto = 24
            }.lparams(wrapContent, wrapContent)
            textView {
                text = if (type == "1"){
                    "款项审核时间"
                }else{
                    "发票审核时间"
                }
                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(155)
        }

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

        verticalLayout {
            textView {
                text = "状态"
                textColorInt = R.color.hint_text_color
                textSizeAuto = 24
            }.lparams(wrapContent, wrapContent)
            textView {
                visibility = View.GONE
                text = "计划编号"
                textColorInt = R.color.hint_text_color
                textSizeAuto = 24
            }.lparams(wrapContent, wrapContent)
        }.lparams(wrapContent, wrapContent){
            marginStart = autoSize(125)
        }
    }.lparams(matchParent, autoSize(92))
}