package com.cheng.blzb.ui.dialog

import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cheng.blzb.R
import com.cheng.blzb.bean.AttachmentEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.databinding.DialogDownloadAttachmentBinding
import com.cheng.blzb.manager.DialogEnum
import com.cheng.blzb.manager.ShareManager
import com.cheng.blzb.utils.DownLoadUtils
import com.example.base.dialog.LoadingDialog
import com.example.base.extensions.longToast
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.utils.DensityUtils
import com.example.base.utils.ScreenUtils
import com.example.base.utils.SpanUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class DownloadAttachmentDialog : DialogFragment() {
    private val mAdapter by lazy { AttachmentAdapter() }
    private val attachmentList = mutableListOf<AttachmentEntity>()

    private val loadingDialog by lazy { LoadingDialog(requireContext()) }

    private var mOnBackListener: ((DialogEnum) -> Unit)? = null     //回调事件

    lateinit var binding: DialogDownloadAttachmentBinding

    override fun onStart() {
        super.onStart()
        val window = dialog?.window
        val windowParams = window?.attributes
        windowParams?.dimAmount = 0.7f
        windowParams?.width = (ScreenUtils.getWindowSize().x * 0.8).toInt()
        dialog?.window?.attributes = windowParams

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val view = layoutInflater.inflate(R.layout.dialog_download_attachment, null)

        binding = DialogDownloadAttachmentBinding.bind(view)

        binding.tvTitle.typeface = Constants.douyinsansB

        val listStr = arguments?.getString("list")

        if (!TextUtils.isEmpty(listStr)) {
            attachmentList.addAll(Gson().fromJson(listStr, object : TypeToken<List<AttachmentEntity>>() {}.type))
        }
        binding.rvAttachment.adapter = mAdapter
        mAdapter.setList(attachmentList)

        mAdapter.setOnItemChildClickListener { _, v, i ->
            when (v.id) {
                R.id.btn_download -> {
                    download(mAdapter.getItem(i))
                }
            }
        }

        binding.ivClose.onClick {
            dismiss()
        }

        val dialog = Dialog(requireContext())
        dialog.setContentView(view)
        return dialog
    }

    private fun download(bean: AttachmentEntity) {
        loadingDialog.show()
        lifecycleScope.launch(Dispatchers.IO) {
            DownLoadUtils.getInstance()
                .setReadTimeOut(10L)
                .setDeleteWhenException(false)
                .initUrl(bean.url, null)
                .addHeader(mapOf(Pair("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0")))
                .setFilePath(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath)
                .setFileName("${bean.title}.${bean.type}")
                .setActionCallBack(
                    actionSuccess = {
                        ShareManager.shareFile(requireActivity(), it)
                        longToast("已下载到文件管理/内部储存/下载/${it.name}")
                        loadingDialog.dismiss()
                    },
                    actionFail = {
                        loadingDialog.dismiss()
                        toast("下载失败")
                    }
                ).down()
        }
    }

    fun setOnSelectListener(listener: ((DialogEnum) -> Unit)) {
        mOnBackListener = listener
    }

    companion object {
        fun newInstance(list: List<AttachmentEntity>): DownloadAttachmentDialog {
            val arg = Bundle()
            arg.putString("list", Gson().toJson(list))
            val fragment = DownloadAttachmentDialog()
            fragment.arguments = arg
            return fragment
        }
    }

    inner class AttachmentAdapter : BaseQuickAdapter<AttachmentEntity, BaseViewHolder>(R.layout.listitem_bid_attachment) {
        init {
            addChildClickViewIds(R.id.btn_download)
        }

        override fun convert(holder: BaseViewHolder, item: AttachmentEntity) {
            SpanUtils.with(holder.getView(R.id.tv_name))
                .appendImage(R.mipmap.ic_pdf_attachment)
                .appendSpace(DensityUtils.dp2px(8f))
                .append(item.title)
                .create()
        }

    }
}