package com.zj365.mime.act

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.ImageView
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.luck.picture.lib.entity.LocalMedia
import com.xty.base.act.BaseVmAct
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.picture.PictureUtils
import com.xty.common.picture.VideoCompressUtils
import com.xty.common.recycleUtils.RecycleItem
import com.xty.common.util.CommonToastUtils
import com.xty.common.weight.LoadingView
import com.zj365.mime.R
import com.zj365.mime.adapter.PictureFeedAdapter
import com.zj365.mime.databinding.ActFeedBackBinding
import com.zj365.mime.vm.FeedBackVm
import java.io.File

/**
 * 意见建议
 */
@Route(path = ARouterUrl.FEED_BACK)
class FeedBackAct : BaseVmAct<FeedBackVm>() {
    val compressLoad by lazy {   LoadingView.Builder(this).setCancelable(false).setCancelOutside(false).setMessage("视频压缩中，此过程不耗费流量...").cteated() }
    val binding by lazy{ActFeedBackBinding.inflate(layoutInflater)}
    val mAdapter by lazy{ PictureFeedAdapter() }
    var name=""
    var userId=""
    val compressUtils by lazy{ VideoCompressUtils({
        compressLoad.dismiss()
        val content = binding.mEdit.text.toString().trim()
        mViewModel.uploadFeedBack(it,mAdapter.data,content,userId,name)
    },{
        compressLoad.dismiss()
        CommonToastUtils.showToast("视频压缩失败")
    }) }
    var isVideo=false
    override fun setLayout()=binding.root
    val textWatch by lazy{
        object:TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val length = s.toString().trim().length
                binding.mSize.text="$length/100"
            }

        }
    }


    override fun initData() {
        super.initData()
        isDarkBar=true
        name=intent.extras!!.getString("name").toString()
        userId=intent.extras!!.getString("id").toString()
    }

    override fun initView() {
        super.initView()
        //RouteManager.goAct( ARouterUrl.FEED_LIST)   往期意见反馈
        statusBar(binding.title.mView)
        binding.title.mIvBack.setOnClickListener {
            finish()
        }
        binding.title.mTvTitle.text=getString(R.string.feed_back)
        binding.title.mTvRight.apply {
            text=getString(R.string.feed_back_history)
            visibility=View.VISIBLE
            setOnClickListener {
                RouteManager.goAct(ARouterUrl.FEED_LIST)
            }

        }
        binding.mEdit.addTextChangedListener(textWatch)

        binding.mVideo.setOnClickListener {
            isVideo=true
            PictureUtils.openCamera(this, PictureMimeType.ofVideo(),1)
        }
        binding.mTvConfirm.setOnClickListener {
             var destPath=externalCacheDir!!.absolutePath+ File.separator+"${System.currentTimeMillis()}.mp4"

            var videoPath=if( binding.mVideo.tag==null) "" else    binding.mVideo.tag.toString()
            if(videoPath.isEmpty()){
                val content = binding.mEdit.text.toString().trim()
                mViewModel.uploadFeedBack(videoPath,mAdapter.data,content,userId,name)
            }else{
                compressLoad.show()
                compressUtils.compress(videoPath,destPath)
            }
        }
        binding.mVideoClose.setOnClickListener {
            it.visibility=View.GONE
            binding.mVideo.tag==null
            binding.mVideo.setImageResource(R.mipmap.ic_picture_add)
            binding.mVideo.scaleType=ImageView.ScaleType.CENTER
        }
        initAdapter()
    }
    private fun initAdapter() {
        var item=RecycleItem(this,40,1)
        item.setSpace(40,40)
        binding.mRecycle.addItemDecoration(item)
        binding.mRecycle.layoutManager=GridLayoutManager(this,3)
        binding.mRecycle.adapter=mAdapter
        mAdapter.addChildClickViewIds(R.id.imageDefault,R.id.mImage,R.id.mClose)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.imageDefault->{
                    isVideo=false
                    PictureUtils.openCameraShow(this, PictureMimeType.ofImage(),9,mAdapter.data.subList(0,mAdapter.data.size-1))
                }
                R.id.mImage->{
                    if(mAdapter.data[mAdapter.data.size-1].size==0L){
                        var list= mutableListOf<LocalMedia>().apply { addAll(mAdapter.data) }
                        list.removeAt(list.size-1)
                        PictureUtils.previewImage(this,position,list)
                    }else{
                        PictureUtils.previewImage(this,position,mAdapter.data)
                    }
                }
                R.id.mClose->{
                    remove(position)
                }
            }
        }
        mAdapter.addData(LocalMedia())
    }

    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(isVideo){
                        binding.mVideoClose.visibility=View.VISIBLE
                        PictureUtils.getVideoThumb(result[0].realPath, binding.mVideo)
                    }else{
                        if(result.size>0){
                            changeList(result)
                        }
                    }
                }
            }
        }
    }




    private fun changeList(newList:MutableList<LocalMedia>) {
        if(newList.size<9){
            newList.add(LocalMedia())
        }
        mAdapter.setNewInstance(newList)
    }

    override fun liveObserver() {
        mViewModel.uploadLive.observe(this){
            CommonToastUtils.showToast(R.string.submit_success)
            finish()
        }
    }

    /**
     * 选择之后 图片列表的样式
     */
    private fun remove(position:Int) {
        val reversed = (0 until mAdapter.data.size).reversed()
        for (i in reversed){
            if(i==position){
                mAdapter.data.removeAt(i)
            }
        }
        if(mAdapter.data[mAdapter.data.size-1].size!=0L){
            mAdapter.data.add(LocalMedia())
        }
        mAdapter.notifyDataSetChanged()
    }
}