package com.lukouguoji.gnc.bluetooth.printer

import android.os.Bundle
import android.os.Looper
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.huitao.printer.Printer
import com.huitao.printer.printerface.DeviceFoundCallback
import com.huitao.printer.printerface.ProcessData
import com.huitao.printer.printerface.TaskCallback
import com.huitao.printer.utils.strToBytes
import com.lukouguoji.gnc.bluetooth.adapter.BlueAdapter
import com.lukouguoji.gnc.bluetooth.bean.SimpleBlueDevice
import com.lukouguoji.gnc.bluetooth.printerface.AdapterClickListener
import com.lukouguoji.gnc.R
import com.lukouguoji.gnc.bluetooth.bean.LabelBean
import com.lukouguoji.gnc.bluetooth.printer.SpaceItemDecoration
import com.lukouguoji.module_base.BaseActivity
import com.lukouguoji.module_base.router.ARouterConstants
import java.util.*

/**
 *author  : huitao
 *e-mail  : pig.huitao@gmail.com
 *date    : 2021/5/17 19:00
 *desc    :
 *version :
 */
@Route(path = ARouterConstants.ACTIVITY_URL_Printer_ACTIVITY)
class PrinterActivity : BaseActivity(), AdapterClickListener {
    private lateinit var mList: ArrayList<SimpleBlueDevice>
    private lateinit var mAdapter: BlueAdapter
//    private lateinit var mBinding: ActivityPrinterBinding
    private var mIsConnect = false
    @Autowired
     lateinit var label : LabelBean

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView( R.layout.activity_printer)
        setBackArrow("出港复磅")

