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

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.ChangeLogData
import cn.muchinfo.rma.global.data.MiddleGoodsData
import cn.muchinfo.rma.global.data.WrStandardData
import cn.muchinfo.rma.global.isBlankString
import cn.muchinfo.rma.global.toPercentage
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.commodity.viewholder.ChangeLogViewHolder
import cn.muchinfo.rma.view.base.home.contract.viewItemUI
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 HedgeSpeciesDetailsActivity : BaseActivity<CommodityInformationViewModel>(){

    /**
     * 数据
     */
    val data: MiddleGoodsData by lazy {
        intent.getParcelableExtra<MiddleGoodsData>("data") as MiddleGoodsData
    }

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

    /** 商品详情 **/
    private val goodsDetailsUI by lazy { GoodsDetailsUI(this,viewModel,data) }
    /** 变更记录 **/
    private val changeRecordUI by lazy { ChangeRecordUI(this,viewModel, data) }
    private val tabsArray: List<String> by lazy {
        arrayListOf(
            "商品详情", "变更记录"
        )
    }

    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 goodsDetailsUI.root.apply {
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    1 -> {
                        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 = "套保品种详情"
                }
            }

            linearLayout {
                gravity = Gravity.CENTER_VERTICAL
//                        rma_yellow_text_color
                background = resources.getDrawable(R.color.rma_pass_status)//rma_pass_status已通过背景色

                imageView {
                    if (data.isvalid == "1"){
                        imageResource = R.mipmap.rma_pass_status
                    }else{
                        imageResource = R.mipmap.rma_wait_status
                    }
                }.lparams(autoSize(38), autoSize(38)) {
                    marginStart = autoSize(37)
                }
                textView {
                    if (data.isvalid == "1"){
                        text = "正常"
                    }else{
                        text = "无效"
                    }
                    textSizeAuto = 31
                    textColorInt = R.color.rma_yellow_text_color
                }.lparams(wrapContent, wrapContent) {
                    marginStart = autoSize(20)
                }
            }.lparams(matchParent, autoSize(60))

            tabSegment {
                segment = this
                background = resources.getDrawable(R.color.white)
                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(80))

            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 CommodityInformationViewModel
 * @property root _FrameLayout
 * @constructor
 */
class GoodsDetailsUI(
    private val activity : AppCompatActivity,
    private val viewModel: CommodityInformationViewModel,
    private val data : MiddleGoodsData
){

    init {
        viewModel.queryMiddleGoodsDetailList(data.middlegoodsid ?: "") {
            viewModel.avalidGoodsDetailsData.postValue(this)
        }
    }
    val root = _FrameLayout(activity).apply {
        verticalLayout {
            contentItem(itemTile = "套保品种名称",itemContent = data.middlegoodsname ?: "")
            viewItemUI()
            contentItem(itemTile = "套保品种代码",itemContent = data.middlegoodscode ?: "")
            viewItemUI()
            contentItem(itemTile = "单位",itemContent = data.enumdicname ?: "")
            viewItemUI()
            contentItem(itemTile = "套保比例",itemContent = data.needhedgeratio?.toPercentage() ?: "")
            viewModel.avalidGoodsDetailsData.bindOptional(context){list ->
                list?.forEach {
                    viewItemUI()
                    contentItem(itemTile = "期货品种" + list.indexOf(it).plus(1),itemContent = it.goodsgroupname?.isBlankString() ?: "")
                    contentItem(itemTile = "期货品种系数" + list.indexOf(it).plus(1),itemContent = it.convertratio?.toPercentage() ?: "")
                }
            }
            viewItemUI()

//            if (data.remark?.isNotEmpty() == true){
//                linearLayout {
//                    gravity = Gravity.CENTER_VERTICAL
//                    background = resources.getDrawable(R.color.white)
//                    linearLayout {
//                        gravity = Gravity.CENTER_VERTICAL
//                        textView {
//                            text = "备注"
//                            textSizeAuto = 31
//                            textColorInt = R.color.rma_gray_color
//                        }.lparams(wrapContent, wrapContent){
//                            marginStart = autoSize(35)
//                        }
//                    }.lparams(autoSize(250), autoSize(120))
//
//                    textView {
//                        text = data.remark
//                        textSizeAuto = 31
//                        textColorInt = R.color.rma_black_33
//                    }.lparams(wrapContent, wrapContent){
//                        marginStart = autoSize(35)
//                        marginEnd = autoSize(35)
//                    }
//
//                }.lparams(matchParent, autoSize(240))
//            }

        }
    }
}

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

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

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

    init {
        viewModel.queryChangeLog(RelatedId = "")
    }

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

            linearLayout {
                textView {
                    gravity = Gravity.CENTER
                    text = "修改时间"
                    textColorInt = R.color.hint_text_color
                    textSizeAuto = 23
                }.lparams(autoSize(225), autoSize(100))
                textView {
                    gravity = Gravity.CENTER
                    text = "修改前套保比例"
                    textColorInt = R.color.hint_text_color
                    textSizeAuto = 23
                }.lparams(autoSize(225), autoSize(100))
                textView {
                    gravity = Gravity.CENTER
                    text = "修改后套保比例"
                    textColorInt = R.color.hint_text_color
                    textSizeAuto = 23
                }.lparams(autoSize(225), autoSize(100))
                textView {
                    gravity = Gravity.CENTER
                    text = "修改人"
                    textColorInt = R.color.hint_text_color
                    textSizeAuto = 23
                }.lparams(autoSize(225), autoSize(100))
            }.lparams(matchParent, autoSize(100))

            statusLayout(contentBlock = {
                statusLayout = this
//                bindTaskStatus(viewModule.status)
                swipeToLoadLayout {
                    swipeToLayout = this
                    setEnableRefresh(true)
                    setEnableLoadMore(false)
                    setOnRefreshListener {
                        viewModel.queryChangeLog(RelatedId = "")
                    }
                    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)
                }
            }
        }
    }
}

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