package com.zj365.health.act.healthrecord

import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.tamsiree.rxkit.RxKeyboardTool
import com.xty.base.act.BaseListAct
import com.xty.base.act.BaseVmAct
import com.xty.base.vm.BaseVm
import com.xty.common.TimeSelect
import com.xty.common.arouter.ARouterUrl
import com.xty.common.picture.PictureUtils
import com.xty.common.util.CommonToastUtils
import com.xty.network.model.EatTypeBean
import com.zj365.health.R
import com.zj365.health.adapter.UploadPicAdapter
import com.zj365.health.databinding.ActUploadHealthRecordBinding
import com.zj365.health.vm.UploadHealthRecordVm
import com.zj365.health.weight.EatTypeDialog
import java.lang.StringBuilder

@Route(path = ARouterUrl.FAMILY_REPORT_UPLOAD_ACT)
class UploadHealthRecordAct : BaseVmAct<UploadHealthRecordVm>() {

    val binding by lazy { ActUploadHealthRecordBinding.inflate(layoutInflater) }

    private val mAdapter by lazy { UploadPicAdapter() }

    private var isCheck = false
    private var delete = arrayListOf<String>()

    var reportType : String = ""

    var reportTime:String = ""
    var reportTitle:String = ""

    var reportExplain:String =""

    private var result = mutableListOf<String>()

    private val uploadTypeData = arrayOf(
        EatTypeBean("体检报告", "1"),
        EatTypeBean("病历报告", "2"),
        EatTypeBean("CT或其他影像", "3")
    )

    private val timSelect by lazy {
        TimeSelect(this) {

        }.apply {
            chooseMany = false
            showYear = true
            showMonth = true
            showDay = true
            showHour = true
            showMin = true
            showSec = false
        }
    }

    override fun liveObserver() {
        mViewModel.imageLive1.observe(this){
            var strBuilder = StringBuilder()
            it.data.forEachIndexed { index, s ->
                strBuilder.append(it.data[index])
                if (index < it.data.size -1 ){
                    strBuilder.append(",")
                }

            }
            mViewModel.submitReport(reportTitle,reportType,reportTime,strBuilder.toString(),reportExplain)
        }
        mViewModel.submitLiveData.observe(this){
            finish()
        }
    }


    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text = "上传报告"
        binding.title.mIvBack.setOnClickListener {
            finish()
        }

        binding.tvUploadTime.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            timSelect.selectTime(it, "yyyy-MM-dd HH:mm:ss")
        }

        binding.tvUploadType.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            uploadTypeSelect.setWheelViewData(uploadTypeData.toMutableList())
            uploadTypeSelect.show()
        }

        binding.recycler.layoutManager = GridLayoutManager(this, 4)
        binding.recycler.adapter = mAdapter
        mAdapter.addChildClickViewIds(R.id.ivImage, R.id.ivDelete)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.ivImage -> {
                    if (adapter.data.size -1 < 5) {
                        isCheck = true
                        val item = adapter.getItem(position) as String
                        if (TextUtils.isEmpty(item)) {
                            val value = 5 - (mAdapter.data.size - 1)
                            PictureUtils.openCamera(this, PictureMimeType.ofImage(), value)
                        }
                    } else {
                        CommonToastUtils.showToast("最多上传5张图片")
                    }
                }

                R.id.ivDelete -> {
                    val path = adapter.data[position] as String
                    if (path.contains("http")) {
                        delete.add(adapter.data[position] as String)
                    }
                    adapter.removeAt(position)
                    adapter.notifyDataSetChanged()
                }
            }
        }
        mAdapter.addData("")

        binding.tvSave.setOnClickListener {
            reportTime= binding.tvUploadTime.text.toString()
            reportTitle = binding.etReportTitle.text.toString()

            if (TextUtils.isEmpty(reportTitle)) {
                CommonToastUtils.showToast("请填写报告标题")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(reportType)) {
                CommonToastUtils.showToast("请选择报告类型")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(reportTime)) {
                CommonToastUtils.showToast("请选择报告时间")
                return@setOnClickListener
            }
            result.clear()
            for (datum in mAdapter.data) {
                if (TextUtils.isEmpty(datum)) {
                    continue
                }
                if (!datum.contains("http")) {
                    result.add(datum)
                }
            }
            if (result.size <= 0) {
                CommonToastUtils.showToast("请上传报告图片")
                return@setOnClickListener
            }
            reportExplain  = binding.etReportExplain.text.toString()
            if (result.size > 0) {
                mViewModel.uploadImagesFiles(result)
            }
        }

    }

    private val uploadTypeSelect by lazy {
        EatTypeDialog(this,"选择报告类型") { selectValue, selectKey ->
            binding.tvUploadType.text = selectKey
            reportType  = selectValue
        }
    }

    override fun setLayout() = binding.root

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode === RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    val result = PictureSelector.obtainMultipleResult(data)
                    if (result.size > 0) {
                        if (result.isNotEmpty()) {
                            for (item in result) {
                                val path = item.compressPath.ifEmpty {
                                    item.androidQToPath
                                }
                                if (isCheck) {
                                    mAdapter.addData(0, path)
                                    mAdapter.notifyDataSetChanged()
                                }
                            }
                        }

                        binding.tvNumDesc.text = "重要内容拍照存储（${mAdapter.data.size -1}/5）"
                    }
                    isCheck = false
                }
            }
        }
    }
}