       /* if (savedInstanceState != null) {
            label= LabelBean(
                titleName = savedInstanceState.getString("titleName","扬州泰州机场"),
                fno=savedInstanceState.getString("fno",""),
                dest = savedInstanceState.getString("dest",""),
                pc=savedInstanceState.getString("pc",""),
                weight = savedInstanceState.getString("weight",""),
                volume = savedInstanceState.getString("volume",""),
                opdate = savedInstanceState.getString("opdate",""),
                location = savedInstanceState.getString("location","")
            )
           // label= savedInstanceState.get("label") as LabelBean
        };*/
        initViews()
    }

    private fun initViews() {
        mList = java.util.ArrayList()
        mAdapter = BlueAdapter(mList, this).apply {
            setOnClickListener(this@PrinterActivity)
        }
        val layoutManager = LinearLayoutManager(this)
        var recyclerView: RecyclerView = findViewById(R.id.rv)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = mAdapter
        recyclerView.apply{
            addItemDecoration(SpaceItemDecoration(0, 12, true))
            adapter = mAdapter
        }
    }


    fun obtainBondDevices(view: View) {
        if (view.id == R.id.tv_bond_device) {
            //获取周围蓝牙设备，已绑定的蓝牙设备会直接通过集合返回，扫描发现的设备通过DeviceFoundCallback回调回来
            val list = Printer.getInstance().getBondDevicesList(object : DeviceFoundCallback {
                override fun deviceFoundCallback(device: String) {
                    //处理扫描发现的周围蓝牙设备
                }
            })
            if (mList.isNotEmpty()) mList.clear()
            list?.forEach {
                mList.add(SimpleBlueDevice(name = it, isConnected = false))
            }
            mAdapter.notifyDataSetChanged()
        } else {
            //如果设备已连接，则执行写入数据
            if (mIsConnect) {
                writeData(label)
            } else {
                Toast.makeText(this, getString(R.string.please_connect_first), Toast.LENGTH_SHORT)
                    .show()
            }
        }

    }


    private fun writeData(label: LabelBean?) {
        var _this=this
        Printer.getInstance().writeData(object : TaskCallback {
            override fun onSucceed() {
                //打印成功
                Looper.prepare()
                Toast.makeText(_this, "打印成功", Toast.LENGTH_SHORT)
                    .show()
                Looper.loop()
            }

            override fun onFailed(error: String) {
                //打印失败
                Looper.prepare()
                Toast.makeText(_this, error, Toast.LENGTH_SHORT)
                    .show()
                Looper.loop()
            }
        }, object : ProcessData {
            //组装数据
            override fun processDataBeforeSend(): MutableList<ByteArray>? {
                val list = ArrayList<ByteArray>()
                list.add(strToBytes("SET HEAD ON \r\n")!!)
                list.add(strToBytes("SET PRINTKEY OFF \r\n")!!)
                list.add(strToBytes("SET KEY1 ON \r\n")!!)
                list.add(strToBytes("SHIFT 0 \r\n")!!)
                list.add(strToBytes("CLS \r\n")!!)
                list.add(strToBytes("SET TEAR 1 \r\n")!!)
                list.add(strToBytes("SET CUTTER 0 \r\n")!!)
                list.add(strToBytes("SIZE 76 mm,48 mm \r\n")!!)
                list.add(strToBytes("GAP 2 mm,0 mm \r\n")!!)
                list.add(strToBytes("TEXT 190，20，\"TSS16.BF2\",0,2,2,\"${label?.titleName}\" \r\n")!!)
                list.add(strToBytes("TEXT 20，100，\"TSS16.BF2\",0,2,2,\"航班： ${label?.fno} \" \r\n")!!)
                list.add(strToBytes("TEXT 280，100，\"TSS16.BF2\",0,2,2,\"目的地:  ${label?.dest}\" \r\n")!!)
                list.add(strToBytes("TEXT 20，180，\"TSS16.BF2\",0,2,2,\"板车号:  ${label?.carId}  \" \r\n")!!)
                list.add(strToBytes("TEXT 280，180，\"TSS16.BF2\",0,2,2,\"重量:  ${label?.weight}\" \r\n")!!)
                list.add(strToBytes("TEXT 20，260，\"TSS16.BF2\",0,2,2,\"体积:  ${label?.volume}\" \r\n")!!)
                list.add(strToBytes("TEXT 280，260，\"TSS16.BF2\",0,2,2,\"舱位:  ${label?.location}\" \r\n")!!)
                list.add(strToBytes("TEXT 20，330，\"TSS16.BF2\",0,2,2,\"件数:  ${label?.pc}\" \r\n")!!)
                list.add(strToBytes("TEXT 250，330，\"TSS24.BF2\",0,2,2,\"${label?.opdate}  \" \r\n")!!)
                list.add(strToBytes("DIRECTION 0,0 \r\n")!!)
                list.add(strToBytes("DENSITY 1 \r\n")!!)
                list.add(strToBytes("PRINT 1 \r\n")!!)
                return list
            }
        })
    }

    override fun onClickViewListener(view: View, obj: Any) {
        //获取当前设备的连接状态，如果已连接，则断开，未连接则连接
        when (mList[obj as Int].isConnected) {
            true -> {
                Printer.getInstance().disconnected(object : TaskCallback {
                    override fun onSucceed() {
                        Toast.makeText(
                            this@PrinterActivity,
                            getString(R.string.disconnect_success),
                            Toast.LENGTH_SHORT
                        ).show()
                        mList[obj].isConnected = false
                        mAdapter.notifyItemChanged(obj)
                        mIsConnect = false
                    }

                    override fun onFailed(error: String) {
                        Toast.makeText(
                            this@PrinterActivity,
                            getString(R.string.disconnect_failure),
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                })
            }

            else -> {
                Printer.getInstance().connectDeviceByMac(mList[obj].name.split("\n").last().trim(),
                    object : TaskCallback {
                        override fun onSucceed() {
                            Toast.makeText(
                                this@PrinterActivity,
                                getString(R.string.connect_success),
                                Toast.LENGTH_SHORT
                            ).show()
                            mIsConnect = true
                            mList[obj].isConnected = true
                            mAdapter.notifyItemChanged(obj)
                        }

                        override fun onFailed(error: String) {
                            Toast.makeText(
                                this@PrinterActivity,
                                getString(R.string.connect_failure),
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    })
            }
        }

    }


}