package com.dlc.chemical.ui.tag

import android.content.Intent
import android.content.IntentFilter
import android.graphics.Typeface
import android.hardware.usb.UsbManager
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dlc.chemical.R
import com.dlc.chemical.databinding.ActivityTagManagementBinding
import com.dlc.chemical.iflytek.AudioPlayerManager
import com.dlc.chemical.print.PrinterListener
import com.dlc.chemical.print.PrinterStateReceiver
import com.dlc.chemical.print.UsbPrinterManager
import com.dlc.chemical.ui.MainActivity
import com.dlc.chemical.ui.common.*
import com.dlc.chemical.ui.dialog.SimpleDialog
import com.dlc.chemical.ui.dialog.SimpleTipsDialog
import com.dlc.chemical.ui.query.SelectCabinetDialog
import com.dlc.chemical.ui.widget.TitleBar
import com.print.usbprint.util.USBUtil
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.ChemicalReq
import com.rc.httpcore.vo.response.CabinetBean
import com.rc.httpcore.vo.response.ChemicalBean
import io.reactivex.disposables.Disposable

/**
 * 标签管理
 *
 * @author ReiChin_
 */
class TagManagementActivity : CommonListActivity<ChemicalBean, ActivityTagManagementBinding>(),
    TitleBar.TitleListener {

    override val mAdapter by lazy { TagManagementAdapter() }
    override val mSrlRefresh by lazy { viewBinding.swipeRefreshLayout }
    override val mRvContent by lazy { viewBinding.recyclerView }
    override val mTvPageInfo by lazy { viewBinding.pageInfo }
    override val mTvPagePrev by lazy { viewBinding.pagePrev }
    override val mTvPageNext by lazy { viewBinding.pageNext }

    private var mCabinetBean: CabinetBean? = null

    override fun createViewBinding() = ActivityTagManagementBinding.inflate(layoutInflater)

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        mAdapter.addChildClickViewIds(R.id.print_qrcode, R.id.change_rfid)

        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.setTitleInfoFromSp()

        // 机柜筛选
        viewBinding.selectCabinet.setOnClickListener {
            queryCabinetList { data ->
                val defSelectedBean = mCabinetBean ?: data[0]
                SelectCabinetDialog(this, data, defSelectedBean) { cBean ->
                    mCabinetBean = cBean
                    viewBinding.selectCabinet.text = cBean.cabinetName
                    loadData(true)
                }.show()
            }
        }

        // 查询
        viewBinding.search.setOnClickListener {
            hintKeyBoard()
            loadData(true)
        }
        // 重置
        viewBinding.reset.setOnClickListener {
            viewBinding.keyword.text = null
            viewBinding.selectCabinet.text = "选择机柜"
            mCabinetBean = null

            loadData(true)
        }
    }

    /*
     * 查询机柜
     */
    private fun queryCabinetList(callback: (data: MutableList<CabinetBean>) -> Unit) {
        showLoading("查询中...")
        val disposable = ApiRepository.queryCabinetList()
            .subscribe({ response ->
                dismissLoading()
                val data = mutableListOf<CabinetBean>()
                data.add(CabinetBean.createDefCabinetBean())
                data.addAll(response)
                callback.invoke(data)
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    override fun queryData(): Disposable? {
        val param = ChemicalReq()
        param.pageNum = mCurrentPage
        param.pageSize = PAGE_SIZE
        param.chemicalName = viewBinding.keyword.text.toString().trim()
        if (CabinetBean.DEF_CABINET_ID != mCabinetBean?.id) {
            param.cabinetId = mCabinetBean?.id
        }

        return ApiRepository.queryChemicalByStock(param)
            .subscribe({
                dismissLoading()
                dispatchLoadDataSuccess(it.rows, it.total)
            }, { throwable ->
                dismissLoading()
                dispatchLoadDataFailure(throwable)
            })
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = mAdapter.getItem(position)
        when (view.id) {
            R.id.print_qrcode -> {
                // 二维码补打
                SimpleDialog(context = this,
                    titleText = "本次补打编号：${item.tagCode}",
                    message = "确认补打？",
                    messageTextColor = "#FF333333",
                    messageTextStyle = Typeface.BOLD,
                    dialogListener = {
                        val device = USBUtil.getInstance()
                            .getUsbDevice(
                                UsbPrinterManager.DEVICE_VID,
                                UsbPrinterManager.DEVICE_PID
                            )
                        if (null != device && USBUtil.getInstance().IsOpen(device, this)) {
                            UsbPrinterManager.printLabel(item)
                        } else {
                            showToast("未连接打印设备！")
                        }
                    }).show()
            }
            R.id.change_rfid -> {
                // RFID标签更换
                val intent = Intent(this, TagScanActivity::class.java)
                intent.putExtra("moduleEnum", ModuleEnum.RFID)
                intent.putExtra("id", item.id)
                startActivity(intent)
            }
        }
    }

    private fun onPrinterEvent(success: Boolean, message: String) {
        if (success) {
            dispatchQRCodePrintSuccess()
        } else {
            showToast(message)
        }
    }

    private var mPrinterStateReceiver: PrinterStateReceiver? = null

    override fun onResume() {
        super.onResume()
        registerPrinterStateReceiver()
    }

    private fun registerPrinterStateReceiver() {
        if (mPrinterStateReceiver == null) {
            val filter = IntentFilter()
            mPrinterStateReceiver = PrinterStateReceiver(printerListener = object : PrinterListener {
                override fun onPrintResult(success: Boolean, message: String) {
                    onPrinterEvent(success, message)
                }

            })
            filter.addAction(PrinterStateReceiver.ACTION_PRINTER_STATE)
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
            this.registerReceiver(mPrinterStateReceiver, filter)
        }
    }

    override fun onPause() {
        super.onPause()
        if (mPrinterStateReceiver != null) {
            unregisterReceiver(mPrinterStateReceiver)
            mPrinterStateReceiver = null
        }
    }

    private fun dispatchQRCodePrintSuccess() {
        val message = "二维码补打成功！\n请将二维码标签粘在化学品瓶身上。"
        AudioPlayerManager.speakVoice(R.raw.audio_success_print_qrcode)
        SimpleTipsDialog(this, message)
            .show()
    }

    override fun createItemDecoration(): RecyclerView.ItemDecoration? = null

    override fun onHomeViewClicked(view: View) {
        startActivity(Intent(this, MainActivity::class.java))
    }

    override fun onBackViewClicked(view: View) {
        finish()
    }

}

class TagManagementAdapter :
    PageQuickAdapter<ChemicalBean>(R.layout.item_tag_management_rfid) {

    override fun convert(holder: BaseViewHolder, item: ChemicalBean) {
        holder.setText(R.id.chemicalName, item.chemicalName)
            .setText(R.id.cabinetName, item.cabinetName)
            .setText(R.id.purity, item.purity)
            .setText(
                R.id.chemicalAmount,
                "${item.chemicalAmount ?: ""}${item.chemicalAmountUnit ?: ""}"
            )
            .setText(R.id.classifyName, item.classifyName)
            .setText(R.id.chemicalNum, item.chemicalNum)
            .setVisible(
                R.id.print_qrcode,
                visiblePrintQrcode(item.labelType, item.printCode)
            )
            .setVisible(R.id.change_rfid, TagType.RFID.type == item.labelType)
    }

    private fun visiblePrintQrcode(labelType: String?, printCode: String?): Boolean {
        return TagType.QR_CODE.type == labelType || (TagType.RFID.type == labelType && "1" == printCode)
    }

}