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

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.RecyclerView
import cn.muchinfo.rma.R
import cn.muchinfo.rma.business.future.FutureManager
import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.global.data.futureOrders.FutureEntrustData
import cn.muchinfo.rma.view.base.BaseViewModel
import cn.muchinfo.rma.view.base.future.enums.CustomerEnums
import cn.muchinfo.rma.view.base.future.interfaces.OnItemClickListener
import org.jetbrains.anko.backgroundColor
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

/**
 * 今日委托和今日可撤model
 */
class EntrustChildViewModel : BaseViewModel() {
    private var type: CustomerEnums.EntrustType? = CustomerEnums.EntrustType.TODAY_CANCEL_TYPE // 默认进入可撤

    val entrustLiveData: MutableLiveData<List<FutureEntrustData>> = MutableLiveData() // 加载状态控制
    val noDataLiveData: MutableLiveData<Boolean> = MutableLiveData() // 如果没有数据

    var list: ArrayList<FutureEntrustData>? = null // 数据
    var onItemClickListener: OnItemClickListener? = null // item点击事件
    var currentEntrustData: FutureEntrustData? = null // 当前选择的item对应的数据


    /**
     * 获取配置器。
     */
    fun getAdapter(): RecyclerView.Adapter<EntrustAdapter.EntrustHolder> {
        return EntrustAdapter(context)
    }

    /**     * 通用的适配器。
     */
    inner class EntrustAdapter(context: Context?) : RecyclerView.Adapter<EntrustAdapter.EntrustHolder>() {
        private var list: ArrayList<FutureEntrustData>? = null
        private var inflater: LayoutInflater? = null
        private var context: Context? = null
        private var selectedColor: Int = 0

        init {
            this.list = GlobalDataCollection.instance?.futureHisEntrustData
            this.inflater = LayoutInflater.from(context)
            this.context = context
            selectedColor = context?.getColor(R.color.p_list_item_select_color)!!
        }

        override fun getItemCount(): Int {
            return list?.size ?: 0
        }

        fun update(list: ArrayList<FutureEntrustData>?) {
            this.list = list
            notifyDataSetChanged()
        }

        inner class EntrustHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) {
            var idGoodsName = itemView?.findViewById<TextView>(R.id.id_goods_name)
            var idStatus = itemView?.findViewById<TextView>(R.id.id_status)
            var idDate = itemView?.findViewById<TextView>(R.id.id_date)
            var idEntrustType = itemView?.findViewById<TextView>(R.id.id_entrust_type)
            var idEntrustNum = itemView?.findViewById<TextView>(R.id.id_entrust_num)
            var idEntrustPrice = itemView?.findViewById<TextView>(R.id.id_entrust_price)
            var idEntrustPl = itemView?.findViewById<TextView>(R.id.id_entrust_pl)

            var idChart = itemView?.findViewById<TextView>(R.id.id_chart)
            var idEntrustDetail = itemView?.findViewById<TextView>(R.id.id_entrust_detail)
            var idCancel = itemView?.findViewById<TextView>(R.id.id_cancel)
        }

        override fun onBindViewHolder(entrust: EntrustHolder, position: Int) {
            entrust.itemView.tag = list?.get(position)

            entrust.idGoodsName?.text = list?.get(position)?.goodsname
//            entrust.idStatus?.text = list?.get(position)?.status
            entrust.idEntrustType?.text = getType(list?.get(position)!!)
            entrust.idDate?.text = getTime(list?.get(position)!!)
            entrust.idEntrustPrice?.text = list?.get(position)?.orderprice.toString()
            entrust.idEntrustNum?.text = list?.get(position)?.orderqty.toString()
//            entrust.idEntrustPl?.text = list?.get(position)?.pl.toString()

            // 下面三个按钮的点击事件
            entrust.idChart?.tag = list?.get(position)
            entrust.idEntrustDetail?.tag = list?.get(position)
            entrust.idCancel?.tag = list?.get(position)
            entrust.idChart?.setOnClickListener {

            }
            entrust.idEntrustDetail?.setOnClickListener {

            }
            entrust.idCancel?.setOnClickListener {

            }

            if (list?.get(position)?.selected == true) {
                entrust.idChart?.visibility = View.VISIBLE
                entrust.idEntrustDetail?.visibility = View.VISIBLE
                entrust.idCancel?.visibility = View.VISIBLE
                entrust.itemView.backgroundColor = selectedColor
            } else if(list?.get(position)?.selected == false) {
                entrust.idChart?.visibility = View.GONE
                entrust.idEntrustDetail?.visibility = View.GONE
                entrust.idCancel?.visibility = View.GONE
                entrust.itemView.backgroundColor = 0
            }

            // 点击item事件
            entrust.itemView.setOnClickListener {
                clickItem(it)
                onItemClickListener?.onClick(it)
            }

        }

        fun getType(_data: FutureEntrustData): String {
            val buyOrSell = _data.buyorsell
            val channelBuildType = _data.channelbuildtype
            return ""
        }

        fun getTime(_data: FutureEntrustData): String {
            val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+08:00", Locale.CHINA)
            val sdf1 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
            return sdf1.format(sdf.parse(_data.ordertime)!!)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EntrustHolder {
            return EntrustHolder(inflater?.inflate(R.layout.entrust_item, parent, false))
        }

        private fun clickItem(view: View) {
            currentEntrustData = view.tag as FutureEntrustData? // 临时存储当前点击item

            // 选择i
            list?.forEach { itemValue ->
                if (itemValue.goodsid == currentEntrustData?.goodsid) {
                    itemValue.selected = !itemValue.selected
                } else {
                    itemValue.selected = false
                }
            }

            // 刷新数据
            notifyDataSetChanged()
        }
    }

    //region 网络请求

    /**
     * 查询
     */
    fun queryOrder() {
        FutureManager().queryErmcpEntrustDetails { isSuccess, respData, _ ->
            if (isSuccess && !respData!!.isNullOrEmpty()) { // 查询成功
                val temps = arrayListOf<FutureEntrustData>()
                respData.filter {
                    // 如果是TODAY_CANCEL_TYPE 那就channelinnerorderstatus == 5，如果是TODAY_TYPE，那么channelinnerorderstatus != 5
                    (it.channelinnerorderstatus == 5 && type == CustomerEnums.EntrustType.TODAY_CANCEL_TYPE) ||
                            (it.channelinnerorderstatus != 5 && type == CustomerEnums.EntrustType.TODAY_TYPE)
                }.forEach {
                    temps.add(it)
                }
                entrustLiveData.value = temps
            } else { // 查询失败
                noDataLiveData.value = true
            }
        }
    }

    //endregion
}