package com.module.backstage.dialog


import android.content.Context
import android.os.Handler
import android.util.Log
import android.view.View
import androidx.lifecycle.LifecycleObserver
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hboxs.serialport.plc.DialogClickListener
import com.module.backstage.R
import com.module.backstage.adapter.CheckDialogAdapter
import com.quyunshuo.androidbaseframemvvm.base.bean.Global
import com.module.backstage.bean.Name
import com.module.backstage.databinding.DialogCheckBinding
import com.module.backstage.repo.CheckRepository
import com.module.backstage.vm.ErrorCheckFragmentVM
import com.module.pay.nayax.CreditCardPresenter
import com.quyunshuo.androidbaseframemvvm.base.addressenum.PayEnum
import com.quyunshuo.androidbaseframemvvm.base.mvvm.v.BaseFrameDialog
import com.quyunshuo.androidbaseframemvvm.base.utils.SimNetworkUtils
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.bean.PayTypeBean
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.util.ToastUtil
import com.quyunshuo.androidbaseframemvvm.common.util.UiUtil
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject

class CheckDialog(mContext: Context) :
    BaseFrameDialog<DialogCheckBinding>(mContext),
    View.OnClickListener,
    LifecycleObserver {

    private var mDisposables: CompositeDisposable? = null
    private var context: Context? = null
    var errorCheckVM: ErrorCheckFragmentVM? = null
    constructor(mContext: Context, merrorCheckVM: ErrorCheckFragmentVM) : this(mContext) {
        this.context = mContext
        this.errorCheckVM = merrorCheckVM
    }

    /*  @Inject
      lateinit var mApi: DevService*/
    @Inject
    lateinit var mApi: CheckRepository

    override fun createVB() = DialogCheckBinding.inflate(layoutInflater)
    protected fun addSubscription(observable: Observable<*>, observer: DisposableObserver<Any>) {
        if (mDisposables == null) {
            mDisposables = CompositeDisposable()
        }
        observable
            .unsubscribeOn(Schedulers.io())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(observer)
        mDisposables?.add(observer)
    }

    override fun initObserve() {

    }

    fun setListener(listener: DialogClickListener?) {
        this.listener = listener
    }

    private var listener: DialogClickListener? = null
    override fun initRequestData() {

    }

    override fun DialogCheckBinding.initView() {

        mBinding.btnApply.setOnClickListener(this@CheckDialog)
        mBinding.btnCancel.setOnClickListener(this@CheckDialog)

    }


    var arrayListState: HashMap<String, PayTypeBean> = HashMap()
    private var adapter: CheckDialogAdapter? = null
    private var csimFunction: String? = null
    override fun onClick(v: View) {

        var text = ""
        when (v.id) {
            R.id.btn_apply -> when (csimFunction) {
                Name.SIM_FUNCTION -> dismiss()
                Name.NAYAX_FUNCTION -> {
                    if (arrayListState != null) {
                        var nayax = arrayListState[PayEnum.NAYAX.code]

                        if (nayax == null) {
                            arrayListState[PayEnum.NAYAX.code] =
                                PayTypeBean(PayEnum.NAYAX.code, true)
                            getValue(
                                0,
                                true,
                                UiUtil.getStringRes(R.string.base_pay_type) + ":" + payType()
                            )
                            text += (UiUtil.getStringRes(R.string.base_pay_type) + UiUtil.getStringRes(R.string.base_successful_repair)).toString() + ","
                            SpUtils.put(MMKVName.PAY_TYPE, Gson().toJson(arrayListState))
                        }
                    } else {
                        arrayListState[PayEnum.NAYAX.code] = PayTypeBean(PayEnum.NAYAX.code, true)

                        getValue(
                            0,
                            true,
                            UiUtil.getStringRes(R.string.base_pay_type) + ":" + payType()
                        )
                        text += (UiUtil.getStringRes(R.string.base_pay_type) + UiUtil.getStringRes(R.string.base_successful_repair)).toString() + ","
                        SpUtils.put(MMKVName.PAY_TYPE, Gson().toJson(arrayListState))

                    }

                    val mCreditCardPresenter: CreditCardPresenter =
                        CreditCardPresenter.getCreditCardContract()
                    if (mCreditCardPresenter != null) {
                        if (mCreditCardPresenter.is_ready()) {
                            getValue(2, true)
                            text += "通讯成功"
                        } else {
                            getValue(2, false)
                            text += "通讯失败"
                        }
                    } else {
                        text += "通讯失败"
                    }
                    ToastUtil.showToast(text)
                }

                //  Name.BILL_FUNCTION -> dismiss()
                Name.NETWORK_FUNCTION -> dismiss()
            }

            R.id.btn_cancel -> dismiss()
        }
    }

    /**
     * 改变对应的状态
     *
     * @param position 要改变的checkbox的位置
     */
    private fun getValue(position: Int, flag: Boolean, message: String?) {
        val view: View = mBinding.rvCheck.getChildAt(position)

        if (null != mBinding.rvCheck.getChildViewHolder(view)) {
            val viewHolder: CheckDialogAdapter.MyViewHolder =
                mBinding.rvCheck.getChildViewHolder(view) as CheckDialogAdapter.MyViewHolder
            viewHolder.ivSimSuccess.setVisibility(View.VISIBLE)
            if (flag) {
                viewHolder.ivSimSuccess.setImageDrawable(UiUtil.getDrawableRes(R.drawable.icon_right))
            } else {
                viewHolder.ivSimSuccess.setImageDrawable(UiUtil.getDrawableRes(R.drawable.pic_shurucuowu))
            }
            if (message != null) {
                viewHolder.tvItemWifiNameContext.setVisibility(View.VISIBLE)
                viewHolder.tvItemWifiNameContext.setText(message)
            }
            viewHolder.zLoadingView.setVisibility(View.GONE)
        }
    }

    val TAG: String = "CheckDialog"
    fun setData(data: Array<String>, simFunction: String?) {
        val productStr = SpUtils.getString(MMKVName.PAY_TYPE, "")
        if (productStr != "") {
            arrayListState = Gson().fromJson(
                productStr,
                object : TypeToken<HashMap<String, PayTypeBean>?>() {}.type
            )

        }
        Log.d("backinfo", "支付类型：" + Gson().toJson(arrayListState))
        adapter = CheckDialogAdapter(context, data)
        mBinding.rvCheck.setLayoutManager(LinearLayoutManager(context))
        this.csimFunction = simFunction
        adapter?.setOnItemClickListener(object : CheckDialogAdapter.onItemClickListener {
            override fun onItemClick(view: View?, postion: Int) {
                Handler().postDelayed({

                    when (csimFunction) {
                        Name.SIM_FUNCTION -> {
                            mBinding.btnApply.setText(UiUtil.getStringRes(R.string.base_confirm))
                            //开始使用工具类的逻辑进行判断。
                            if (SimNetworkUtils.test()) {
                                getValue(0, true)
                            } else {
                                getValue(0, false)
                            }
                            if (SimNetworkUtils.test2()) {
                                getValue(1, true)
                            } else {
                                getValue(1, false)
                            }
                            CoroutineScope(Dispatchers.Main).launch {
                                  main()
                            }

                        }

                        Name.NAYAX_FUNCTION -> {
                            mBinding.btnApply.setText(UiUtil.getStringRes(R.string.base_repair))
                            var nayax = arrayListState[PayEnum.NAYAX.code]
                            Log.d("backinfo", "")
                            if (nayax != null && nayax.isSelected) {
                                getValue(
                                    0,
                                    true,
                                    UiUtil.getStringRes(R.string.base_pay_type) + ":" + payType()
                                )
                            } else {
                                getValue(
                                    0,
                                    false,
                                    UiUtil.getStringRes(R.string.base_pay_type) + ":" + payType()
                                )
                            }
                            var alwaysIdle = SpUtils.getBoolean(Name.ALWAYS_IDLE, false)
                            if (alwaysIdle == true) {
                                getValue(1, true, UiUtil.getStringRes(R.string.base_open_wifi))
                            } else {
                                getValue(1, true, UiUtil.getStringRes(R.string.base_btnClose))
                            }
                            val mCreditCardPresenter: CreditCardPresenter =
                                CreditCardPresenter.getCreditCardContract()
                            Handler().postDelayed({
                                if (mCreditCardPresenter != null) {
                                    if (mCreditCardPresenter.is_ready()) {
                                        getValue(2, true)
                                    } else {
                                        getValue(2, false)
                                    }
                                }
                            }, 5000)
                            val ox = SpUtils.getString(Name.OXSERIALPORT, "ttyS1")
                            getValue(3, true, ox)
                        }

                        /* Name.BILL_FUNCTION -> {
                             binding.btnApply.setText(UiUtil.getStringRes(R.string.confirm))
                             val protocol: String = Hawk.get(Name.NOTE_COMMUNICATION, Name.MDB)
                             getValue(0, true, protocol)
                             val billBeanDao: BillBeanDao =
                                 MyApplication.getInstances().getDaoSession().getBillBeanDao()
                             val billBeans: List<BillBean> = billBeanDao.loadAll()
                             Log.d(CheckDialog.TAG, "billBean run: " + billBeans!!.size)

                             if (billBeans != null && billBeans.size >= 1) {
                                 getValue(1, false, billBeans[billBeans.size - 1].toString())
                             } else {
                                 getValue(1, true, UiUtil.getStringRes(R.string.none))
                             }
                             if (Hawk.get(Name.TRUSTEESHIP, false)) {
                                 getValue(2, true, UiUtil.getStringRes(R.string.collocation))
                             } else {
                                 getValue(2, true, UiUtil.getStringRes(R.string.no_collocation))
                             }
                             val mdb: String = Hawk.get(Name.MDBSERIALPORT, "ttyS3")
                             getValue(3, true, mdb)
                         }*/

                        Name.NETWORK_FUNCTION -> {
                            mBinding.btnApply.setText(UiUtil.getStringRes(R.string.base_confirm))

                            if (Global.isNetWork) {
                                getValue(0, true)
                            } else {
                                getValue(0, false)
                            }
                        }
                    }
                }, 2000)
            }
        })
        mBinding.rvCheck.setAdapter(adapter)
    }


    /**
     * sim卡接口查询
     */
    suspend fun main() {
        errorCheckVM?.checkSim()
    }

    fun setSimStatus(toString: String?, isStatus: Boolean) {
        getValue(2, isStatus, toString)
    }

    /**
     * 改变对应的状态
     *
     * @param position 要改变的checkbox的位置
     */
    private fun getValue(position: Int, flag: Boolean) {
        val view: View = mBinding.rvCheck.getChildAt(position)

        if (null != mBinding.rvCheck.getChildViewHolder(view)) {
            val viewHolder: CheckDialogAdapter.MyViewHolder =
                mBinding.rvCheck.getChildViewHolder(view) as CheckDialogAdapter.MyViewHolder
            viewHolder.ivSimSuccess.visibility = View.VISIBLE
            if (flag) {
                viewHolder.ivSimSuccess.setImageDrawable(UiUtil.getDrawableRes(R.drawable.icon_right))
            } else {
                viewHolder.ivSimSuccess.setImageDrawable(UiUtil.getDrawableRes(R.drawable.pic_shurucuowu))
            }
            viewHolder.zLoadingView.visibility = View.GONE
        }
    }


    fun payType(): String {
        var payType = ""
        payType = when (SpUtils.getInt(Name.PAY_TYPE, -1)) {
            1 -> UiUtil.getStringRes(R.string.base_pay_no)
            2 -> UiUtil.getStringRes(R.string.base_pay_online)
            3 -> UiUtil.getStringRes(R.string.base_pay_offline)

            else -> UiUtil.getStringRes(R.string.base_pay_type)
        }
        return payType
    }
}