package com.casic.electric.detector.view

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.media.AudioAttributes
import android.media.SoundPool
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.provider.Settings
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.widget.AdapterView
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.casic.electric.detector.R
import com.casic.electric.detector.adapter.EditableImageAdapter
import com.casic.electric.detector.base.SerialPortActivity
import com.casic.electric.detector.callback.OnImageCompressListener
import com.casic.electric.detector.extensions.*
import com.casic.electric.detector.utils.*
import com.casic.electric.detector.vm.TaskViewModel
import com.gyf.immersionbar.ImmersionBar
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.pengxh.kt.lite.extensions.convertColor
import com.pengxh.kt.lite.extensions.isNetworkConnected
import com.pengxh.kt.lite.extensions.navigatePageTo
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.SaveKeyValues
import com.pengxh.kt.lite.utils.WeakReferenceHandler
import com.pengxh.kt.lite.vm.LoadState
import com.pengxh.kt.lite.widget.dialog.NoNetworkDialog
import kotlinx.android.synthetic.main.activity_install_small_label.*
import kotlinx.android.synthetic.main.include_base_title.*
import kotlinx.android.synthetic.main.include_open_camera.*
import kotlinx.android.synthetic.main.include_small_label_object_attribute.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException

@SuppressLint("SetTextI18n")
class InstallSmallLabelActivity : SerialPortActivity(), Handler.Callback {

    private val kTag = "SmallLabelActivity"
    private val context: Context = this@InstallSmallLabelActivity
    private val gpioManager by lazy { GpioManager() }
    private val realPaths: ArrayList<String> = ArrayList() //真实图片路径
    private var soundResId = 0
    private lateinit var weakReferenceHandler: WeakReferenceHandler
    private lateinit var soundPool: SoundPool
    private lateinit var imageAdapter: EditableImageAdapter
    private lateinit var taskViewModel: TaskViewModel

    override fun initLayoutView(): Int = R.layout.activity_install_small_label

    override fun setupTopBarLayout() {
        titleView.text = "安装新电子标签"
        titleView.setTextColor(R.color.themeColor.convertColor(this))

        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .statusBarColor(R.color.mainBackground)
            .init()
        initLayoutImmersionBar(rootView)
    }

    override fun initData(savedInstanceState: Bundle?) {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN or WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)

        weakReferenceHandler = WeakReferenceHandler(this)

        val audioAttributes = AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()
        soundPool = SoundPool.Builder()
            .setMaxStreams(16)
            .setAudioAttributes(audioAttributes)
            .build()

        //设置上次填写过的值
        cableNumberView.setText("cableNumberView".getDefaultValue())
        cableNameView.setText("cableNameView".getDefaultValue())
        lineView.setText("lineView".getDefaultValue())
        voltageLevelView.setText("voltageLevelView".getDefaultValue())
        cableModelView.setText("cableModelView".getDefaultValue())
        cableSpecView.setText("cableSpecView".getDefaultValue())
        cableBrandView.setText("cableBrandView".getDefaultValue())
        cableStartView.setText("cableStartView".getDefaultValue())
        cableEndView.setText("cableEndView".getDefaultValue())
        jointCreatorView.setText("jointCreatorView".getDefaultValue())
        objectRemarkView1.setText("objectRemarkView1".getDefaultValue())
        objectRemarkView2.setText("objectRemarkView2".getDefaultValue())
        objectRemarkView3.setText("objectRemarkView3".getDefaultValue())

        //初始化图片九宫格
        imageAdapter = EditableImageAdapter(this, 3, 3f)
        addImageRecyclerView.adapter = imageAdapter

