package com.dlc.chemical.ui.settings

import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.provider.Settings
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import com.dlc.chemical.common.CommonUtils
import com.dlc.chemical.common.Constants
import com.dlc.chemical.databinding.ActivitySettingsBinding
import com.dlc.chemical.sp.*
import com.dlc.chemical.ui.SplashActivity
import com.rc.core.ui.ActivityCollector
import com.rc.core.ui.activity.RcBaseActivity
import com.rc.core.util.DeviceUtils
import com.rc.httpcore.HttpConfig
import java.lang.ref.WeakReference
import java.util.*

/**
 * info
 *
 * @author ReiChin_
 */
class SettingsActivity : RcBaseActivity<ActivitySettingsBinding>() {

    private val weakHandler by lazy { WeakReferenceHandler(this) }
    companion object {
        private const val REQ_STEELYARD = 100
        private const val REQ_SCAN = 101
        private const val REQ_CAMERA = 102
    }

    override fun createViewBinding() = ActivitySettingsBinding.inflate(LayoutInflater.from(this))

    override fun initListener() {
        viewBinding.back.setOnClickListener {
            ActivityCollector.finishAll()
            val intent = Intent(this, SplashActivity::class.java)
            startActivity(intent)
        }

        viewBinding.versionInfoLayout.setOnLongClickListener {
            startActivity(Intent(Settings.ACTION_SETTINGS))
            finish()
            true
        }

        viewBinding.apiVersion.setOnClickListener {
            val items = HttpConfig.ApiVersion.values().map { it.desc }.toTypedArray()
            val apiVersion = viewBinding.apiVersion.tag as Int? ?: Constants.NetExtra.API_VERSION
            AlertDialog.Builder(this)
                .setTitle("选择Api版本")
                .setSingleChoiceItems(items, apiVersion) { dialog, which ->
                    viewBinding.apiVersion.tag = which
                    viewBinding.apiVersion.text = items[which]
                    dialog.dismiss()
                }.show()
        }

        viewBinding.steelyard.setOnClickListener {
            val intent = Intent(this, SteelyardSettingsActivity::class.java)
            startActivityForResult(intent, REQ_STEELYARD)
        }

        // 扫描抢
        viewBinding.scan.setOnClickListener {
            val intent = Intent(this, ScanSettingsActivity::class.java)
            startActivityForResult(intent, REQ_SCAN)
        }

        // 摄像头-人脸识别
        viewBinding.faceCamera.setOnClickListener {
            val intent = Intent(this, CameraSettingsActivity::class.java)
            intent.putExtra("cameraType", CameraType.FACE)
            startActivityForResult(intent, REQ_CAMERA)
        }
        // 摄像头-称重录像
        viewBinding.videoCamera.setOnClickListener {
            val intent = Intent(this, CameraSettingsActivity::class.java)
            intent.putExtra("cameraType", CameraType.VIDEO)
            startActivityForResult(intent, REQ_CAMERA)
        }

        viewBinding.confirm.setOnClickListener { changeEen() }
    }

    private fun changeEen() {
        val inputEnv = viewBinding.curEnvInput.text.toString().trim()
        if (inputEnv.isEmpty()) {
            showToast("服务器新环境不能为空！")
            return
        }

        val mqttInputEnv = viewBinding.curMqttEnvInput.text.toString().trim()
        if (mqttInputEnv.isEmpty()) {
            showToast("MQTT新环境不能为空！")
            return
        }

        val mqttInputName = viewBinding.curMqttNameInput.text.toString().trim()
        if (mqttInputName.isEmpty()) {
            showToast("MQTT账号不能为空！")
            return
        }

        val mqttInputPwd = viewBinding.curMqttPwdInput.text.toString().trim()
        if (mqttInputPwd.isEmpty()) {
            showToast("MQTT密码不能为空！")
            return
        }

        val settingPwd = viewBinding.curSettingPwdInput.text.toString().trim()
        if (settingPwd.isEmpty()) {
            showToast("工程模式密码不能为空！")
            return
        }

        val apiVersion = viewBinding.apiVersion.tag as Int? ?: Constants.NetExtra.API_VERSION

        val newEnv = if (!inputEnv.endsWith("/")) "${inputEnv}/" else inputEnv

        val envConfig =
            EnvConfig(newEnv, null, mqttInputEnv, mqttInputName, mqttInputPwd, settingPwd, apiVersion)
        EnvSp.saveEnv(this, envConfig)
        weakHandler.sendEmptyMessageDelayed(1,1000)
//        object : Handler(Looper.getMainLooper()) {
//            override fun handleMessage(msg: Message) {
//                showToast("设置成功")
//                CommonUtils.restartApp(applicationContext)
//            }
//        }.sendEmptyMessageDelayed(1, 1000)
    }

