package com.zj365.health.act.datamanage

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.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.xty.base.act.BaseVmAct
import com.xty.common.arouter.ARouterUrl
import com.xty.common.picture.PictureUtils
import com.luck.picture.lib.PictureSelector
import com.tamsiree.rxkit.RxKeyboardTool
import com.xty.common.TimeSelect
import com.xty.common.event.HealthDataChangeEvent
import com.xty.common.util.CommonToastUtils
import com.zj365.health.R
import com.zj365.health.adapter.PictureAdapter
import com.zj365.health.databinding.ActUploadMedicalBinding
import com.zj365.health.vm.DataManageVm
import org.greenrobot.eventbus.EventBus
import java.text.SimpleDateFormat
import java.util.Calendar

/**
 * 上传体检--提交页面
 */
@Route(path = ARouterUrl.UPLOAD_Medical)
open class UploadMedicalAct<V : DataManageVm> : BaseVmAct<DataManageVm>() {

    // 6：体检 7：用药，9：住院
    var type: String = "6"

    val mAdapter by lazy { PictureAdapter() }
    val mAdapter1 by lazy { PictureAdapter() }

    val binding by lazy { ActUploadMedicalBinding.inflate(layoutInflater) }
    var delete = arrayListOf<String>()
    var delete1 = arrayListOf<String>()
    var isCheck = false
    var isMedical = false

    var selectTime = ""
    var firstSelectedDate: Calendar? = null  // 添加一个伴生对象的属性用于保存第一个选择的时间
    var format = "yyyy-MM-dd"  //需要在外部输出的时间格式
    var selectedDate = Calendar.getInstance()
    var startDate = Calendar.getInstance()
    var mEndDate = Calendar.getInstance()

    val timSelect by lazy {
        TimeSelect(this) {

        }
    }

    var userId:String?=null

    private val timeMedicalStart by lazy {
        TimeSelect(this) {
        }.apply {
            if (type == "7"){
                setStartTime = true
                val date = Calendar.getInstance()
                //当前年的前一年到当前年的后一年
                startDate.set(date.get(Calendar.YEAR)-1,0,1)
                endDate.set(date.get(Calendar.YEAR)+1,11,31)
            }

        }
    }

    private val timeMedicalEnd by lazy {
        TimeSelect(this) {}.apply {
            if (type == "7"){
                setStartTime = true
                startDate.set(1970,1,31)
                endDate.set(3050,11,31)
            }
        }
    }

    override fun setLayout() = binding.root
    override fun initData() {
        super.initData()
        userId = intent.getStringExtra("userId")
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)

        type = intent.getStringExtra("type").toString()
        binding.title.mTvTitle.text =
        if (type == "6") "上传体检记录" else if (type == "7") "上传用药记录" else "上传住院记录"
        if (type == "7") {  //用药
            binding.llTijianUpload.visibility = View.GONE
            binding.llMedicalLayout.visibility = View.VISIBLE
        }else if(type == "9"){  //住院
            binding.llTijianUploadHead.visibility = View.GONE
            binding.llHospitalLayout.root.visibility = View.VISIBLE
            binding.picUpload.text = "上传报告"
            binding.tvRed.visibility = View.VISIBLE
        }

        binding.title.mIvBack.setOnClickListener { finish() }
//        binding.ivUpload.setOnClickListener {
//            PictureUtils.openCamera(this, PictureMimeType.ofImage(),5)
//        }

