package com.doverfuelingsolutions.issp.view.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.api.SystemApi
import com.doverfuelingsolutions.issp.data.GlobalData
import com.doverfuelingsolutions.issp.databinding.FragmentNozzleBinding
import com.doverfuelingsolutions.issp.fusion.FusionManager
import com.doverfuelingsolutions.issp.utils.DFSToastUtil
import com.doverfuelingsolutions.issp.utils.StringUtil
import com.doverfuelingsolutions.issp.utils.log.DFSLog
import com.doverfuelingsolutions.issp.utils.sp.SPKeys
import com.doverfuelingsolutions.issp.utils.sp.SPUtil
import com.doverfuelingsolutions.issp.view.MainActivity
import com.doverfuelingsolutions.issp.view.adapter.ChooseListAdapter
import com.doverfuelingsolutions.issp.view.fragment.callback.RefreshNozzle
import com.doverfuelingsolutions.issp.view.util.ClickUtils
import com.scwang.smart.refresh.header.ClassicsHeader
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.io.IOException

class FragmentNozzle private constructor() : FragmentBasic(),RefreshNozzle{

    companion object {

        fun build() = FragmentNozzle()

    }

    override val title = StringUtil.get(R.string.query_by_nozzle)

//    private val colorForSignOrder = arrayListOf<Int>() // 用于标记该油枪是否有订单，有：深色 ； 无：浅色

    private var isFrist: Boolean = true
    private lateinit var binding: FragmentNozzleBinding
    private val isExistOrderMap = hashMapOf<String,Boolean>()
    private val chooseListAdapter = ChooseListAdapter(FusionManager.nozzles.map { it.physicalId.toString() },
        this::select,signOrderList = isExistOrderMap)

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

        FusionManager.onRefreshNozzleUi = this
        loadListData()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        if (!this::binding.isInitialized) {
            binding = DataBindingUtil.inflate(inflater, R.layout.fragment_nozzle, container, false)

            binding.nozzleList.layoutManager = GridLayoutManager(context, 4)
            binding.nozzleList.adapter = chooseListAdapter

            binding.smartRefreshLayout.setEnableLoadMore(false)
            binding.smartRefreshLayout.setRefreshHeader(ClassicsHeader(context))
            binding.smartRefreshLayout.setOnRefreshListener { handleNozzleRefresh() }
        }
        return binding.root
    }



    private fun handleNozzleRefresh() {
        lifecycleScope.launchWhenStarted {
            val resultNozzles = FusionManager.getPumpInfo()
            if (resultNozzles.success && resultNozzles.data != null) {
                binding.nozzleList.adapter?.notifyDataSetChanged()
                loadRemoteData()
                binding.smartRefreshLayout.finishRefresh(200, true, false)
            } else {
                binding.smartRefreshLayout.finishRefresh(200, false, true)
            }

        }
    }

    private fun select(physicalId: String) {
        if (ClickUtils.isFastClick()) return
        if (GlobalData.paymentId.get() == -1) {
            DFSToastUtil.fail(R.string.fail_get_pay_param_retry)
            GlobalScope.launch {
                SystemApi.paymentParam()
            }
            return
        }

        FusionManager.nozzles.find { it.physicalId.toString() == physicalId }?.let {
            (requireActivity() as MainActivity).fragmentRouter.push(FragmentOrderList.build(it.pumpId))
        }
    }

    private fun loadListData(){
        lifecycleScope.launchWhenStarted {
            /**
            if (GlobalData.isFrist) {
                val loadingDialog = loading(R.string.in_get_nozzle)
                loadRemoteData()
                loadingDialog.dismiss()
                GlobalData.isFrist = false
            } else {
                val loadingDialog = loading(R.string.in_get_nozzle)

                FusionManager.nozzles.forEach {
                    val orders = SPUtil.getOrderListByPump(it.pumpId)
                    isExistOrderMap[it.pumpId.toString()] = orders.isNotEmpty()
                }
                chooseListAdapter.notifyDataSetChanged()


                loadingDialog.dismiss()
            }
            */

            val loadingDialog = loading(R.string.in_get_nozzle)
            loadRemoteData()
            DFSLog.d("油枪页面加载完成")
            loadingDialog.dismiss()
        }
    }

    private suspend fun loadRemoteData() {
//        if(isRefreshing) return
//
//        isRefreshing = true
        FusionManager.nozzles.forEach {
            val result = FusionManager.getAllUnsettledOrder(it.pumpId)
            if (result.success && result.data != null) {
                synchronized(this) {
                    isExistOrderMap[it.pumpId.toString()] = result.data.isNotEmpty()
                    SPUtil.setOrderListByPump(it.pumpId,result.data)
                }

            }
        }

        chooseListAdapter.notifyDataSetChanged()
//        isRefreshing = false
    }

    override fun onRefreshNozzleUi(pump: Int,isExist: Boolean) {
        lifecycleScope.launchWhenStarted {
//            if (isExist) {
//                isExistOrderMap[pump.toString()] = isExist
//            } else {  // false 表示有消单，还需检测是否此 pump 已无订单
//                val result = FusionManager.getAllUnsettledOrder(pump)
//                isExistOrderMap[pump.toString()] = result.success && result.data != null && result.data.isNotEmpty()
//            }
//            chooseListAdapter.notifyDataSetChanged()


            isExistOrderMap[pump.toString()] = isExist
            chooseListAdapter.notifyDataSetChanged()
        }
    }


    /*
    private fun unsettledList(): ArrayList<Int>{
        ToastUtils.show(R.string.in_get_nozzle)
        val colorList = arrayListOf<Int>()
        lifecycleScope.launchWhenStarted {
            FusionManager.nozzles.forEach {
                val result = FusionManager.getAllUnsettledOrder(it.pumpId)
                if (result.success && result.data != null && result.data.isNotEmpty()) {
                    colorList.add(ResourcesCompat.getColor(DFSApplication.instance.applicationContext.resources, R.color.colorPrimaryTransparent, null))
                } else {
                    colorList.add(ResourcesCompat.getColor(DFSApplication.instance.applicationContext.resources, R.color.colorPrimary, null))
                }
            }
            chooseListAdapter.notifyDataSetChanged()
            ToastUtils.show(R.string.end_get_nozzle)
        }

        return colorList
    }

     */

}