        taskViewModel = ViewModelProvider(this)[TaskViewModel::class.java]
    }

    override fun observeRequestState() {
        taskViewModel.loadState.observe(this) {
            when (it) {
                LoadState.Loading -> LoadingDialogHub.show(this, "电子标签安装中，请稍后...")
                LoadState.Success -> {
                    LoadingDialogHub.dismiss()
                    finish()
                }
                else -> LoadingDialogHub.dismiss()
            }
        }
    }

    override fun initEvent() {
        leftBackView.setOnClickListener { finish() }

        /**************************************************************************************/

        //TODO 读取电子标签为未实现
        readElectricTagButton.setOnClickListener {
            gpioManager.setGpioHigh("18")

            LoadingDialogHub.show(this, "电子标签读取中，请稍后...")

            soundResId = soundPool.load(this, R.raw.ring3, 1)
            soundPool.setOnLoadCompleteListener { soundPool, _, _ ->
                soundPool.play(soundResId, 1f, 1f, 0, -1, 1f)
            }

            // 1000ms后发送读标识器或搜索信号
            weakReferenceHandler.postDelayed({
                try {
                    // 发送读标识器或搜索信号
                    outputStream?.write("00".toByteArray())
                    outputStream?.flush()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }, 1000)
        }

        bindMarkerSpinner.show(this, arrayOf("是", "否"), 0)
        bindMarkerSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?, view: View?, position: Int, id: Long
            ) {
                if (position == 0) {
                    markerLayout.visibility = View.VISIBLE
                } else {
                    markerLayout.visibility = View.GONE
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }

        middleJointSpinner.show(this, arrayOf("有", "无"), 0)

        imageAdapter.setOnItemClickListener(object : EditableImageAdapter.OnItemClickListener {
            override fun onAddImageClick() {
                PictureSelector.create(this@InstallSmallLabelActivity)
                    .openCamera(SelectMimeType.ofImage())
                    .forResult(object : OnResultCallbackListener<LocalMedia> {
                        override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                            if (result == null) {
                                "拍照失败，请重试".show(context)
                                return
                            }
                            analyticalSelectResult(result[0])
                        }

                        override fun onCancel() {

                        }
                    })
            }

            override fun onItemClick(position: Int) {
                if (realPaths[position].isEmpty()) {
                    "图片加载失败，无法查看大图".show(context)
                } else {
                    context.navigatePageTo<BigImageActivity>(position, realPaths)
                }
            }

            override fun onItemLongClick(view: View?, position: Int) {
                imageAdapter.deleteImage(position)
            }
        })

        /**************************************************************************************/
        installButton.setOnClickListener {
            if (isNetworkConnected()) {
                val companyId = SaveKeyValues.getValue(LocaleConstant.USER_COMPANY_ID, "") as String

                if (markerIdView.text.isNullOrBlank()) {
                    "标识器ID不能为空，请读标识器".show(this)
                    return@setOnClickListener
                }

                if (smallLabelIdView.text.isNullOrBlank()) {
                    "电子标签ID不能为空，请读电子标签".show(this)
                    return@setOnClickListener
                }

                if (voltageLevelView.text.isNullOrBlank()) {
                    "电压等级不能为空，请输入电压等级".show(this)
                    return@setOnClickListener
                }

                //保存默认值
                "cableNumberView".setDefaultValue(cableNumberView)
                "cableNameView".setDefaultValue(cableNameView)
                "lineView".setDefaultValue(lineView)
                "voltageLevelView".setDefaultValue(voltageLevelView)
                "cableModelView".setDefaultValue(cableModelView)
                "cableSpecView".setDefaultValue(cableSpecView)
                "cableBrandView".setDefaultValue(cableBrandView)
                "cableStartView".setDefaultValue(cableStartView)
                "cableEndView".setDefaultValue(cableEndView)
                "jointCreatorView".setDefaultValue(jointCreatorView)
                "objectRemarkView1".setDefaultValue(objectRemarkView1)
                "objectRemarkView2".setDefaultValue(objectRemarkView2)
                "objectRemarkView3".setDefaultValue(objectRemarkView3)

                val smallLabelData = SmallLabelDataClass(
                    companyId,
                    markerIdView.text.toString(),
                    markerNumberView.text.toString(),
                    markerNameView.text.toString(),
                    smallLabelIdView.text.toString(),
                    cableNameView.toString(),
                    cableNumberView.toString(),
                    lineView.text.toString(),
                    voltageLevelView.toString(),
                    cableModelView.text.toString(),
                    cableSpecView.text.toString(),
                    cableBrandView.text.toString(),
                    cableStartView.text.toString(),
                    cableEndView.text.toString(),
                    middleJointSpinner.selectedItem.toString(),
                    jointCreatorView.text.toString(),
                    objectRemarkView1.text.toString(),
                    objectRemarkView2.text.toString(),
                    objectRemarkView3.text.toString(),
                    realPaths
                )

                //先存本地
                lifecycleScope.launch {
                    withContext(Dispatchers.IO) {
                        DataBaseManager.get.insertSmallLabel(smallLabelData)
                    }
                }

                //再存服务器
                taskViewModel.installSmallLabel(smallLabelData)
            } else {
                NoNetworkDialog.Builder()
                    .setContext(context)
                    .setOnDialogButtonClickListener(object :
                        NoNetworkDialog.OnDialogButtonClickListener {
                        override fun onButtonClick() {
                            val intent = Intent(Settings.ACTION_SETTINGS)
                            startActivity(intent)
                        }
                    }).build().show()
            }
        }

        readLabelButton.setOnClickListener {
            gpioManager.setGpioHigh("18")

            LoadingDialogHub.show(this, "标识器读取中，请稍后...")

            soundResId = soundPool.load(this, R.raw.ring3, 1)
            soundPool.setOnLoadCompleteListener { soundPool, _, _ ->
                soundPool.play(soundResId, 1f, 1f, 0, -1, 1f)
            }

            // 1000ms后发送读标识器或搜索信号
            weakReferenceHandler.postDelayed({
                try {
                    // 发送读标识器或搜索信号
                    outputStream?.write("2".toByteArray())
                    outputStream?.flush()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }, 1000)
        }
    }

    override fun onDataReceived(buffer: ByteArray?, size: Int) {
        if (buffer != null) {
            val message = weakReferenceHandler.obtainMessage()
            message.what = 2023081702
            message.obj = buffer
            weakReferenceHandler.sendMessage(message)
        }
    }

    override fun handleMessage(msg: Message): Boolean {
        if (msg.what == 2023081702) {
            soundPool.release()

            val buffer = msg.obj as ByteArray
            val hex = buffer.toHex()

            Log.d(kTag, "handleMessage => $hex")
            if (hex.length >= 20) {
                val markerId = hex.substring(0, 20).hexToString()

                gpioManager.setGpioLow("18")

                //查本地库
                val result = DataBaseManager.get.queryLabelById(markerId)
                if (result.isEmpty()) {
                    markerIdView.text = markerId
                } else {
                    "此标识器已安装，请更换标识器！".show(this)
                }
                LoadingDialogHub.dismiss()
            }
        }
        return true
    }

    private fun analyticalSelectResult(result: LocalMedia) {
        //压缩图片
        result.realPath.compressImage(this, object : OnImageCompressListener {
            override fun onSuccess(file: File) {
                realPaths.add(file.absolutePath)
                imageAdapter.setupImage(realPaths)
            }

            override fun onError(e: Throwable) {
                e.printStackTrace()
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        soundPool.release()
        gpioManager.setGpioLow("18")
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            soundPool.release()
        }
        return super.onKeyDown(keyCode, event)
    }
}