package com.zj365.health.fragment

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
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.xty.base.fragment.BaseVmFrag
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.picture.PictureUtils
import com.xty.common.util.CommonToastUtils
import com.zj365.health.R
import com.zj365.health.adapter.PictureDetailShowAdapter
import com.zj365.health.databinding.FragUploadCheckBinding
import com.zj365.health.vm.PayCancerVm
import com.xty.network.model.CancerGoodsBean
import com.xty.network.model.CancerImageBean

/**
 * 全国排行榜
 */
class UploadCheckFrag : BaseVmFrag<PayCancerVm>() {
    //val binding by lazy{FragWholeRankBinding.inflate(layoutInflater)}
    val binding by lazy { FragUploadCheckBinding.inflate(layoutInflater) }
    val adapter by lazy { PictureDetailShowAdapter() }
    override fun setLayout() = binding.root

    /**
     * 暂存用户删除图片未点提交时的条目，点提交时统一删除
     */
    var deleteImages = mutableSetOf<Long>()
    var result = mutableListOf<String>()
    override fun initView() {
        super.initView()
        initRecycle()
        binding.getBlood.setOnClickListener {
            bundle.clear()
            bundle.putBoolean("isList",false)
            RouteManager.goAct(ARouterUrl.COLLECT_BLOOD,  bundle)
        }
        binding.mSubmit.setOnClickListener {
            result.clear()
            deleteImages.forEach {
                it.let {
                    mViewModel.deleteImage(it)
                }
            }
            for (datum in adapter.data) {
                val imageUrl = datum.imageUrl
                if (TextUtils.isEmpty(imageUrl)) {
                    continue
                }
                result.add(imageUrl!!)
            }

            if (result.isEmpty()){
                CommonToastUtils.showToast("请上传检验单")
                return@setOnClickListener
            }
            var imageResult = mutableListOf<String>()
            for (s in result) {
                if (s.contains("http")){
                    continue
                }
                imageResult.add(s)
            }

            if (imageResult.isEmpty()){
                order?.orderNo?.let {
                    mViewModel.uploadImages(it, mutableListOf())
                    return@setOnClickListener
                }
            }
            mViewModel.uploadImagesFile(result)

        }
        mViewModel.isCanReservation()
    }

    var order: CancerGoodsBean? = null
    var status: Int? = null
    override fun initData() {
        super.initData()
        var result = arguments?.getString("order")
        result?.let {
            order = GsonUtils.fromJson(it, CancerGoodsBean::class.java)
        }
        order?.let {
            var showData = mutableListOf<CancerImageBean>()
            it.images?.let {
                showData.addAll(it)
                showData.add(CancerImageBean("", "", "", "", "", 0, 0L, ""))
                adapter.setNewInstance(showData)
            }
            status = it.status
            adapter.status1 = status
            var remark = ""
            it.images?.forEach {
                if (!it.remark.isNullOrEmpty()) {
                    remark = it.remark!!
                    return@forEach
                }
            }
            binding.tvRemark.setText(remark)

        }
        if (status == 5) {
            //已完成状态
            binding.llApprovalResult.visibility = View.VISIBLE
            binding.getBlood.visibility = View.GONE
            binding.llDelete.visibility = View.VISIBLE
            binding.mSubmit.visibility = View.GONE
            order?.images?.let {
                if (it.isEmpty()) {
                    //已删除状态
                    showData(false)
                }
            }
        }  else if (status == 3){
            binding.llApprovalResult.visibility = View.VISIBLE
            binding.getBlood.visibility = View.GONE
            binding.llDelete.visibility = View.GONE
            binding.mSubmit.visibility = View.GONE
        }else {
            //未完成状态
            binding.llApprovalResult.visibility = View.VISIBLE
            binding.getBlood.visibility = View.VISIBLE
            binding.llDelete.visibility = View.GONE
            binding.mSubmit.visibility = View.VISIBLE
        }
        binding.llDelete.setOnClickListener {
            order?.orderNo?.let {
                mViewModel.deleteImages(it)
            }
        }
    }

    fun newInstance(data: CancerGoodsBean?): UploadCheckFrag {

        val fragment = UploadCheckFrag()
        var bundle = Bundle()
        data?.let {
            bundle.putString("order", GsonUtils.toJson(it))
        }
        fragment.arguments = bundle
        return fragment
    }

    fun initRecycle() {
        binding.rvRecyclerview.layoutManager = GridLayoutManager(requireContext(), 4)
        binding.rvRecyclerview.adapter = adapter
        adapter.addChildClickViewIds(R.id.ivImage, R.id.ivDelete)
        adapter.setOnItemChildClickListener { adapter, view, position ->
            val item = adapter.getItem(position) as CancerImageBean
            when (view.id) {
                R.id.ivImage -> {

                    if (TextUtils.isEmpty(item.imageUrl)) {
                        val value = 5 - (adapter.data.size - 1)
                        PictureUtils.openCamera(requireActivity(), PictureMimeType.ofImage(), value)
                    } else {

                    }
                }
                R.id.ivDelete -> {
                    adapter.removeAt(position)
                    adapter.notifyItemRemoved(position)
                    deleteImages.add(item.id?:0L)
                }
            }
        }
    }

    override fun setViewModel() = PayCancerVm()
    override fun observer() {
        mViewModel.uploadImage.observe(this) {
            //跳转评估记录
            bundle.clear()
            RouteManager.goAct(ARouterUrl.ESTIMATE_RECORD, bundle)
            activity?.finish()
        }

        mViewModel.imageLive.observe(this) {
            it.data?.let { list ->
                order?.orderNo?.let {
                    mViewModel.uploadImages(it, list)
                }
            }
        }
        mViewModel.deleteOb.observe(this) {
            showData(false)
        }

        mViewModel.isCanReservationOb.observe(this) {
            it.data?.let {
                if (it.equals("1")) {
                    //可预约
                    binding.getBlood.visibility = View.VISIBLE
                } else{
                    //不可预约
                    binding.getBlood.visibility = View.GONE
                }
            }
        }
    }

    private fun showData(showData: Boolean) {
        if (showData) {
            binding.tvApprocalRecord.visibility = View.VISIBLE
            binding.llApprovalResult.visibility = View.VISIBLE
            binding.tvUploadorder.visibility = View.VISIBLE
            binding.getBlood.visibility = View.VISIBLE
            binding.tvApprocalRecord.visibility = View.VISIBLE
            binding.viewNone.rlRoot.visibility = View.GONE
        } else {
            binding.tvApprocalRecord.visibility = View.GONE
            binding.llApprovalResult.visibility = View.GONE
            binding.tvUploadorder.visibility = View.GONE
            binding.getBlood.visibility = View.GONE
            binding.tvApprocalRecord.visibility = View.GONE
            binding.llDelete.visibility = View.GONE
            binding.viewNone.rlRoot.visibility = View.VISIBLE


        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode === AppCompatActivity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    var result = PictureSelector.obtainMultipleResult(data)
                    if (result.size > 0) {
                        if (result.isNotEmpty()) {
//                            fileUrl = result[0].compressPath
                            for (item in result) {
                                var path = item.compressPath.ifEmpty {
                                    item.androidQToPath
                                }
                                adapter.addData(0, CancerImageBean(path, "", "", "", "", 0, 0L, ""))
                            }
                        }
                    }
                }
            }
        }
    }
}