package com.rdiot.yx485.device.view

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.clj.fastble.BleManager
import com.lindroy.iosdialog.IAlertDialog
import com.rdiot.yx485.BaseActivity
import com.rdiot.yx485.QRCodeActivity
import com.rdiot.yx485.R
import com.rdiot.yx485.bean.DeviceRoomListBean
import com.rdiot.yx485.bean.EditDeviceReplyBean
import com.rdiot.yx485.databinding.ActivityDeviceMessageBinding
import com.rdiot.yx485.device.model.BindViewModel
import com.rdiot.yx485.util.PermissionUtils
import com.rdiot.yx485.widget.CommonPopupWindow
import com.zcolin.frame.util.ActivityUtil
import com.zcolin.frame.util.DisplayUtil


class EnterRoomInfoActivity : BaseActivity() {
    private val mViewModel by lazy { BindViewModel() }

    private lateinit var mBiding: ActivityDeviceMessageBinding
    private var dialog: IAlertDialog? = null
    private var mNeedBluetooth = true
    private var mIsMaster = true
    private var mMasterDeviceCode: String? = null
    private var mSubDeviceCode: String? = null
    private var homeListPopupWindow: CommonPopupWindow? = null
    private var mSelectedRoom: DeviceRoomListBean.RoomBean? = null
    private var mSelectedMaster: EditDeviceReplyBean.DataBean.DeviceBean? = null

