package cn.muchinfo.rma.view.base.future.orderDeatails

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.muchinfo.rma.R
import cn.muchinfo.rma.lifecycle.bindOptional
import cn.muchinfo.rma.view.autoWidget.toArrayList
import cn.muchinfo.rma.view.base.BaseActivity
import cn.muchinfo.rma.view.base.future.costs.OrderDetailData
import cn.muchinfo.rma.view.base.future.holds.HoldViewModel
import kotlinx.android.synthetic.main.order_detail.*

/**
 * 单据详情页面
 */
class OrderDetail : BaseActivity<OrderDetailModel>() {

    var data: ArrayList<OrderDetailData>? = null
    var titleName: String? = ""

    private var idTradeDetailList: RecyclerView? = null // 相关成交单列表

    companion object {
        fun start(context: Context, data: ArrayList<OrderDetailData>?, titleName: String?, goodsID: Int? = null, buyOrSell: Int? = 0) {
            val intent = Intent(context, OrderDetail::class.java)
            intent.putExtra("data", data)
            intent.putExtra("title_name", titleName)
            if (null != goodsID) {
                intent.putExtra("goodsid", goodsID)
            }
            if (null != buyOrSell) {
                intent.putExtra("buyorsell", buyOrSell)
            }
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.order_detail)
        if (intent != null) {
            viewModel.orderDetailList = intent.getParcelableArrayListExtra<OrderDetailData>("data")
            titleName = intent.getStringExtra("title_name") ?: resources.getString(R.string.details)
            // 相关成交单所需信息
            viewModel.goodsID = intent.getIntExtra("goodsid", 0)
            viewModel.buyOrSell = intent.getIntExtra("buyorsell", 0)

        }
        initViews()
        initData()
    }

    private fun initViews() {
        id_head.setTitle(titleName!!)

        val layoutManager = LinearLayoutManager(this@OrderDetail)
        id_order_detail_list?.layoutManager = layoutManager
        id_order_detail_list?.adapter = viewModel.getCostInfoAdapter(context = this)

        // 相关成交单列表
        idTradeDetailList = this.findViewById(R.id.id_order_relation_list)
        val tradeDetailAdapter = viewModel.getTradeDetailAdapter(this)
        idTradeDetailList?.layoutManager = LinearLayoutManager(this)
        idTradeDetailList?.adapter = tradeDetailAdapter
        viewModel.tradeDeatils.bindOptional(this) { data ->
            data?.toArrayList()?.let {
                (idTradeDetailList?.adapter as OrderDetailModel.TradeDetailAdapter).update(
                    it
                )
            }
        }
    }

    private fun initData() {
        if (viewModel.goodsID != 0) {
            viewModel.queryHedgeTradeDetails(viewModel.goodsID, viewModel.buyOrSell)
        }
    }
}