package com.zj365.health.act.datamanage

import android.annotation.SuppressLint
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.blankj.utilcode.util.GsonUtils
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.BaseVmAct
import com.xty.common.TimeSelect
import com.xty.common.arouter.ARouterUrl
import com.xty.common.event.HealthDataChangeEvent
import com.xty.common.picture.PictureUtils
import com.xty.common.util.CommonToastUtils
import com.zj365.health.R
import com.zj365.health.adapter.PictureAdapter
import com.zj365.health.databinding.ActYshiUploadingBinding
import com.zj365.health.vm.DataManageVm
import com.zj365.health.weight.EatTypeDialog
import com.xty.network.model.EatTypeBean
import com.xty.network.model.MedicalDataBean
import com.xty.network.model.RevampImgBean
import org.greenrobot.eventbus.EventBus
import java.text.SimpleDateFormat
import java.util.Date

/**
 * 饮食上传页面
 */
@Route(path = ARouterUrl.DATAMANAGE_YSHI_UPLOADING_ACT)
class YShiUploadingAct : BaseVmAct<DataManageVm>() {

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

    private val mAdapter by lazy { PictureAdapter() }

    private var delete = arrayListOf<String>()
    private var result = mutableListOf<String>()
    private val revampImgList = mutableListOf<RevampImgBean>()//修改数据图片集合
    private var isCheck = false
    private var eatType = ""
    private var resultData: MedicalDataBean? = null
    private var isRevamp = false
    private var userId = ""

    //tab列表
    private val eatTypeData = arrayOf(
        EatTypeBean("早餐", "1"),
        EatTypeBean("午餐", "2"),
        EatTypeBean("晚餐", "3"),
        EatTypeBean("早餐加餐", "4"),
        EatTypeBean("午餐加餐", "5"),
        EatTypeBean("晚餐加餐", "6")
    )

    private val timSelect by lazy {
        TimeSelect(this) {

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

    private val eatTypeSelect by lazy {
        EatTypeDialog(this) { selectValue, selectKey ->
            binding.tvEatType.text = selectKey
            eatType = selectValue
        }
    }

    override fun initData() {
        super.initData()
        val result = intent.getStringExtra("data")
        userId = intent.getStringExtra("userId").toString()
        result?.let {
            resultData = GsonUtils.fromJson(it, MedicalDataBean::class.java)
            if (resultData != null) {
                isRevamp = true
                eatType = resultData?.mealType!!
                binding.tvEatType.text = getEatType(eatType.toInt())
                binding.tvEatTime.text = resultData?.time
                binding.etEatExplain.setText(resultData?.mealExplain)
                val mealList = resultData?.mealList
                if (mealList!!.isNotEmpty()) {
                    revampImgList.clear()
                    val imgList = mutableListOf<String>()
                    mealList.forEach { img ->
                        imgList.add(img.imageUrl!!)
                        revampImgList.add(RevampImgBean(img.id!!, img.imageUrl!!))
                    }
                    mAdapter.setNewInstance(imgList)
                }
            } else {
                isRevamp = false
            }
        }
    }

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

        //点击选择时间
        binding.tvEatTime.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            timSelect.selectTime(it, "yyyy-MM-dd HH:mm")
        }
        //点击选择用餐类型
        binding.tvEatType.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            eatTypeSelect.setWheelViewData(eatTypeData.toMutableList())
            eatTypeSelect.show()
        }

