package com.zj365.health.act.datamanage

import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
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.util.CommonToastUtils
import com.xty.common.util.CommonUtils
import com.zj365.health.R
import com.zj365.health.adapter.IllAdapter
import com.zj365.health.databinding.ActIllHistoryBinding
import com.zj365.health.vm.MedicalHistoryVm
import com.xty.network.model.MedicBean
import org.json.JSONArray
import org.json.JSONObject

/**
 * 病史
 */
@Route(path = ARouterUrl.ILL_HISTORY)
class IllHistoryAct : BaseVmAct<MedicalHistoryVm>() {
    val binding by lazy { ActIllHistoryBinding.inflate(layoutInflater) }
    val mAdapter by lazy { IllAdapter() }
    var idStr = StringBuilder()
    var operationView: LinearLayout? = null
    var traumaView: LinearLayout? = null
    var isCheck = true

    var ids: String? = null
    var hasOperation = true
    var hasTrauma = true
    var isShowFoot = true
    var inputPosition = 0 //
    var nameStr = StringBuilder()

    var other = ""
    var tumour = ""

    //    var arrays = ""
    var type1Size = 0
    var type2Size = 0

    //    var bottomView: View? = null  //底部view
    val timeSel by lazy { TimeSelect(this) {} }

    var userId:String?=null
    override fun setLayout() = binding.root

    override fun initData() {
        super.initData()
        isDarkBar = true
        userId = intent.getStringExtra("userId")
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text = "既往病史"
        binding.title.mIvBack.setOnClickListener { finish() }

        binding.mConfirm.setOnClickListener {
            val trim = binding.mEditInfo.text.toString().trim()
            if (trim.isNullOrEmpty()) {
                return@setOnClickListener
            }
            mAdapter.data[inputPosition].inputStr = trim
            mAdapter.notifyItemChanged(inputPosition)
            hideInputSoft()
        }
        initAdapter()
        mViewModel.getUserInfo(userId)

        binding.save.setOnClickListener {

            val ills = getLastData()
            getSelectList()
            val selectIds = idStr.toString()
            val name = nameStr.toString()

            mAdapter.data.forEach {
                if (TextUtils.equals(it.dictName, "肿瘤")) {
                    tumour = it.inputStr
                }

                if (TextUtils.equals(it.dictName, "其他")) {
                    other = it.inputStr
                }
            }
            mViewModel.submit(name, selectIds, tumour, other, ills.toString(),userId)
        }
    }

    /**
     * 最后信息
     */
    private fun getLastData(): JSONArray {
        val array = JSONArray()
        if (hasOperation) {//手术
            if (operationView!!.childCount > 0) {
                for (i in 0 until operationView!!.childCount) {
                    var parent = operationView!!.getChildAt(i)
                    var bean = parent.tag as ChildViewInfo
                    var name = bean.mEdit!!.text.toString().trim()
                    var time = bean.mText!!.text.toString().trim()
                    if (name.isNotEmpty() && time.isNotEmpty()) {
                        var json = JSONObject()
                        json.put("name", name)
                        json.put("time", time)
                        json.put("userId", CommonUtils.getMyUserId())
                        json.put("type", 1)
                        array.put(json)
                    }
                }
            }
        }
        if (hasTrauma) {//外伤
            if (traumaView!!.childCount > 0) {
                for (i in 0 until traumaView!!.childCount) {
                    var parent = traumaView!!.getChildAt(i)
                    var bean = parent.tag as ChildViewInfo
                    var name = bean.mEdit!!.text.toString().trim()
                    var time = bean.mText!!.text.toString().trim()
                    if (name.isNotEmpty() && time.isNotEmpty()) {
                        var json = JSONObject()
                        json.put("name", name)
                        json.put("time", time)
                        json.put("userId", CommonUtils.getMyUserId())
                        json.put("type", 2)
                        array.put(json)
                    }

                }
            }
        }
        return array
    }

