package com.ypsx.yppos.ui.activity

import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.list.SingleChoiceListener
import com.afollestad.materialdialogs.list.listItemsSingleChoice
import com.elvishew.xlog.XLog
import com.ypsx.base.ext.util.toJson
import com.ypsx.base.network.manager.NetState
import com.ypsx.base.util.AppUtils
import com.ypsx.base.util.DeviceUtils
import com.ypsx.base.util.LogUtils
import com.ypsx.yppos.PosApp
import com.ypsx.yppos.R
import com.ypsx.yppos.databinding.ActivityRegisterBinding
import com.ypsx.yppos.http.data.entity.PosStatus
import com.ypsx.yppos.http.data.request.ApplyPosMachineRequest
import com.ypsx.yppos.room.database.PosDatabase
import com.ypsx.yppos.ui.popup.MessagePopupWindow
import com.ypsx.yppos.utils.CacheUtil
import com.ypsx.base.util.dXLog
import com.ypsx.common.app.base.BaseActivity
import com.ypsx.common.app.ext.getIntent
import com.ypsx.common.app.ext.showServerHostExt
import com.ypsx.common.app.ext.startKtxActivityFinish
import com.ypsx.yppos.utils.toast
import com.ypsx.yppos.viewmodel.request.RequestRegisterViewModel
import com.ypsx.yppos.viewmodel.state.RegisterViewModel

/**
 * 注册页
 */
class RegisterActivity : BaseActivity<RegisterViewModel, ActivityRegisterBinding>() {

    private val requestMeViewModel: RequestRegisterViewModel by viewModels()

    override fun layoutId(): Int = R.layout.activity_register


    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        mDatabind.click = ProxyClick()

        val state = intent.getBooleanExtra("state", false)
        val posId:String? = intent.getStringExtra("posId")

        if (state) {
            mViewModel.submitState.set(false)
            mViewModel.submitText.set("审核中")
            requestMeViewModel.getById(posId!!)
        }
    }


    inner class ProxyClick {
        fun submit() {
            mViewModel.submitState.set(false)
            mViewModel.submitText.set("审核中")
            val brand = mViewModel.brand
            val model = mViewModel.model
            val ipAddress = mViewModel.ipAddress
            var port = mDatabind.etPort.text.toString()
            if (port.isEmpty()) {
                port = mDatabind.etPort.hint.toString()
            }
            val version = AppUtils.getVersionCode().toString()
            val macAddress = DeviceUtils.getMacAddress()
            val applyPosMachineRequest = ApplyPosMachineRequest(
                brand,
                ipAddress,
                macAddress,
                port.toInt(),
                version,
                model,
                "8G", "/",
            )
            XLog.d("提交申请信息：${applyPosMachineRequest.toJson()}")

            mViewModel.submitState.set(false)
            mViewModel.submitText.set("审核中")
//            showLoading("请求网络中...")
            requestMeViewModel.applyPos(applyPosMachineRequest)
        }

        fun combosClick(){
            showServerHostExt(CacheUtil.getHost()) {
                CacheUtil.setHost(it)
                CacheUtil.clearAll()
                PosDatabase.clearAllTables()
                PosApp.instance.restartApplication()
            }
        }
    }



    override fun createObserver() {
        requestMeViewModel.posDetails.observe(this, { data ->
            val id = data.id
            val status = data.status
            requestMeViewModel.savePosConfig(data)
            when (status) {
                PosStatus.APPLY.name -> {
                    LogUtils.debugInfo(status)
                    requestMeViewModel.getById(id)
                }
                PosStatus.ACTIVE.name -> {
                    startLogin()
                }
                PosStatus.APPLY_FAILED.name -> {
                    val applyFailedMessage = data.applyFailedMessage
                    LogUtils.debugInfo("错误原因：${applyFailedMessage}")
//                    showError("提示", "您的审核未通过，请重新提交", "我知道了")
                    val messagePopupWindow = MessagePopupWindow(this)
                    messagePopupWindow.showPopupWindow()
                    messagePopupWindow.setData("提示", "您的审核未通过，请重新提交", sure = "我知道了", gone = false)
                    messagePopupWindow.setMessageClick {
                        messagePopupWindow.dismiss()
                        mViewModel.submitState.set(true)
                        mViewModel.submitText.set("提交申请")
                        requestMeViewModel.cancelJob()
                    }
                }
                PosStatus.DISABLED.name -> {
                    val messagePopupWindow = MessagePopupWindow(this)
                    messagePopupWindow.showPopupWindow()
                    messagePopupWindow.setData("提示", "该POS机已停用，是否将删除本地数据", "取消", "确定", false)
                    messagePopupWindow.setMessageClick {
                        messagePopupWindow.dismiss()
                        mViewModel.submitState.set(true)
                        mViewModel.submitText.set("提交申请")
                        requestMeViewModel.cancelJob()
                    }
                }
            }


        })

        requestMeViewModel.posState.observe(this, Observer {
            if (it.isSuccess) {
                it.errorMsg.toast()

                mViewModel.submitState.set(true)
                mViewModel.submitText.set("提交申请")
                requestMeViewModel.cancelJob()
            }else{
                it.errorMsg.toast()

                mViewModel.submitState.set(true)
                mViewModel.submitText.set("提交申请")
            }
        })

    }

    private fun startLogin() {
        startKtxActivityFinish<LoginActivity>()

    }

    private fun showError(title: String, content: String, sure: String) {
        val messagePopupWindow = MessagePopupWindow(this)
        messagePopupWindow.showPopupWindow()
        messagePopupWindow.setData(title, content, sure = sure, gone = false)

    }

    override fun onNetworkStateChanged(netState: NetState) {
        super.onNetworkStateChanged(netState)
        if (netState.isSuccess) {
            "我特么终于有网了啊!".dXLog()
        } else {
            "我特么怎么断网了!".dXLog()
        }
    }



}