package com.grkj.iscs.view.fragment

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.PointF
import android.widget.ImageView
import com.grkj.iscs.R
import com.grkj.iscs.databinding.FragmentWorkshopBinding
import com.grkj.iscs.model.Constants
import com.grkj.iscs.model.bo.PageChangeBO
import com.grkj.iscs.model.vo.ticket.WorkstationTicketListRespVO
import com.grkj.iscs.util.ToastUtils
import com.grkj.iscs.view.base.BaseMvpFragment
import com.grkj.iscs.view.iview.IWorkshopView
import com.grkj.iscs.view.presenter.WorkshopPresenter
import com.grkj.iscs.view.widget.CustomMarkLayer
import com.onlylemi.mapview.library.MapViewListener
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder
import java.io.IOException

/**
 * 车间岗位页
 */
class WorkshopFragment(val changePage: (PageChangeBO) -> Unit) :
    BaseMvpFragment<IWorkshopView, WorkshopPresenter, FragmentWorkshopBinding>() {

    private lateinit var jobStatisticList: MutableList<JobStatistics>
    private var markLayer: CustomMarkLayer? = null
    private val mPointList = mutableListOf(
        CustomPoint(PointF(600f, 260f), "R&R", 8, mutableListOf()),
        CustomPoint(PointF(800f, 480f), "CCO", 7, mutableListOf())
    )

    override val viewBinding: FragmentWorkshopBinding
        get() = FragmentWorkshopBinding.inflate(layoutInflater)

    override fun initView() {
        jobStatisticList = mutableListOf(
            JobStatistics(Constants.SOP_REPAIR, 0),
            JobStatistics(Constants.SOP_PRE_MAINTENANCE, 0),
            JobStatistics(Constants.SOP_CHANGE_SHIFTS, 0),
            JobStatistics(Constants.SOP_CLEAN, 0),
            JobStatistics(Constants.SOP_SWITCH_PRODUCT, 0)
        )
        
        mBinding?.rvStatistics?.adapter = object : CommonAdapter<JobStatistics>(requireActivity(), R.layout.item_rv_job_management, jobStatisticList) {
            override fun convert(holder: ViewHolder, statistic: JobStatistics, position: Int) {
                holder.getView<ImageView>(R.id.iv).setImageResource(statistic.sopType.icon)
                holder.setText(R.id.tv_name,
                    if (statistic.count == 0) statistic.sopType.title
                    else "${statistic.sopType.title}（${statistic.count}）"
                )
            }
        }

        initMap()
        refreshPage()
    }

    fun refreshPage() {
        presenter?.getWorkstationTicketList {
            if (it == null) {
                return@getWorkstationTicketList
            }
            jobStatisticList.forEach { itJob ->
                itJob.count = it.count { it.ticketType == itJob.sopType.type.toString() }
            }
            mPointList.forEach { itPoint ->
                itPoint.ticketList = it.filter { it.workstationId == itPoint.workstationId }.toMutableList()
            }
            mBinding?.rvStatistics?.adapter?.notifyDataSetChanged()
            mBinding?.mapview?.currentRotateDegrees = 0f
            mBinding?.mapview?.currentZoom = 1f
            mBinding?.mapview?.refresh()
        }
    }

    private fun initMap() {
        var bitmap: Bitmap? = null
        try {
            bitmap = BitmapFactory.decodeStream(requireActivity().assets.open("map.png"))
        } catch (e: IOException) {
            e.printStackTrace()
        }

        mBinding?.mapview?.isScaleAndRotateTogether = false
        mBinding?.mapview?.loadMap(bitmap)
        mBinding?.mapview?.setMapViewListener(object : MapViewListener {
            override fun onMapLoadSuccess() {
                markLayer = CustomMarkLayer(mBinding?.mapview, mPointList)
                markLayer?.setMarkIsClickListener(object : CustomMarkLayer.MarkIsClickListener {
                    override fun markIsClick(index: Int, btnIndex: Int) {
//                        ToastUtils.tip(mPointList[index].name + " is selected, btnIndex is " + btnIndex)
                        if (btnIndex == -1) {
                            changePage(
                                PageChangeBO(
                                    1,
                                    mPointList[index].workstationId,
                                    machineryName = mPointList[index].name
                                )
                            )
                        } else {
                            changePage(
                                PageChangeBO(
                                    2,
                                    mPointList[index].workstationId,
                                    mPointList[index].ticketList[btnIndex].ticketId,
                                    mPointList[index].ticketList[btnIndex].machineryId,
                                    mPointList[index].name
                                )
                            )
                        }
                    }
                })
                mBinding?.mapview?.addLayer(markLayer)
                mBinding?.mapview?.refresh()
            }

            override fun onMapLoadFail() {
                ToastUtils.tip("onMapLoadFail")
            }
        })
    }

    override fun initPresenter(): WorkshopPresenter {
        return WorkshopPresenter()
    }

    data class JobStatistics(var sopType: Constants.SopType, var count: Int)

    data class CustomPoint(val pos: PointF, val name: String, val workstationId: Long, var ticketList: MutableList<WorkstationTicketListRespVO>)
}