package cn.muchinfo.rma.view.base.procurement

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.ViewEnumUtils
import cn.muchinfo.rma.global.data.BusinessData
import cn.muchinfo.rma.global.data.ChangeLogData
import cn.muchinfo.rma.global.data.ContractData
import cn.muchinfo.rma.global.data.FinancialManageData
import cn.muchinfo.rma.global.isBlankString
import cn.muchinfo.rma.global.isShowTimeString
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.business.BusinessManagementViewholder
import cn.muchinfo.rma.view.base.home.commodity.viewholder.ChangeLogViewHolder
import cn.muchinfo.rma.view.base.home.contract.viewItemUI
import cn.muchinfo.rma.view.base.procurement.detailsviewholder.ChangeRecordViewHolder
import cn.muchinfo.rma.view.base.procurement.detailsviewholder.InvoiceRecordViewHolder
import cn.muchinfo.rma.view.base.procurement.detailsviewholder.PriceRecordViewHolder
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 ContractDetailActivity : BaseActivity<ProcurementViewModel>() {

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

    private val data by lazy {
        intent.getParcelableExtra<ContractData>("data") as ContractData
    }

    private val tabsArray: List<String> by lazy {
        arrayListOf("合同详情", "点价登记", "结算登记", "款项登记", "发票登记", "变更记录")
    }

    //合同详情
    private val contractDetailsUI by lazy { ContractDetailsUI(this, viewModel, data) }

    //点价登记
    private val priceRecordUI by lazy { PriceRecordUI(this, viewModel, data) }

    //结算登记
    private val settlementRecordUI by lazy { SettlementRecordUI(this, viewModel, data) }

    //款项登记
    private val paymentRecordUI by lazy { PaymentRecordUI(this, viewModel, data) }

    //发票登记
    private val invoiceRecordUI by lazy { InvoiceRecordUI(this, viewModel, data) }

    //变更登记
    private val changeRecordUI by lazy { ChangeRecordUI(this, viewModel, data) }

    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 contractDetailsUI.root.apply {
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    1 -> { // 待审核
                        return priceRecordUI.root.apply {
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    2 -> {
                        return settlementRecordUI.root.apply {
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    3 -> {
                        return paymentRecordUI.root.apply {
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    4 -> {
                        return invoiceRecordUI.root.apply {
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    5 -> {
                        return changeRecordUI.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 onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        verticalLayout {
            topBar {
                // 返回
                commonLeftButton()
                commonTitle {
                    text = "合同详情"
                }
            }

            // 分页框
            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(14f), ConvertUtils.sp2px(14f))
            }.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)


        }
    }

}

/**
 * 合同详情
 * @property activity AppCompatActivity
 * @property viewModel ProcurementViewModel
 * @property data ContractData
 * @property root _FrameLayout
 * @constructor
 */
class ContractDetailsUI(
    private val activity: AppCompatActivity,
    private val viewModel: ProcurementViewModel,
    private val data: ContractData
) {

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            scrollView {
                verticalLayout {
                    contentItem(itemTile = ViewEnumUtils.getContractType(data.contracttype ?: "") + "-" + ViewEnumUtils.getPriceType(data.pricetype ?: "") + "合同",itemContent = data.contractno?.isBlankString() ?: "")
                    viewItemUI()
                    contentItem(itemTile = if (data.contracttype == "1") { "销售方" }else{ "采购方" } ,itemContent = if (data.contracttype == "1") { data?.sellusername ?: "" }else{ data?.buyusername ?: "" })
                    viewItemUI()
                    contentItem(itemTile = "现货品种",itemContent = data.deliverygoodsname ?: "")
                    viewItemUI()
                    contentItem(itemTile = "产品类型",itemContent = ViewEnumUtils.getProductType(data.producttype ?: ""))
                    viewItemUI()
                    contentItem(itemTile = "产品规格",itemContent = data?.spotgoodsdesc ?: "")
                    viewItemUI()
                    contentItem(itemTile = "定价类型",itemContent = ViewEnumUtils.getPriceType(data.pricetype ?: ""))
                    viewItemUI()
                    contentItem(itemTile = "期货合约",itemContent = data.goodscode ?: "")
                    viewItemUI()
                    contentItem(itemTile = "升贴水",itemContent = data.pricemove ?: "")
                    viewItemUI()
                    contentItem(itemTile = "标仓系数",itemContent = data.convertfactor ?: "")
                    viewItemUI()
                    contentItem(itemTile = "点价期",itemContent = data.startdate?.isShowTimeString("MM-dd") + "~" + data.enddate?.isShowTimeString("MM-dd"))
                    viewItemUI()
                    contentItem(itemTile = "点价期",itemContent = data.deliverystartdate?.isShowTimeString("MM-dd") + "~" + data.deliveryenddate?.isShowTimeString("MM-dd"))
                    viewItemUI()
                    contentItem(itemTile = "合同量",itemContent = data.qty ?: "" + data.enumdicname ?: "")
                    viewItemUI()
                    contentItem(itemTile = "初始保证金",itemContent = data.margin ?: "")
                }
            }
        }
    }
}
//合同详情的item
fun _LinearLayout.contentItem(itemTile : String,itemContent : String){
    linearLayout {
        gravity = Gravity.CENTER_VERTICAL
        background = resources.getDrawable(R.color.white)
        linearLayout {
            gravity = Gravity.CENTER_VERTICAL
            textView {
                text = itemTile
                textSizeAuto = 31
                textColorInt = R.color.rma_gray_color
            }.lparams(wrapContent, wrapContent){
                marginStart = autoSize(35)
            }
        }.lparams(autoSize(250), autoSize(120))

        textView {
            text = itemContent
            textSizeAuto = 31
            textColorInt = R.color.rma_black_33
        }.lparams(wrapContent, wrapContent){
            marginStart = autoSize(35)
        }

    }.lparams(matchParent, autoSize(120))
}

/**
 * 点价记录
 * @property activity AppCompatActivity
 * @property viewModel ProcurementViewModel
 * @property data ContractData
 * @constructor
 */
class PriceRecordUI(
    private val activity: AppCompatActivity,
    private val viewModel: ProcurementViewModel,
    private val data: ContractData
) {

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

    private val unSubmitAdapter: BaseAdapter<BusinessData, PriceRecordViewHolder> = BaseAdapter { _, _ -> PriceRecordViewHolder(activity,"1") }

    init {
        viewModel.queryBusinessDJ(relatedid = data.spotcontractid ?: "")
    }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            creatContrctTitleUI(type = "1")
            statusLayout(contentBlock = {
                statusLayout = this
//                bindTaskStatus(viewModule.status)
                swipeToLoadLayout {
                    swipeToLayout = this
                    setEnableRefresh(true)
                    setEnableLoadMore(false)
                    setOnRefreshListener {
                        viewModel.queryBusinessDJ(relatedid = data.spotcontractid ?: "")
                    }
                    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.somePriceList.bindOptional(context){
                if (it?.isEmpty() == true || it?.size == 0){
                    statusLayout.showEmpty()
                }else {
                    if (swipeToLayout.getIsRefreshing()){
                        swipeToLayout.finishRefresh()
                    }
                    statusLayout.showSuccess()
                    unSubmitAdapter.setNewData(it)
                }
            }
        }
    }
}

/**
 * 结算记录
 * @property activity AppCompatActivity
 * @property viewModel ProcurementViewModel
 * @property data ContractData
 * @property root _FrameLayout
 * @constructor
 */
class SettlementRecordUI(
    private val activity: AppCompatActivity,
    private val viewModel: ProcurementViewModel,
    private val data: ContractData
) {

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

    private val unSubmitAdapter: BaseAdapter<BusinessData, PriceRecordViewHolder> = BaseAdapter { _, _ -> PriceRecordViewHolder(activity,"2") }

    init {
        viewModel.queryBusinessJS(relatedid = data.spotcontractid ?: "")
    }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            creatContrctTitleUI(type = "2")

            statusLayout(contentBlock = {
                statusLayout = this
//                bindTaskStatus(viewModule.status)
                swipeToLoadLayout {
                    swipeToLayout = this
                    setEnableRefresh(true)
                    setEnableLoadMore(false)
                    setOnRefreshListener {
                        viewModel.queryBusinessJS(relatedid = data.spotcontractid ?: "")
                    }
                    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.settlementList.bindOptional(context){
                if (it?.isEmpty() == true || it?.size == 0){
                    statusLayout.showEmpty()
                }else {
                    if (swipeToLayout.getIsRefreshing()){
                        swipeToLayout.finishRefresh()
                    }
                    statusLayout.showSuccess()
                    unSubmitAdapter.setNewData(it)
                }
            }
        }
    }
}

/**
 * 款项记录
 * @property activity AppCompatActivity
 * @property viewModel ProcurementViewModel
 * @property data ContractData
 * @property root _FrameLayout
 * @constructor
 */
class PaymentRecordUI(
    private val activity: AppCompatActivity,
    private val viewModel: ProcurementViewModel,
    private val data: ContractData
) {

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

    private val unSubmitAdapter: BaseAdapter<FinancialManageData, InvoiceRecordViewHolder> = BaseAdapter { _, _ -> InvoiceRecordViewHolder(activity,"1") }

    init {
        viewModel.queryBusinessKx(relatedid = data.spotcontractid ?: "")
    }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            creatContrctTitleUI(type = "3")

            statusLayout(contentBlock = {
                statusLayout = this
//                bindTaskStatus(viewModule.status)
                swipeToLoadLayout {
                    swipeToLayout = this
                    setEnableRefresh(true)
                    setEnableLoadMore(false)
                    setOnRefreshListener {
                        viewModel.queryBusinessKx(relatedid = data.spotcontractid ?: "")
                    }
                    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.paymentList.bindOptional(context){
                if (it?.isEmpty() == true || it?.size == 0){
                    statusLayout.showEmpty()
                }else {
                    if (swipeToLayout.getIsRefreshing()){
                        swipeToLayout.finishRefresh()
                    }
                    statusLayout.showSuccess()
                    unSubmitAdapter.setNewData(it)
                }
            }
        }
    }
}

/**
 * 发票记录
 * @property activity AppCompatActivity
 * @property viewModel ProcurementViewModel
 * @property data ContractData
 * @property root _FrameLayout
 * @constructor
 */
class InvoiceRecordUI(
    private val activity: AppCompatActivity,
    private val viewModel: ProcurementViewModel,
    private val data: ContractData
) {


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

    private val unSubmitAdapter: BaseAdapter<FinancialManageData, InvoiceRecordViewHolder> = BaseAdapter { _, _ -> InvoiceRecordViewHolder(activity,"2") }

    init {
        viewModel.queryBusinessFp(relatedid = data.spotcontractid ?: "")
    }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            creatContrctTitleUI(type = "4")

            statusLayout(contentBlock = {
                statusLayout = this
//                bindTaskStatus(viewModule.status)
                swipeToLoadLayout {
                    swipeToLayout = this
                    setEnableRefresh(true)
                    setEnableLoadMore(false)
                    setOnRefreshListener {
                        viewModel.queryBusinessFp(relatedid = data.spotcontractid ?: "")
                    }
                    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.paymentList.bindOptional(context){
                if (it?.isEmpty() == true || it?.size == 0){
                    statusLayout.showEmpty()
                }else {
                    if (swipeToLayout.getIsRefreshing()){
                        swipeToLayout.finishRefresh()
                    }
                    statusLayout.showSuccess()
                    unSubmitAdapter.setNewData(it)
                }
            }
        }
    }
}

/**
 * 变更记录
 * @property activity AppCompatActivity
 * @property viewModel ProcurementViewModel
 * @property data ContractData
 * @property root _FrameLayout
 * @constructor
 */
class ChangeRecordUI(
    private val activity: AppCompatActivity,
    private val viewModel: ProcurementViewModel,
    private val data: ContractData
) {

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

    private val spotVarietiesNormalAdapter: BaseAdapter<ChangeLogData, ChangeRecordViewHolder> = BaseAdapter { _, _ -> ChangeRecordViewHolder(activity) }

    init {
        viewModel.queryChangeLog(RelatedId = data.spotcontractid ?: "")
    }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            linearLayout {
                gravity = Gravity.CENTER_HORIZONTAL
                textView {
                    gravity = Gravity.CENTER
                    text = "变更时间"
                    textColorInt = R.color.hint_text_color
                    textSizeAuto = 24
                }.lparams(autoSize(300), autoSize(70))

                textView {
                    gravity = Gravity.CENTER
                    text = "类型"
                    textColorInt = R.color.hint_text_color
                    textSizeAuto = 24
                }.lparams(autoSize(300), autoSize(70))

                textView {
                    gravity = Gravity.CENTER
                    text = "操作人"
                    textColorInt = R.color.hint_text_color
                    textSizeAuto = 24
                }.lparams(autoSize(300), autoSize(70))
            }.lparams(matchParent, autoSize(70))


            statusLayout(contentBlock = {
                statusLayout = this
//                bindTaskStatus(viewModule.status)
                swipeToLoadLayout {
                    swipeToLayout = this
                    setEnableRefresh(true)
                    setEnableLoadMore(false)
                    setOnRefreshListener {
                        viewModel.queryChangeLog(RelatedId = data.spotcontractid ?: "")
                    }
                    setEnableScrollContentWhenLoaded(false)
                    setEnableLoadMoreWhenContentNotFull(false)
                    recyclerView {
                        background = resources.getDrawable(R.color.white)
                        adapter = spotVarietiesNormalAdapter
                    }.lparams(matchParent, matchParent)
                }
            }, emptyBlock = {
                emptyView(hint = resources.getString(R.string.now_no_data))
            }).lparams(matchParent, matchParent)

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

        }
    }
}

/**
 *
 * @receiver _LinearLayout
 * @param type String 1 点价记录 2 结算记录 3 款项记录 4 发票记录
 */
fun _LinearLayout.creatContrctTitleUI(type: String) {
    linearLayout {

        verticalLayout {
            gravity = Gravity.CENTER_HORIZONTAL
            textView {
                when (type) {
                    "1" -> {
                        text = "点价登记时间"
                    }
                    "2" -> {
                        text = "结算登记时间"
                    }
                    "3" -> {
                        text = "款项登记时间"
                    }
                    "4" -> {
                        text = "发票登记时间"
                    }
                }
                textColorInt = R.color.hint_text_color
                textSizeAuto = 24
            }.lparams(wrapContent, wrapContent) {
                topMargin = autoSize(20)
            }
            textView {
                when (type) {
                    "1" -> {
                        text = "点价审核时间"
                    }
                    "2" -> {
                        text = "结算审核时间"
                    }
                    "3" -> {
                        text = "款项审核时间"
                    }
                    "4" -> {
                        text = "发票审核时间"
                    }
                }
                textColorInt = R.color.hint_text_color
                textSizeAuto = 24
            }.lparams(wrapContent, wrapContent)
        }.lparams(autoSize(315), autoSize(92))

        verticalLayout {
            gravity = Gravity.CENTER_HORIZONTAL
            textView {
                when (type) {
                    "1" -> {
                        text = "点价价格"
                    }
                    "2" -> {
                        text = "结算项"
                    }
                    "3" -> {
                        text = "款项类型"
                    }
                    "4" -> {
                        text = "发票类型"
                    }
                }
                textColorInt = R.color.hint_text_color
                textSizeAuto = 24
            }.lparams(wrapContent, wrapContent) {
                topMargin = autoSize(20)
            }
            textView {
                when (type) {
                    "1" -> {
                        text = "升贴水"
                    }
                    "2" -> {
                        text = "值"
                    }
                    "3" -> {
                        text = "金额"
                    }
                    "4" -> {
                        text = "金额"
                    }
                }
                textColorInt = R.color.hint_text_color
                textSizeAuto = 24
            }.lparams(wrapContent, wrapContent)
        }.lparams(autoSize(195), autoSize(92))

        verticalLayout {
            gravity = Gravity.CENTER_HORIZONTAL
            textView {
                when (type) {
                    "1" -> {
                        text = "点价数量"
                    }
                    "2" -> {
                        text = "申请人"
                    }
                    "3" -> {
                        text = "金额"
                    }
                    "4" -> {
                        text = "金额"
                    }
                }
                textColorInt = R.color.hint_text_color
                textSizeAuto = 24
            }.lparams(wrapContent, wrapContent) {
                topMargin = autoSize(20)
            }
            textView {
                when (type) {
                    "1" -> {
                        text = "点价金额"
                    }
                    "2" -> {
                        text = "审核人"
                    }
                    "3" -> {
                        text = "审核人"
                    }
                    "4" -> {
                        text = "审核人"
                    }
                }
                textColorInt = R.color.hint_text_color
                textSizeAuto = 24
            }.lparams(wrapContent, wrapContent)
        }.lparams(autoSize(195), autoSize(92))

        verticalLayout {
            gravity = Gravity.CENTER_HORIZONTAL
            textView {
                if (type == "1") {
                    text = "申请人/审核人"
                } else {
                    text = "状态"
                }
                textColorInt = R.color.hint_text_color
                textSizeAuto = 24
            }.lparams(wrapContent, wrapContent) {
                topMargin = autoSize(20)
            }
            textView {
                if (type == "1") {
                    visibility = View.VISIBLE
                } else {
                    visibility = View.GONE
                }
                text = "状态"
                textColorInt = R.color.hint_text_color
                textSizeAuto = 24
            }.lparams(wrapContent, wrapContent)
        }.lparams(autoSize(195), autoSize(92))
    }.lparams(matchParent, autoSize(92))
}