        binding.tvTime.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            timSelect.selectTime(it, "yyyy-MM-dd")
        }

        binding.tvMedicalStartTime.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            timeMedicalStart.selectTime(it)

        }

        binding.tvMedicalEndTime.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            timeMedicalEnd.selectTime(it)
        }

        binding.llHospitalLayout.tvStartTime.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            timeMedicalStart.selectTime(it)
        }
        binding.llHospitalLayout.tvEndTime.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            timeMedicalEnd.selectTime(it)
        }
        binding.rvRecyclerview1.layoutManager = GridLayoutManager(this, 4)
        binding.rvRecyclerview1.adapter = mAdapter
        mAdapter.addChildClickViewIds(R.id.ivImage, R.id.ivDelete)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.ivImage -> {
                    isCheck = true
                    val item = adapter.getItem(position) as String
                    if (TextUtils.isEmpty(item)) {
                        val value = 50 - (mAdapter.data.size - 1)
                        PictureUtils.openCamera(this, PictureMimeType.ofImage(), value)
                    } else {

                    }
                }

                R.id.ivDelete -> {
                    var 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.rvRecyclerview2.layoutManager = GridLayoutManager(this, 4)
        binding.rvRecyclerview2.adapter = mAdapter1
        mAdapter1.addChildClickViewIds(R.id.ivImage, R.id.ivDelete)
        mAdapter1.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.ivImage -> {
                    isMedical = true
                    val item = adapter.getItem(position) as String
                    if (TextUtils.isEmpty(item)) {
                        val value = 50 - (mAdapter1.data.size - 1)
                        PictureUtils.openCamera(this, PictureMimeType.ofImage(), value)
                    } else {

                    }
                }

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

        binding.mSubmit.setOnClickListener {
            result.clear()
            result1.clear()
            var newResult1 = mutableListOf<String>()
            var newResult2 = mutableListOf<String>()

            val title = binding.etName.text.toString()
            val time = binding.tvTime.text.toString() + " 00:00:00"

            val medicalName: String
            val startTime: String
            val endTime: String

            val hospitalName:String
            val hospitalInstruction:String

            if (type == "6") { //体检
                if (title.isEmpty()) {
                    CommonToastUtils.showToast("请输入体检说明")
                    return@setOnClickListener
                }

                if (time.isEmpty() || time == " 00:00:00") {
                    CommonToastUtils.showToast("请选择体检时间")
                    return@setOnClickListener
                }
            } else if(type == "7"){  //用药
                medicalName = binding.etMedicalName.text.toString()
                startTime = binding.tvMedicalStartTime.text.toString()
                endTime = binding.tvMedicalEndTime.text.toString()

                if (medicalName.isEmpty()) {
                    CommonToastUtils.showToast("请输入药品名称")
                    return@setOnClickListener
                }

                if (startTime.isEmpty() || startTime == " 00:00:00") {
                    CommonToastUtils.showToast("请选择开始时间")
                    return@setOnClickListener
                }

                if (endTime.isEmpty() || endTime == " 00:00:00") {
                    CommonToastUtils.showToast("请选择结束时间")
                    return@setOnClickListener
                }

                val format = SimpleDateFormat("yyyy-MM-dd")
                val startDate = format.parse(startTime)
                val endDate = format.parse(endTime)
                if (startDate != null && endDate != null) {
                    if (endDate.time < startDate.time) {
                        CommonToastUtils.showToast("结束时间不能早于开始时间")
                        return@setOnClickListener
                    }
                }
            }else if(type == "9"){ //住院
                startTime = binding.llHospitalLayout.tvStartTime.text.toString()
                endTime = binding.llHospitalLayout.tvEndTime.text.toString()

                hospitalName = binding.llHospitalLayout.etHospitalName.text.toString()
                hospitalInstruction = binding.llHospitalLayout.etHospitalInstruction.text.toString()

                if (TextUtils.isEmpty(hospitalName)){
                    CommonToastUtils.showToast("请输入住院医院")
                    return@setOnClickListener
                }

                if (TextUtils.isEmpty(hospitalInstruction)){
                    CommonToastUtils.showToast("请输入住院说明")
                    return@setOnClickListener
                }

                if (startTime.isEmpty() || startTime == " 00:00:00") {
                    CommonToastUtils.showToast("请选择开始时间")
                    return@setOnClickListener
                }

                if (endTime.isEmpty() || endTime == " 00:00:00") {
                    CommonToastUtils.showToast("请选择结束时间")
                    return@setOnClickListener
                }

                val format = SimpleDateFormat("yyyy-MM-dd")
                val startDate = format.parse(startTime)
                val endDate = format.parse(endTime)
                if (startDate != null && endDate != null) {
                    if (endDate.time < startDate.time) {
                        CommonToastUtils.showToast("结束时间不能早于开始时间")
                        return@setOnClickListener
                    }
                }
            }

            for (datum in mAdapter.data) {
                if (TextUtils.isEmpty(datum)) {
                    continue
                }
                if (datum.contains("http")) {
                    newResult1.add(datum)
                    continue
                }
                result.add(datum)
            }

            for (datum in mAdapter1.data) {
                if (TextUtils.isEmpty(datum)) {
                    continue
                }
                if (datum.contains("http")) {
                    newResult2.add(datum)
                    continue
                }
                result1.add(datum)
            }
            if ((result1.size == 0 && result.size == 0) && (newResult1.size == 0 && newResult2.size == 0)) {
                CommonToastUtils.showToast("请上传图片")
                return@setOnClickListener
            }

            var finalData = mutableListOf<String>()
            finalData.addAll(result)
            finalData.addAll(result1)
            var deleteFileData = mutableListOf<String>()
            deleteFileData.addAll(delete)
            deleteFileData.addAll(delete1)
            if (deleteFileData.size > 0) {
                deleteData(deleteFileData)
            }
            if (finalData.isEmpty()) {
                when (type) {
                    "6" -> {
                        uploadData(
                            mutableListOf<String>(),
                            mutableListOf<String>(),
                            title,
                            "$time 00:00:00"
                        )
                    }
                    "7" -> {
                        uploadData(mutableListOf<String>(), mutableListOf<String>())
                    }
                    "9" -> {
                        uploadHospitalDate(mutableListOf<String>(), mutableListOf<String>())
                    }
                }
            } else {
                mViewModel.uploadImagesFiles(finalData)
            }
        }
    }

   open fun uploadHospitalDate(list: MutableList<String>, list1: MutableList<String>){
       mViewModel.submitHospital(
           list,
           list1,
           binding.mZyDesc.text.toString(),
           binding.llHospitalLayout.etHospitalInstruction.text.toString(),
           binding.llHospitalLayout.tvStartTime.text.toString(),
           binding.llHospitalLayout.tvEndTime.text.toString(),
           binding.llHospitalLayout.etHospitalName.text.toString(),
           type,
           userId
       )
   }
    open fun uploadData(list: MutableList<String>, list1: MutableList<String>) {
        mViewModel.submitUseMedical(
            list, list1, binding.mZyDesc.text.toString(),
            binding.etMedicalName.text.toString(),
            binding.tvMedicalStartTime.text.toString(),
            binding.tvMedicalEndTime.text.toString(),
            type,
            userId
        )
    }

    open fun uploadData(
        list: MutableList<String>,
        list1: MutableList<String>,
        name: String,
        time: String
    ) {
        mViewModel.submitMedical(
            list,
            list1,
            type,
            name,
            time,
            binding.etOrg.text.toString(),
            binding.mZyDesc.text.toString(),
            userId
        )
    }

    open fun deleteData(list: MutableList<String>) {
    }

    var result = mutableListOf<String>()
    var result1 = mutableListOf<String>()
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode === RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {

                    var result = PictureSelector.obtainMultipleResult(data)
                    if (result.size > 0) {
                        if (result.isNotEmpty()) {
                            for (item in result) {
                                var path = item.compressPath.ifEmpty {
                                    item.androidQToPath
                                }
                                if (isCheck) {
                                    mAdapter.addData(0, path)
                                    mAdapter.notifyDataSetChanged()
                                } else if (isMedical) {
                                    mAdapter1.addData(0, path)
                                    mAdapter1.notifyDataSetChanged()
                                }
                            }
                        }
                    }
                    isCheck = false
                    isMedical = false
                }

            }
        }
    }

    override fun liveObserver() {
        mViewModel.imageLive1.observe(this) {
            val data = it.data
            var submitData1 = mutableListOf<String>()
            var submitData2 = mutableListOf<String>()
            if (result.isNotEmpty()) {
                data?.forEach {
                    val indexOf = data.indexOf(it)
                    if (indexOf < result.size) {
                        submitData1.add(it)
                    } else {
                        submitData2.add(it)
                    }
                }

            } else {
                if (result1.isNotEmpty()) {
                    data?.forEach {
                        submitData2.add(it)
                    }
                }
            }

            if (type == "6") {
                val title = binding.etName.text.toString()
                val time = binding.tvTime.text.toString() + " 00:00:00"
                uploadData(submitData1, submitData2, title, time)
            } else if(type == "7"){
                uploadData(submitData1, submitData2)
            }else{
                uploadHospitalDate(submitData1, submitData2)
            }
        }

        mViewModel.addDataOb.observe(this) {
            EventBus.getDefault().post(HealthDataChangeEvent())
            finish()
        }
        mViewModel.editMedicalOb.observe(this) {
            EventBus.getDefault().post(HealthDataChangeEvent())
            finish()
        }
    }
}