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

import android.content.Intent
import android.content.res.Configuration
import android.content.res.Configuration.ORIENTATION_LANDSCAPE
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.ContractData
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

/**
 * 现货合同页面
 * @property segment QMUITabSegment
 * @property selectedTabIndex Int
 * @property viewPager ViewPager
 * @property tabsArray List<String>
 * @property unSubmitUI UnSubmitUI
 * @property toAuditUI ToAuditUI
 * @property performanceUI PerformanceUI
 * @property finishUI FinishUI
 * @property pagerAdapter PagerAdapter
 */
class ContractActivity : BaseActivity<ContractViewModel>() {


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

    private val tabsArray: List<String> by lazy {
        arrayListOf("未提交", "待审核", "履约中", "已完成")
    }
    //未提交
    private val unSubmitUI : UnSubmitUI by lazy {
        UnSubmitUI(this,viewModel)
    }
    //待审核
    private val toAuditUI by lazy { ToAuditUI(this,viewModel) }
    //履约中
    private val performanceUI by lazy { PerformanceUI(this,viewModel) }
    //已完成
    private val finishUI by lazy { FinishUI(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 unSubmitUI.root.apply {
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    1 -> {
                        return toAuditUI.root.apply {
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    2 -> {
                        return performanceUI.root.apply {
                            container.addView(
                                this,
                                ViewGroup.LayoutParams(matchParent, matchParent)
                            )
                        }
                    }
                    3 -> {
                        return finishUI.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 onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        val orientation = newConfig.orientation
        if (orientation == ORIENTATION_LANDSCAPE) {
//            Log.i(FragmentActivity.TAG, "-------------横屏-------------")

        } else {
//            Log.i(FragmentActivity.TAG, "-------------竖屏-------------")

        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.queryContract(QueryType = "1")
        viewModel.queryContract(QueryType = "2")
        viewModel.queryContract(QueryType = "3")
        viewModel.queryContract(QueryType = "4")
//        when (selectedTabIndex) {
//            0 -> {
//
//            }
//            1 -> {
//
//            }
//            3 -> {
//
//            }
//            4 -> {
//
//            }
//        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        verticalLayout {
            frameLayout {
//                viewModel.isLandscape.bindOptional(context){
//                    if (it == true){
//                        lparams(matchParent, autoSize(120,ScreenUtils.getScreenWidth()))
//                    }else{
//                        lparams(matchParent, autoSize(120,900))
//                    }
//                }

                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("operationtype","1")
                            intent.putExtra("data",ContractData())
                            intent.setClass(context,AddContractActivity::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))
//            viewModel.setFalseData()
            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)

        }
    }

}

/**
 * 未提交
 */
class UnSubmitUI(
    private val activity: AppCompatActivity,
    private val viewModel: ContractViewModel
) {

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

    private val unSubmitAdapter: BaseAdapter<ContractData, ContractDataViewHolder> = BaseAdapter { _, _ -> ContractDataViewHolder(activity, viewModel,"1") }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            viewModel.queryContract(QueryType = "1")
            creatContractHeadUI()

            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.queryContract(QueryType = "1")
                    }
                    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()
                    }
                    statusLayout.showSuccess()
                    unSubmitAdapter.setNewData(it)
                }
            }
        }
    }
}


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

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

    private val unSubmitAdapter: BaseAdapter<ContractData, ContractDataViewHolder> = BaseAdapter { _, _ -> ContractDataViewHolder(activity, viewModel,"2") }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            viewModel.queryContract(QueryType = "2")
            creatContractHeadUI()

            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.queryContract(QueryType = "2")
                    }
                    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()
                    }
                    statusLayout.showSuccess()
                    unSubmitAdapter.setNewData(it)
                }
            }
        }
    }
}

/**
 * 履约中
 */
class PerformanceUI(
    private val activity: AppCompatActivity,
    private val viewModel: ContractViewModel
) {

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

    private val unSubmitAdapter: BaseAdapter<ContractData, ContractDataViewHolder> = BaseAdapter { _, _ -> ContractDataViewHolder(activity, viewModel,"3") }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            viewModel.queryContract(QueryType = "3")
            creatContractHeadUI()

            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.queryContract(QueryType = "3")
                    }
                    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.performanceList.bindOptional(context){
                if (it?.isEmpty() == true || it?.size == 0){
                    statusLayout.showEmpty()
                }else {
                    if (swipeToLayout.getIsRefreshing()){
                        swipeToLayout.finishRefresh()
                    }
                    statusLayout.showSuccess()
                    unSubmitAdapter.setNewData(it)
                }
            }
        }
    }
}

/**
 * 已完成
 */
class FinishUI(
    private val activity: AppCompatActivity,
    private val viewModel: ContractViewModel
){

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

    private val unSubmitAdapter: BaseAdapter<ContractData, ContractDataViewHolder> = BaseAdapter { _, _ -> ContractDataViewHolder(activity, viewModel,"4") }

    val root = _FrameLayout(activity).apply {
        verticalLayout {
            viewModel.queryContract(QueryType = "4")
            creatContractHeadUI()

            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.queryContract(QueryType = "4")
                    }
                    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.finishList.bindOptional(context){
                if (it?.isEmpty() == true || it?.size == 0){
                    statusLayout.showEmpty()
                }else {
                    if (swipeToLayout.getIsRefreshing()){
                        swipeToLayout.finishRefresh()
                    }
                    statusLayout.showSuccess()
                    unSubmitAdapter.setNewData(it)
                }
            }
        }
    }
}

fun _LinearLayout.creatContractHeadUI(){
    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 {
            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)
        }

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