package com.grkj.iscs.presentation

import android.view.Gravity
import android.widget.CheckBox
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.grkj.iscs.R
import com.grkj.iscs.view.base.BaseMvpActivity
import com.grkj.iscs.databinding.ActivityPresentationBinding
import com.grkj.iscs.modbus.DockBean
import com.grkj.iscs.modbus.ModBusController
import com.grkj.iscs.model.DeviceConst
import com.grkj.iscs.model.presentation.WorkTicketBean
import com.grkj.iscs.util.ToastUtils
import com.grkj.iscs.view.widget.SelectableInput
import com.manu.mdatepicker.MDatePicker
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder
import java.text.SimpleDateFormat
import java.util.Date
import java.util.stream.Collectors

class PresentationActivity :
    BaseMvpActivity<IPresentationView, PresentationPresenter, ActivityPresentationBinding>() {

    private var cardRfid: String? = null
    private var mSelectedSopIdx: Int? = null

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

    override fun initView() {
        cardRfid = intent.getStringExtra("card")

        mBinding?.siSop?.setOptionList(PresentationManager.mSopList.stream().map { it.sop }.collect(Collectors.toList()))
        mBinding?.siSop?.setOnSpinnerSelectListener(object : SelectableInput.OnSpinnerSelectListener {
            override fun onSelect(str: String?, index: Int) {
                mSelectedSopIdx = index
                val sop = PresentationManager.mSopList[index]
                mBinding?.siWorkshop?.setText(sop.workshop)
                mBinding?.siLine?.setText(sop.line)
                mBinding?.siTicketName?.setText(sop.ticketName)
                mBinding?.siTicketNumber?.setText(sop.ticketNumber)
                mBinding?.siTicketType?.setText(sop.type)
                mBinding?.siSegregationPoint?.setText(sop.pointList.map { it.name }.toString())
            }
        })

        mBinding?.siPersonLock?.setOptionList(PresentationManager.mLockerList.map { it.name } as MutableList)
        mBinding?.siPersonSafety?.setOptionList(PresentationManager.mSafetyList)

        mBinding?.confirm?.setOnClickListener {
            confirm()
        }

        mBinding?.tvStartTime?.setOnClickListener {
            MDatePicker.create(this)
                .setCanceledTouchOutside(true)
                .setGravity(Gravity.CENTER)
                .setSupportTime(true)
                .setTwelveHour(false)
                .setOnDateResultListener {
                    mBinding?.tvStartTime?.text = SimpleDateFormat("yyyy-MM-dd HH:mm").format(Date(it))
                }
                .build().show()
        }

        mBinding?.tvEndTime?.setOnClickListener {
            MDatePicker.create(this)
                .setCanceledTouchOutside(true)
                .setGravity(Gravity.CENTER)
                .setSupportTime(true)
                .setTwelveHour(false)
                .setOnDateResultListener {
                    mBinding?.tvEndTime?.text = SimpleDateFormat("yyyy-MM-dd HH:mm").format(Date(it))
                }
               .build().show()
        }

        (mBinding?.rvLockerTogether?.layoutManager as LinearLayoutManager).orientation =  LinearLayoutManager.HORIZONTAL
        mBinding?.rvLockerTogether?.adapter = object : CommonAdapter<PresentationManager.PLockerTogetherBean>(this, R.layout.item_rv_locker_together, PresentationManager.mLockerTogetherList) {
            override fun convert(holder: ViewHolder, data: PresentationManager.PLockerTogetherBean, position: Int) {
                holder.setText(R.id.tv_name, data.name)
                holder.setChecked(R.id.cb, data.isChecked)
                holder.getView<CheckBox>(R.id.cb).setOnCheckedChangeListener { _, b ->
                    data.isChecked = b
                }
            }
        }
    }

    private fun confirm() {
        if (mSelectedSopIdx == null) {
            ToastUtils.tip("请选择SOP")
            return
        }

        // 锁
        val dockList = ModBusController.getDockByType(DeviceConst.DOCK_TYPE_PORTABLE)
        if (dockList.isEmpty()) {
            ToastUtils.tip("没有找到移动柜")
            return
        }
        val lockList = dockList[0].getLockList().take(2)
        if (lockList.isEmpty()) {
            ToastUtils.tip("没有找到移动柜的锁")
            return
        }
        if (lockList.size < 2) {
            ToastUtils.tip("移动柜的锁数量不够2个")
            return
        }
//        val lockIdxList = lockList.map { it.idx } as MutableList

//        // 蓝牙钥匙
//        val keyList = ModBusController.getKeyByDockType(DeviceConst.DOCK_TYPE_PORTABLE)
//        if (keyList.isNullOrEmpty()) {
//            ToastUtils.tip("没有找到钥匙")
//            return
//        }
//        val rfid = keyList[0].rfid
//        if (rfid.isNullOrEmpty()) {
//            ToastUtils.tip("没有找到钥匙的RFID")
//            return
//        }

        // 创建工单
        if (mBinding?.siPersonLock?.mSelectIdx == null) {
            ToastUtils.tip("请选择上锁人")
            return
        }
        createWorkTicket(lockList)
        finish()

//        // 操作设备
//        ModBusController.controlLockBuckle(true, dockList[0].addr.toInt() - 1, lockIdxList) { res ->
//            LogUtil.i("confirm开锁卡扣 : ${res.toHexStrings()}")
//        }
//        BusinessManager.sendTicketBusiness(PresentationManager.keyMac, this) { b, s ->
//            handleLoading(b, s)
//            if (s.equals("切换工作模式成功")) {
//                ModBusController.controlKeyBuckle(true, isLeft = true, dockList[0].addr.toInt() - 1)
//            }
//        }
    }


    /**
     * 创建工作票
     */
    private fun createWorkTicket(lockList: List<DockBean.LockBean>): String {
        val ticket = WorkTicketBean()
        ticket.cardNo = cardRfid
        ticket.effectiveTime = 24

        ticket.data = mutableListOf()

        val dataDTO = WorkTicketBean.DataDTO()
        dataDTO.taskCode = SimpleDateFormat("yyyyMMddHHmm").format(Date(System.currentTimeMillis()))
        dataDTO.taskId = "123456"
        dataDTO.codeId = PresentationManager.workTicketList.size + 1
        dataDTO.dataList = mutableListOf()

        val pointList = PresentationManager.mSopList[mSelectedSopIdx!!].pointList
        for (i in pointList.indices) {
            val dataListDTO = WorkTicketBean.DataDTO.DataListDTO()
            dataListDTO.dataId = i
            dataListDTO.equipRfidNo = pointList[i].rfid
            dataListDTO.target = 0
            if (i != 0) {
                dataListDTO.prevId = i - 1
            }
            dataDTO.dataList?.add(dataListDTO)
        }

        ticket.data?.add(dataDTO)

        ticket.lockList = mutableListOf()
        for (i in lockList.indices) {
            val lockListDTO = WorkTicketBean.LockListDTO()
            lockListDTO.lockId = "${i + 1}"
            lockListDTO.rfid = lockList[i].rfid
            ticket.lockList?.add(lockListDTO)
        }

        PresentationManager.workTicketList.add(
            PresentationManager.PServerTicket(
                PresentationManager.workTicketList.size + 1,
                PresentationManager.mSopList[mSelectedSopIdx!!].sopId,
                PresentationManager.mSopList[mSelectedSopIdx!!],
                ticket,
                mBinding?.tvStartTime?.text.toString(),
                mBinding?.tvEndTime?.text.toString(),
                0,
                PresentationManager.mLockerList[mBinding?.siPersonLock?.mSelectIdx!!],
                PresentationManager.mLockerTogetherList.filter { it.isChecked } as MutableList,
                PresentationManager.mSafetyList[mBinding?.siPersonSafety?.mSelectIdx!!]
            )
        )

        return Gson().toJson(ticket)
    }


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