    override fun liveObserver() {

        mViewModel.allData.observe(this) { it ->
            mViewModel.getMedicHistory()
            it.data.user?.let {
                ids = it.historyId
                other = if (it.other == null) "" else it.other!!
                tumour = if (it.tumour == null) "" else it.tumour!!

                var array = JSONArray()
                it.diseaseList.forEach {
                    var json = JSONObject()
                    json.put("name", it.name)
                    json.put("type", it.type)
                    json.put("time", it.time)
                    array.put(json)
                }

                type1Size = 0
                type2Size = 0

                if (array.length() > 0) {
                    for (i in 0 until array.length()) {
                        var json = JSONObject(array[i].toString())
                        if (json.get("type").toString().toInt() == 1) {
                            ++type1Size
                        } else {
                            ++type2Size
                        }
                    }
                }
                medicBottom()
                if (array.length() > 0) {
                    for (i in 0 until array.length()) {
                        var json = JSONObject(array[i].toString())
                        var name = ""
                        json.get("name")?.let {
                            name = it.toString()
                        }
                        var time = ""
                        json.get("time")?.let {
                            time = it.toString()
                        }
                        if (json.get("type").toString().toInt() == 1) {

                            addChild(
                                operationView!!,
                                0,
                                name,
                                time
                            )
                        } else {
                            addChild(
                                traumaView!!,
                                1,
                                name,
                                time
                            )
                        }
                    }
                }
            }
        }

        mViewModel.setBasic.observe(this) {
            finish()
            CommonToastUtils.showSucceedToast("保存成功")
        }

        mViewModel.medicLive.observe(this) {
            it.data.forEach { bean ->

                ids?.let {
                    if (it.contains("${bean.id}")) {
                        bean.isSelect = true
                        if (bean.dictName == "无") {
                            mAdapter.isCheckNone = true
                        }
                    }
                }

                if (bean.dictName == "肿瘤" && tumour.isNotEmpty()) {
                    bean.isSelect = true
                    bean.inputStr = tumour
                } else if (bean.dictName == "其他" && other.isNotEmpty()) {
                    bean.isSelect = true
                    bean.inputStr = other
                }
            }
            mAdapter.setNewInstance(it.data)
            type1Size = 0
            type2Size = 0
        }
    }

