package com.dlc.chemical.ui.waring

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import com.dlc.chemical.R
import com.dlc.chemical.databinding.ActivityWaringDetailBinding
import com.dlc.chemical.iflytek.AudioPlayerManager
import com.dlc.chemical.ui.MainActivity
import com.dlc.chemical.ui.common.BaseCountDownActivity
import com.dlc.chemical.ui.dialog.SuccessDialog
import com.dlc.chemical.ui.widget.TitleBar
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.UpdateAlarmRecordReq
import com.rc.httpcore.vo.response.AioAlarmRecordVo

/**
 * 预警详情
 *
 * @author ReiChin_
 */
class WaringDetailActivity : BaseCountDownActivity<ActivityWaringDetailBinding>(),
    TitleBar.TitleListener {

    private var mAlarmRecord: AioAlarmRecordVo? = null

    override fun createViewBinding() = ActivityWaringDetailBinding.inflate(layoutInflater)

    override fun initViews(savedInstanceState: Bundle?) {
        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.setTitleInfoFromSp()

        viewBinding.handlingStatus.setOnClickListener {
            if ("3" != mAlarmRecord?.alarmMode && "2" != mAlarmRecord?.handlingStatus) return@setOnClickListener

            val items = arrayOf("待处理", "已处理")
            AlertDialog.Builder(this)
                .setItems(items) { _, which ->
                    viewBinding.handlingStatus.text = items[which]
                }.show()
        }

        viewBinding.cancel.setOnClickListener { finish() }
        viewBinding.save.setOnClickListener {
            handleWaring()
        }
    }

    private fun handleWaring() {
        if (null == mAlarmRecord) return

        val status = viewBinding.handlingStatus.text
        if ("待处理" != status && "已处理" != status) {
            showToast("请选择处理状态！")
            return
        }

        showLoading("保存中...")
        val param = UpdateAlarmRecordReq().apply {
            id = mAlarmRecord!!.id
            handlingStatus = if ("待处理" == status) "1" else "2"
        }
        val disposable = ApiRepository.updateAlarmRecord(param)
            .subscribe({
                dismissLoading()
                dispatchHandleSuccess()
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    private fun dispatchHandleSuccess() {
        AudioPlayerManager.speakVoice(R.raw.audio_handle_completed)
        SuccessDialog(this, "处理完成").apply {
            setCancelable(false)
            setOnDismissListener {
                setResult(RESULT_OK)
                finish()
            }
        }.show()
    }

    override fun initData() {
        queryAlarmRecordDetail()
    }

    private fun queryAlarmRecordDetail() {
        showLoading("查询中...")
        val id = intent.getStringExtra("id") ?: ""
        val disposable = ApiRepository.queryAlarmRecordDetail(id)
            .subscribe({ data ->
                dismissLoading()
                mAlarmRecord = data
                refreshUI()
            }, { throwable ->
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    private fun refreshUI() {
        mAlarmRecord?.let { data ->
            // 报警时间
            viewBinding.alarmTime.text = data.alarmTime
            // 报警内容
            viewBinding.alarmContent.text = data.alarmContent
            // 学院
            viewBinding.deptName.text = data.deptName
            // 实验室
            viewBinding.subName.text = data.subName
            // 实验室负责人
            viewBinding.liableUserNames.text = data.adminNames
            // 安全责任人
            viewBinding.safeUserName.text = data.safeUserNames
            // 报警方式
            viewBinding.alarmMode.text = data.decodeAlarmMode()
            // 处理状态
            viewBinding.handlingStatus.text = data.decodeHandlingStatus()
            // 处理状态：1-待处理，2-已处理
            if ("1" == data.handlingStatus) {
                viewBinding.handlingStatus.setTextColor(Color.parseColor("#FFFF7300"))
            } else {
                viewBinding.handlingStatus.setTextColor(Color.parseColor("#FF333333"))
            }
            // 报警方式（1.系统通知，2.声光报警，3.短信通知）
//            if ("3" == data.alarmMode) {
//                // 短信报警
//                if ("2" != data.handlingStatus) { // 非已处理
//                    viewBinding.cancel.visibility = View.VISIBLE
//                    viewBinding.save.visibility = View.VISIBLE
//
//                    handlingStatusViewCompoundDrawable()
//                } else {
//                    viewBinding.cancel.visibility = View.GONE
//                    viewBinding.save.visibility = View.GONE
//                }
//
//                // 报警短信号码
//                viewBinding.waringMsgPhone.text = data.liableUserIds
//                viewBinding.waringMsgPhoneGroup.visibility = View.VISIBLE
//            } else {
//                viewBinding.cancel.visibility = View.GONE
//                viewBinding.save.visibility = View.GONE
//
//                viewBinding.waringMsgPhoneGroup.visibility = View.GONE
//            }

            if ("2" == data.alarmMode) {
                // 短信报警
                if ("2" != data.handlingStatus) { // 非已处理
                    viewBinding.cancel.visibility = View.VISIBLE
                    viewBinding.save.visibility = View.VISIBLE

                    handlingStatusViewCompoundDrawable()
                } else {
                    viewBinding.cancel.visibility = View.GONE
                    viewBinding.save.visibility = View.GONE
                }

                // 报警短信号码
                viewBinding.waringMsgPhone.text = data.liableUserIds
                viewBinding.waringMsgPhoneGroup.visibility = View.VISIBLE
            } else {
                viewBinding.cancel.visibility = View.GONE
                viewBinding.save.visibility = View.GONE

                viewBinding.waringMsgPhoneGroup.visibility = View.GONE
            }
        }
    }

    private fun handlingStatusViewCompoundDrawable() {
        viewBinding.handlingStatus.setBackgroundResource(R.drawable.shape_rect_round_3_stroke_e0)
        viewBinding.handlingStatus.gravity = Gravity.CENTER_VERTICAL
        val paddingLeft =
            TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                7f,
                resources.displayMetrics
            )
                .toInt()
        viewBinding.handlingStatus.setPadding(
            paddingLeft,
            viewBinding.handlingStatus.paddingTop,
            paddingLeft,
            viewBinding.handlingStatus.paddingBottom
        )
        val drawableEnd = ContextCompat.getDrawable(this, R.mipmap.ic_arrow_down_cd)
        viewBinding.handlingStatus.compoundDrawablePadding =
            TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                4f,
                resources.displayMetrics
            )
                .toInt()
        viewBinding.handlingStatus.setCompoundDrawablesWithIntrinsicBounds(
            null,
            null,
            drawableEnd,
            null
        )
    }

    override fun onHomeViewClicked(view: View) {
        startActivity(Intent(this, MainActivity::class.java))
    }

    override fun onBackViewClicked(view: View) {
        finish()
    }

}