    override fun initData() {
        viewBinding.androidId.text = CommonUtils.getAndroidId()
        viewBinding.versionName.text = DeviceUtils.getVersionName(this)
        viewBinding.curEnv.text = HttpConfig.API_BASE_URL

        val envConfig = EnvSp.loadEnv(this)
        val apiVersion = envConfig?.apiVersion ?: Constants.NetExtra.API_VERSION
        viewBinding.apiVersion.text = HttpConfig.ApiVersion.values().find { it.code == apiVersion }?.desc
        viewBinding.apiVersion.tag = apiVersion

        viewBinding.curMqttEnv.text = Constants.MqttConfig.SERVER_URI
        viewBinding.curMqttName.text = Constants.MqttConfig.U_NAME
        viewBinding.curMqttPwd.text = Constants.MqttConfig.U_PWD

        viewBinding.curSettingPwd.text = envConfig?.settingPwd ?: Constants.Mock.SETTING_PWD

        viewBinding.curEnvInput.setText(HttpConfig.API_BASE_URL)
        viewBinding.curMqttEnvInput.setText(Constants.MqttConfig.SERVER_URI)
        viewBinding.curMqttNameInput.setText(Constants.MqttConfig.U_NAME)
        viewBinding.curMqttPwdInput.setText(Constants.MqttConfig.U_PWD)
        viewBinding.curSettingPwdInput.setText(envConfig?.settingPwd ?: Constants.Mock.SETTING_PWD)
        loadSteelyardConfig()
        loadScanConfig()
        loadCameraConfig()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQ_STEELYARD -> if (RESULT_OK == resultCode) loadSteelyardConfig()
            REQ_SCAN -> if (RESULT_OK == resultCode) loadScanConfig()
            REQ_CAMERA -> if (RESULT_OK == resultCode) loadCameraConfig()
        }
    }

    private fun loadSteelyardConfig() {
        val device = UsbDevicesSp.loadConfig(this)
        viewBinding.steelyard.text =
            String.format(Locale.US, "Vendor %04X, Product %04X", device.vendorId, device.productId)
    }

    private fun loadScanConfig() {
        val device = PortDevicesSp.loadConfig(this)
        viewBinding.scan.text =
            String.format(Locale.US, "path %s, baud rate %d", device.path, device.baudRate)
    }

    private fun loadCameraConfig() {
        val cameraIdFace = CameraSp.loadConfig(this, CameraType.FACE)
        viewBinding.faceCamera.text = String.format(Locale.US, "camera id: %d", cameraIdFace)
        val cameraIdVideo = CameraSp.loadConfig(this, CameraType.VIDEO)
        viewBinding.videoCamera.text = String.format(Locale.US, "camera id: %d", cameraIdVideo)
    }

    // static + 弱引用  防止内存泄露
    class WeakReferenceHandler(obj: SettingsActivity) : Handler(Looper.getMainLooper()) {
        private val mRef: WeakReference<SettingsActivity> = WeakReference(obj)

        override fun handleMessage(msg: Message) {
            mRef.get()?.run {
                showToast("设置成功")
                CommonUtils.restartApp(this)
            }
        }
    }

    override fun onDestroy() {
        weakHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }
}