    private fun initAdapter() {
        binding.mRecycle.layoutManager = LinearLayoutManager(this)
        binding.mRecycle.adapter = mAdapter
        mAdapter.addChildClickViewIds(R.id.mTvName, R.id.mInput)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = adapter.getItem(position) as MedicBean
            if (!isShowFoot) {
                return@setOnItemChildClickListener
            }
            when (view.id) {
                R.id.mTvName -> {
                    item.isSelect = !item.isSelect
                    mAdapter.isCheckNone = item.dictName == "无"
                    mAdapter.notifyDataSetChanged()
                    hideInputSoft()
                }

                R.id.mInput -> {
                    inputPosition = position
                    if (item.dictName == "肿瘤") {
                        shouInputSoft("请输入肿瘤名称", item.inputStr)
                    } else if (item.dictName == "其他") {
                        shouInputSoft("请输入其他疾病", item.inputStr)
                    }
                }
            }
        }
    }


    private fun medicBottom() {
        var view = LayoutInflater.from(this).inflate(R.layout.layout_ill_bottom, null, false)

        binding.mTrauma.addView(view)
//        bottomView = view
        operationView = view.findViewById(R.id.mParent1)
        traumaView = view.findViewById(R.id.mParent2)
        //addChild(operationView!!)
        // addChild(traumaView!!)
        var textAddView1 = view.findViewById<TextView>(R.id.mAddView1)
        var textAddView2 = view.findViewById<TextView>(R.id.mAddView2)
        if (isShowFoot) {
            textAddView1.visibility = View.VISIBLE
            textAddView2.visibility = View.VISIBLE
        } else {
            textAddView1.visibility = View.GONE
            textAddView2.visibility = View.GONE
        }

        textAddView1.setOnClickListener {
            addChild(operationView!!)
        }
        textAddView2.setOnClickListener { addChild(traumaView!!, 1) }

        if (isShowFoot) {
            view.findViewById<RadioGroup>(R.id.mRadio1)
                .setOnCheckedChangeListener { group, checkedId ->
                    when (checkedId) {
                        R.id.mOperation1 -> {

                            hasOperation = false
                            operationView!!.visibility = View.GONE
                            textAddView1.visibility = View.GONE
                        }

                        R.id.mOperation2 -> {
                            hasOperation = true
                            operationView!!.visibility = View.VISIBLE
                            textAddView1.visibility = View.VISIBLE

                            if (operationView!!.childCount == 0) {
                                addChild(operationView!!)
                            }
                        }
                    }
                }

            view.findViewById<RadioGroup>(R.id.mRadio2)
                .setOnCheckedChangeListener { group, checkedId ->
                    when (checkedId) {
                        R.id.mTrauma1 -> {
                            hasTrauma = false
                            textAddView2.visibility = View.GONE
                            traumaView!!.visibility = View.GONE
                        }

                        R.id.mTrauma2 -> {
                            hasTrauma = true
                            traumaView!!.visibility = View.VISIBLE
                            textAddView2.visibility = View.VISIBLE

                            if (traumaView!!.childCount == 0) {
                                addChild(traumaView!!, 1)
                            }
                        }
                    }
                }
        } else {
            view.findViewById<RadioButton>(R.id.mOperation1).isEnabled = false
            view.findViewById<RadioButton>(R.id.mOperation2).isEnabled = false
            view.findViewById<RadioButton>(R.id.mTrauma2).isEnabled = false
        }
        if (type1Size > 0) {
            view.findViewById<RadioButton>(R.id.mOperation2).isChecked = true
        } else {

            view.findViewById<RadioButton>(R.id.mOperation1).isChecked = true
        }
        if (type2Size > 0) {
            view.findViewById<RadioButton>(R.id.mTrauma2).isChecked = true
        } else {
            view.findViewById<RadioButton>(R.id.mTrauma1).isChecked = true
        }
    }


    /**
     * 添加子view
     */
    private fun addChild(
        parentView: LinearLayout,
        type: Int = 0,
        name: String = "",
        time: String = ""
    ) {
        var childView =
            LayoutInflater.from(this).inflate(R.layout.item_foot_ill_layout, null, false)
        var deleteView = childView.findViewById<TextView>(R.id.mDelete)
        if (isShowFoot) {
            deleteView.visibility = View.VISIBLE
        } else {
            deleteView.visibility = View.GONE
        }

        childView.findViewById<EditText>(R.id.mName).apply {
            isEnabled = isShowFoot
            hint = if (type == 0) {
                "请输入手术名称"
            } else {
                "请输入外伤名称"
            }
            setText(name)
        }
        childView.findViewById<TextView>(R.id.mTvTime).apply {
            isEnabled = isShowFoot
            text = time
        }


        //删除用的
        var bean = ChildViewInfo().apply {
            this.view = parentView
            this.position = parentView.childCount
            this.mEdit = childView.findViewById(R.id.mName)
            this.mText = childView.findViewById(R.id.mTvTime)
        }
        childView.tag = bean
        deleteView.tag = bean

        deleteView.setOnClickListener {
            var childInfo = it.tag as ChildViewInfo
            reorder(childInfo.view!!, it)
        }
        childView.findViewById<TextView>(R.id.mTvTime).setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            timeSel.selectTime(it)
        }
        parentView.addView(childView)
    }

    /**
     * 重新调整顺序
     */
    private fun reorder(view: LinearLayout, delete: View) {
        var reversed = (0 until view.childCount).reversed()
        for (i in reversed) {
            if (view.getChildAt(i) == delete.parent as View) {
                view.removeViewAt(i)
                view.invalidate()
                return
            }
        }

    }

    /**
     * 获取以选择的数据 回传
     */
    private fun getSelectList() {

        mAdapter.data.forEach {
            if (it.isSelect) {
                if (idStr.isEmpty()) {
                    idStr.append("${it.id}")
                    if (it.dictName == "肿瘤") {
                        tumour = it.inputStr
                    } else if (it.dictName == "其他") {
                        other = it.inputStr
                    }

                    nameStr.append(if (nameStr.isNullOrEmpty()) it.dictName else ",${it.dictName}")

                } else if (idStr.contains("156") || it.dictName == "无") {
                    idStr.clear()
                    nameStr.clear()
                    idStr.append("${it.id}")
                    nameStr.append("${it.dictName}")
                } else {
                    idStr.append(",${it.id}")
                    if (it.dictName == "肿瘤") {
                        tumour = it.inputStr
                    } else if (it.dictName == "其他") {
                        other = it.inputStr
                    }

                    nameStr.append(",${it.dictName}")
                }
            }
        }
    }

    inner class ChildViewInfo {
        var view: LinearLayout? = null
        var mEdit: EditText? = null
        var mText: TextView? = null
        var position: Int = 0
    }


    private fun shouInputSoft(inputHint: String, value: String) {
        (binding.mEditInfo.parent as View).visibility = View.VISIBLE
        binding.mEditInfo.isFocusable = true
        binding.mEditInfo.setText(value)
        binding.mEditInfo.hint = inputHint
        binding.mEditInfo.isSelected = true
        RxKeyboardTool.showSoftInput(this, binding.mEditInfo)

    }

    private fun hideInputSoft() {
        (binding.mEditInfo.parent as View).visibility = View.GONE
        binding.mEditInfo.setText("")
        binding.mEditInfo.clearFocus()
        binding.mEditInfo.isSelected = false
        RxKeyboardTool.hideSoftInput(this)
    }

    override fun keyBoardHind(isPopup: Boolean) {
        super.keyBoardHind(isPopup)
        if (!isPopup) {
            hideInputSoft()
        }
    }

}