        binding.rvRecyclerview.layoutManager = GridLayoutManager(this, 4)
        binding.rvRecyclerview.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 < 10) {
                        isCheck = true
                        val item = adapter.getItem(position) as String
                        if (TextUtils.isEmpty(item)) {
                            val value = 9 - (mAdapter.data.size - 1)
                            PictureUtils.openCamera(this, PictureMimeType.ofImage(), value)
                        }
                    } else {
                        CommonToastUtils.showToast("最多上传9张图片")
                    }
                }

                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.mSubmit.setOnClickListener {
            val eatTimeStr = binding.tvEatTime.text.toString()
            if (TextUtils.isEmpty(eatType)) {
                CommonToastUtils.showToast("请选择用餐类型")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(eatTimeStr)) {
                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 && revampImgList.size <= 0) {
                CommonToastUtils.showToast("请上传用餐图片")
                return@setOnClickListener
            }
            val mealExplain = binding.etEatExplain.text.toString()
            if (result.isEmpty() && revampImgList.size <= 0 && !isRevamp) {
                uploadData(mutableListOf(), eatType, eatTimeStr, mealExplain)
            } else {
                if (result.size > 0) {
                    mViewModel.uploadImagesFiles(result)
                } else {
                    if (delete.size > 0) {
                        if (revampImgList.size > 0) {
                            val imgIdList = mutableListOf<String>()
                            delete.forEach {
                                revampImgList.forEach { imgData ->
                                    if (it == imgData.imageUrl) {
                                        imgIdList.add(imgData.id.toString())
                                    }
                                }
                            }
                            mViewModel.deleteMedicalFile(imgIdList)
                        }
                    } else {
                        mViewModel.edittYShiData(
                            userId,
                            resultData?.id,
                            revampImgList,
                            resultData?.createTime!!,
                            eatType.toInt(),
                            eatTimeStr,
                            mealExplain,
                            "8"
                        )
                    }
                }
            }
        }
    }

    @SuppressLint("SimpleDateFormat")
    private fun uploadData(
        list: MutableList<RevampImgBean>,
        mEatType: String,
        eatTimeStr: String,
        mealExplain: String
    ) {
        mViewModel.submitYShiData(
            userId,
            list,
            SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(System.currentTimeMillis())),
            mEatType.toInt(),
            eatTimeStr,
            mealExplain,
            "8"
        )
    }

    override fun liveObserver() {
        //图片上传成功执行方法
        mViewModel.imageLive1.observe(this) {
            if (it.code == 0) {
                val data = it.data

                val eatTimeStr = binding.tvEatTime.text.toString()
                val mealExplain = binding.etEatExplain.text.toString()

                if (data.size > 0) {
                    data.forEach { imgUrl ->
                        revampImgList.add(RevampImgBean(-1, imgUrl))
                    }
                }
                if (!isRevamp) {
                    uploadData(revampImgList, eatType, eatTimeStr, mealExplain)
                } else {
                    mViewModel.edittYShiData(
                        userId,
                        resultData?.id,
                        revampImgList,
                        resultData?.createTime!!,
                        eatType.toInt(),
                        eatTimeStr,
                        mealExplain,
                        "8"
                    )
                }
            } else {
                CommonToastUtils.showToast("图片上传失败")
            }
        }

        //数据上传返回方法
        mViewModel.addDataOb.observe(this) {
            if (it.code == 0) {
                EventBus.getDefault().post(HealthDataChangeEvent())
                finish()
            } else {
                CommonToastUtils.showToast("上传失败：${it.msg}")
            }
        }

        //修改数据返回方法
        mViewModel.editMedicalOb.observe(this) {
            if (it.code == 0) {
                EventBus.getDefault().post(HealthDataChangeEvent())
                finish()
            } else {
                CommonToastUtils.showToast("修改失败：${it.msg}")
            }
        }

        //删除图片返回方法
        mViewModel.deleteOb.observe(this) {
            if (it.code == 0) {
                mViewModel.edittYShiData(
                    userId,
                    resultData?.id,
                    revampImgList,
                    resultData?.createTime!!,
                    eatType.toInt(),
                    binding.tvEatTime.text.toString(),
                    binding.etEatExplain.text.toString(),
                    "8"
                )
            } else {
                CommonToastUtils.showToast("删除图片失败")
            }
        }
    }

    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()
                                }
                            }
                        }
                    }
                    isCheck = false
                }
            }
        }
    }

    private fun getEatType(mealType: Int): String {
        val mealTypeStr = when (mealType) {
            1 -> {
                "早餐"
            }

            2 -> {
                "午餐"
            }

            3 -> {
                "晚餐"
            }

            4 -> {
                "早餐加餐"
            }

            5 -> {
                "中餐加餐"
            }

            6 -> {
                "晚餐加餐"
            }

            else -> {
                "其它"
            }
        }
        return mealTypeStr
    }
}