package com.zj365.health.act

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.core.view.get
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.tamsiree.rxkit.RxKeyboardTool
import com.xty.base.act.BaseVmAct
import com.xty.common.TimeSelect
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.XTangUploadEvent
import com.xty.common.recycleUtils.RecycleItem
import com.xty.common.util.CommonToastUtils
import com.xty.common.weight.DecimalInputTextWatcher
import com.zj365.health.R
import com.zj365.health.adapter.TimeStatusAdapter
import com.zj365.health.databinding.ActXtangUploadBinding
import com.zj365.health.vm.XTangVm
import com.zj365.health.weight.DialogTip
import com.zj365.health.weight.HealthDialog
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import org.json.JSONObject

/**
 *
 * 血糖上传
 */
@Route(path = ARouterUrl.XT_UPLOAD)
class XTangUploadAct : BaseVmAct<XTangVm>() {

    private val binding by lazy { ActXtangUploadBinding.inflate(layoutInflater) }
    override fun setLayout() = binding.root

    var userId = ""
    private var isCalibration = false

    private val tagArray by lazy { resources.getStringArray(R.array.xt_time_array) }
    private val uploadDialog by lazy {
        DialogTip(this, "是否确认上传?") {
            //确认数据上传
            upload()

        }
    }
    private val successDialog by lazy {
        HealthDialog(this, true, "尊敬的用户您好，系统将在1个小时后完成血糖校准，请您耐心等待！") {

            finish()
        }
    }
    val timSelect by lazy {
        TimeSelect(this) {
        }.apply {
            showHour = true
            showMin = true
            showSec = false
        }
    }

    override fun initData() {
        super.initData()
        intent.extras?.let {
            if (it.containsKey("id")) {
                userId = it.getString("id").toString()
            }
            isCalibration = it.getBoolean("isCalibration", false)
        }
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text =
            if (isCalibration) getString(R.string.xt_calibration) else getString(R.string.xt_upload)

        binding.mConfirm.isSelected = true

        binding.title.mIvBack.setOnClickListener(onClickListener)
        binding.jiaozhijilu.setOnClickListener(onClickListener)
        binding.mConfirm.setOnClickListener(onClickListener)
        binding.mAdd.setOnClickListener(onClickListener)
        binding.mTip.setOnClickListener {
            val webUrl = "https://mp.weixin.qq.com/s/FxNnUSkmEo-q8sg9leSisQ"
            bundle.clear()
            bundle.putString("title", "血糖校准须知")
            bundle.putString("url", webUrl)
            RouteManager.goAct(ARouterUrl.WEB_ACT, bundle)
        }
        addChildViews()
    }


    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    private fun addChildViews() {
        val childView = LayoutInflater.from(this).inflate(R.layout.xtang_upload_item, null)
        val viewIndex = binding.childLayout.childCount//view下标
        val viewNum = viewIndex + 1//页码 第几次（总共只能21组数据）
        childView.findViewById<TextView>(R.id.mTitle).text =
            "第${viewNum}次"
        val mTvTimeView = childView.findViewById<TextView>(R.id.mTvTime)
        mTvTimeView.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            timSelect.selectTime(it, "yyyy-MM-dd HH:mm")
        }

        val editText = childView.findViewById<EditText>(R.id.mTvNum)
        //输入总长度5位，小数1位
        editText.addTextChangedListener(
            DecimalInputTextWatcher(editText, 6, 2)
        )

        val recyclerView = childView.findViewById<RecyclerView>(R.id.mRecycle)

        val recycleItem = RecycleItem(baseContext, 4, 1)
        recycleItem.setSpace(40, 40)
        recyclerView.addItemDecoration(recycleItem)
        recyclerView.layoutManager = GridLayoutManager(baseContext, 4)
        val adapter = TimeStatusAdapter()
        recyclerView.adapter = adapter
        adapter.setOnItemClickListener { _, _, position ->
            adapter.positionSelect = position
            adapter.notifyDataSetChanged()
        }
        adapter.setNewInstance(tagArray.toMutableList())

        binding.childLayout.addView(
            childView
        )

        if (viewNum > 20) {//最多上传21组数据,不能大于区间数量
            binding.mAdd.visibility = View.GONE
        }
    }

    private fun getChildView(index: Int, childId: Int = 0): View {
        return if (childId == 0) binding.childLayout[index]
        else binding.childLayout[index].findViewById(childId)
    }

    private var onClickListener = View.OnClickListener {
        when (it.id) {
            //返回
            R.id.mIvBack -> {
                finish()
            }
            //右上角上传记录
            R.id.mTvRight -> {
                bundle.clear()
                bundle.putString("id", userId)
                RouteManager.goAct(ARouterUrl.XT_HISTORY, bundle)
            }
            //保存
            R.id.mConfirm -> {
                uploadDialog.show()
            }
            //添加
            R.id.mAdd -> {
                addChildViews()
            }

            R.id.jiaozhijilu -> {
                bundle.clear()
                bundle.putString("id", userId)
                RouteManager.goAct(ARouterUrl.XT_HISTORY, bundle)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun upload() {
        val jsonArray = JSONArray()

        for (i in 0 until binding.childLayout.childCount) {
            val tvTime = (getChildView(i, R.id.mTvTime) as TextView)
            val bloodsugar = (getChildView(i, R.id.mTvNum) as EditText)

            if (tvTime.text.isNullOrEmpty() && !bloodsugar.text.isNullOrEmpty()) {
                tvTime.hint = "请选择测量时间"
                CommonToastUtils.showToast("测量时间未填写")
                return
            }

            if (!tvTime.text.isNullOrEmpty() && bloodsugar.text.isNullOrEmpty()) {
                bloodsugar.hint = "请输入测量值"
                CommonToastUtils.showToast("测量数据未填写")
                return
            }

            if (!bloodsugar.text.isNullOrEmpty() && bloodsugar.text.toString().toFloat() > 33.3) {
                CommonToastUtils.showToast("请确认测量数据是否正确，如血糖值>33.3请填写33.3")
                return
            }

            if (tvTime.text.isNullOrEmpty() || bloodsugar.text.isNullOrEmpty() || bloodsugar.text.toString()
                    .toFloat() < 0
            ) {
                continue
            }

            tvTime.text = "${tvTime.text}:00"//手动拼接秒

            val json = JSONObject()
            json.put(
                "tag",
                tagArray[((getChildView(
                    i,
                    R.id.mRecycle
                ) as RecyclerView).adapter as TimeStatusAdapter).positionSelect]
            )
            json.put("hour", tvTime.text.toString())
            json.put("bloodsugar", bloodsugar.text.toString())
            jsonArray.put(json)
        }

        if (jsonArray.length() < 1) {
            CommonToastUtils.showToast("测量记录填写有误，请检查后重新提交！")
            return
        }

        mViewModel.xtUpload(jsonArray)
    }


    override fun liveObserver() {
        mViewModel.upload.observe(this) {
            if (null == it.data) {
                CommonToastUtils.showToast("上传失败")
                return@observe
            }

            it.data.let { result ->
                if (result.contains("成功") || result.contains("手表未采集到")) {

                    bundle.clear()
                    bundle.putString("id", userId)
                    RouteManager.goAct(ARouterUrl.XT_HISTORY, bundle)

                    CommonToastUtils.showToast(result)
                    EventBus.getDefault().post(XTangUploadEvent())
                    finish()
                } else {
                    CommonToastUtils.showToast(result)
                    successDialog.setCancelable(false)
                    successDialog.setCanceledOnTouchOutside(false)
                    successDialog.show()
                }
            }
        }
    }
}