package com.zj365.health.act

import android.annotation.SuppressLint
import android.graphics.Color
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.MedicalAdapter
import com.zj365.health.databinding.ActMedicalHistoryBinding
import com.zj365.health.vm.MedicalHistoryVm
import com.xty.network.model.MedicBean
import org.json.JSONArray
import org.json.JSONObject

/**
 * 病史
 */
@Route(path = ARouterUrl.MEDICAL_HISTORY)
class MedicalHistoryAct : BaseVmAct<MedicalHistoryVm>() {

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

    private val mAdapter by lazy { MedicalAdapter() }
    private var idStr = StringBuilder()
    private var operationView: LinearLayout? = null
    private var traumaView: LinearLayout? = null
    private var isCheck = true
    private var ids = ""
    private var hasOperation = true
    private var hasTrauma = true
    private var isShowFoot = true
    private var inputPosition = 0 //
    private var nameStr = StringBuilder()
    private var other = ""
    private var tumour = ""
    private var arrays = ""
    private var type1Size = 0
    private var type2Size = 0
    private var bottomView: View? = null  //底部view
    private val timeSel by lazy { TimeSelect(this) {} }

    override fun initData() {
        super.initData()
        isDarkBar = true
        intent.extras?.let {
            if (it.containsKey("ids")) {
                ids = it.getString("ids").toString()
            }
            other = it.getString("other").toString()
            tumour = it.getString("tumour").toString()
            arrays = it.getString("arrays").toString()
        }
        isShowFoot = intent.extras!!.getBoolean("isShowFoot", false)
        mAdapter.isShow = !isShowFoot
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text = getString(R.string.medic_history)
        binding.title.mIvBack.setOnClickListener { finish() }
        binding.title.mTvRight.apply {
            text = getString(R.string.confirm)
            setTextColor(Color.parseColor("#3B4343"))
            visibility = if (isShowFoot) View.VISIBLE else View.GONE
            setOnClickListener {
                getSelectList()
                val lastIds = nameStr.toString().replace(",", "")
                if (lastIds.isEmpty()) {
                    CommonToastUtils.showToast("请选择疾病类型")
                    return@setOnClickListener
                }
                bundle.clear()
                bundle.putString("ids", idStr.toString())
                bundle.putString("names", nameStr.toString())
                bundle.putString("other", other)
                bundle.putString("tumour", tumour)
                bundle.putString("diseaseList", getLastData().toString())
                intent.putExtras(bundle)
                setResult(RESULT_OK, intent)
                finish()
            }
        }


        binding.mConfirm.setOnClickListener {
            val trim = binding.mEditInfo.text.toString().trim()
            if (trim.isNullOrEmpty()) {
                return@setOnClickListener
            }
            mAdapter.isCheckNone = false
            mAdapter.data[inputPosition].inputStr = trim
            mAdapter.data[inputPosition].isSelect = true
          //  mAdapter.notifyItemChanged(inputPosition)
            mAdapter.notifyDataSetChanged()
            hideInputSoft()
        }
        //设置起始时间
        timeSel.startDate.set(1950, 0, 1)
        initAdapter()
        mViewModel.getMedicHistory()
    }

    /**
     * 最后信息
     */
    private fun getLastData(): JSONArray {
        val array = JSONArray()
        if (hasOperation) {//手术
            if (operationView!!.childCount > 0) {
                for (i in 0 until operationView!!.childCount) {
                    val parent = operationView!!.getChildAt(i)
                    val bean = parent.tag as ChildViewInfo
                    val name = bean.mEdit!!.text.toString().trim()
                    val time = bean.mText!!.text.toString().trim()
                    if (name.isNotEmpty() && time.isNotEmpty()) {
                        val 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) {
                    val parent = traumaView!!.getChildAt(i)
                    val bean = parent.tag as ChildViewInfo
                    val name = bean.mEdit!!.text.toString().trim()
                    val time = bean.mText!!.text.toString().trim()
                    if (name.isNotEmpty() && time.isNotEmpty()) {
                        val 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.medicLive.observe(this) {
            it.data.forEach { bean ->
                if (ids.contains("${bean.id}")) {
                    bean.isSelect = true
                    if (bean.dictName == "无") {
                        mAdapter.isCheckNone = true
                    }
                }
                if (bean.dictName == "肿瘤") {
                    bean.inputStr = tumour
                } else if (bean.dictName == "其他") {
                    bean.inputStr = other
                }
            }
            mAdapter.setNewInstance(it.data)
            val array = JSONArray(arrays)
            //加载回显示数据
            type1Size = 0
            type2Size = 0

            if (array.length() > 0) {
                for (i in 0 until array.length()) {
                    val 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()) {
                    val 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!!,
                            name,
                            time
                        )
                    } else {
                        addChild(
                            traumaView!!,
                            name,
                            time
                        )
                    }
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    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 selectNone() {
        bottomView!!.findViewById<RadioGroup>(R.id.mRadio1).check(R.id.mOperation1)
        bottomView!!.findViewById<RadioGroup>(R.id.mRadio2).check(R.id.mTrauma1)
    }

    @SuppressLint("CutPasteId")
    private fun medicBottom() {
        val view = LayoutInflater.from(this).inflate(
            R.layout.layout_medic_bottom,
            null,
            false
        )
        bottomView = view
        operationView = view.findViewById(R.id.mParent1)
        traumaView = view.findViewById(R.id.mParent2)
        //addChild(operationView!!)
        // addChild(traumaView!!)
        val textAddView1 = view.findViewById<TextView>(R.id.mAddView1)
        val 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!!) }


        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
                        }
                    }
                }

            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

                        }
                    }
                }
        } 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
        }
        mAdapter.addFooterView(view)
    }


    /**
     * 添加子view
     */
    private fun addChild(parentView: LinearLayout, name: String = "", time: String = "") {
        val childView = LayoutInflater.from(this).inflate(
            R.layout.item_foot_medic_layout,
            null,
            false
        )
        val 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
            setText(name)
        }
        childView.findViewById<TextView>(R.id.mTvTime).apply {
            isEnabled = isShowFoot
            text = time
        }

        //删除用的
        val 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 {
            val 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) {
        val 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()
        }
    }
}