    companion object {
        fun newIntent(context: Context, bundle: Bundle) {
            Intent(context, EnterRoomInfoActivity::class.java).apply {
                putExtra("bundle", bundle)
                context.startActivity(this)
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBiding = ActivityDeviceMessageBinding.inflate(layoutInflater)
        setContentView(mBiding.root)
        initView()
        initData()
    }

    private fun initData() {
        mViewModel.errorMessage.observe(this) { showMessage(it) }
        mViewModel.addState.observe(this) { success ->
            if (success) {
                showSuccessDialog()
            }
        }
        mViewModel.loadRoomList()
    }

    private fun showSuccessDialog() {
        dialog?.dismiss()
        dialog = IAlertDialog.build(this)
            .setTitle("添加成功")
            .setCancelOutside(false)
            .setShowNegButton(false)
            .setAlpha(1.0F)
            .setMessage("添加设备成功，点击确定返回列表查看")
            .setPosButtonText(R.string.got_it)
            .setPosClickListener {
                ActivityUtil.backToHome()
            }

        dialog?.isCancelable = false
        dialog?.show()
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun initView() {
        val bundle = intent.getBundleExtra("bundle")
        bundle?.let {
            val deviceName = bundle.getString("device_name")
            deviceName?.let {
                mBiding.editDeviceName.setText(it)
            }

            val blueCode = bundle.getString("blue_code")
            blueCode?.let {
                if (TextUtils.isEmpty(it)) {
                    return@let
                }
                mBiding.editTextDeviceNumber.setText(blueCode)
                mBiding.layoutInputDeviceCode.visibility = View.GONE
            }

            mIsMaster = bundle.getBoolean("isMaster", true)
            mBiding.editDeviceType.visibility =
                if (mIsMaster) View.GONE else View.VISIBLE
            if (!mIsMaster) {
                mViewModel.loadDeviceList(true)
            }
            mNeedBluetooth = bundle.getBoolean("bluetooth", true)
            mBiding.buttonConfirmAdd.text = if (mNeedBluetooth) {
                "下一步"
            } else {
                "确认添加"
            }
        }

        mBiding.layoutTitle.btnTitleLeft.setOnClickListener { finish() }
        mBiding.buttonConfirmAdd.setOnClickListener {
            gotoEnterWifiInfo()
        }

        mBiding.editDeviceType.setOnClickListener { showDeviceListPopupWindow(mBiding.editDeviceType) }
        mBiding.editRoomName.setOnClickListener { showRoomListPopupWindow(mBiding.editRoomName) }
        mBiding.ivScan.setOnClickListener {
            if (PermissionUtils.checkPermissionGranted(this, "scan")) {
                openScanner()
            }
        }
    }

    private fun gotoEnterWifiInfo() {
        val deviceName = mBiding.editDeviceName.text.toString()
        if (TextUtils.isEmpty(deviceName)) {
            showMessage("请填写设备名称")
            return
        }

        val deviceNumber = mBiding.editTextDeviceNumber.text.toString()
        if (TextUtils.isEmpty(deviceNumber)) {
            showMessage("设备编号（或者设备blue_code）不能为空")
            return
        }

        if (mSelectedRoom == null) {
            showMessage("请选择房间")
            return
        }

        if (!verifyDeviceCode(deviceNumber)) {
            return
        }

        val bundle = intent.getBundleExtra("bundle") ?: Bundle()
        bundle.putString("deviceName", deviceName)
        bundle.putString("deviceNumber", mMasterDeviceCode)
        bundle.putString("subDeviceCode", mSubDeviceCode)
        bundle.putString("room_name", mSelectedRoom!!.name)
        bundle.putString("home_id", mSelectedRoom!!.home_id)
        bundle.putString("room_id", mSelectedRoom!!.record_id)
        if (mNeedBluetooth) {
            if (PermissionUtils.checkPermissionGranted(this, "enterWifi")) {
                EnterWifiInfoActivity.newIntent(this, bundle)
            }
            return
        }

        if (PermissionUtils.checkPermissionGranted(this, "ble")) {
            ScanDeviceActivity.newIntent(this, bundle)
        }
    }

    private fun verifyDeviceCode(deviceNumber: String): Boolean {
        if (mIsMaster) {
            mMasterDeviceCode = deviceNumber
            return true
        }

        if (mSelectedMaster == null) {
            showMessage("请先选择主控设备")
            return false
        }

        mMasterDeviceCode = mSelectedMaster!!.device_code
        mSubDeviceCode = deviceNumber
        return true
    }

    private fun openScanner() {
        startActivityForResult(Intent(this, QRCodeActivity::class.java), 1000)
    }

    override fun onActivityResult(requestCode: Int, result: Int, data: Intent?) {
        super.onActivityResult(requestCode, result, data)
        if (result == RESULT_OK) {
            val scan = data?.getStringExtra("SCAN_RESULT")
            Log.d("SCAN_RESULT", "onActivityResult: $scan")
            scan?.apply {
                mBiding.editTextDeviceNumber.setText(this)
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    fun showDeviceListPopupWindow(view: TextView?) {
        mViewModel.deviceList.value ?: return
        mViewModel.deviceList.value?.let {
            if (it.isEmpty()) {
                showMessage("主控设备列表数据为空")
                return
            }

            homeListPopupWindow = CommonPopupWindow(this, true)
            for (device in it) {
                homeListPopupWindow!!.addMenuItem(
                    device.name,
                    View.OnClickListener { v1: View? ->
                        mSelectedMaster = device
                        mBiding.editDeviceType.text = device.name
                        mBiding.editDeviceType.setTextColor(getColor(R.color.black_1E))
                    })
            }
            homeListPopupWindow!!.show(view, DisplayUtil.dip2px(this, 16.0f), 0)
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    fun showRoomListPopupWindow(view: TextView?) {
        mViewModel.roomList.value ?: return
        mViewModel.roomList.value?.let {
            if (it.isEmpty()) {
                showMessage("当前房间列表数据为空")
                return
            }

            homeListPopupWindow = CommonPopupWindow(this, true)
            for (room in it) {
                homeListPopupWindow!!.addMenuItem(
                    room.name,
                    View.OnClickListener { v1: View? ->
                        mSelectedRoom = room
                        mBiding.editRoomName.text = room.name
                        mBiding.editRoomName.setTextColor(getColor(R.color.black_1E))
                    })
            }
            homeListPopupWindow!!.show(view, DisplayUtil.dip2px(this, 16.0f), 0)
        }
    }

    override fun onDestroy() {
        if (homeListPopupWindow != null) {
            homeListPopupWindow!!.dismiss()
            homeListPopupWindow = null
        }
        super.onDestroy()
    }
}