package com.zj365.health.fragment

import android.app.Activity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.blankj.utilcode.util.GsonUtils
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadSampleListener
import com.liulishuo.filedownloader.FileDownloader
import com.liulishuo.filedownloader.util.FileDownloadUtils
import com.xty.base.fragment.BaseVmFrag
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.zj365.health.DownloadFile
import com.zj365.health.adapter.PictureDetailShowAdapter
import com.zj365.health.databinding.FragDownloadPdfBinding
import com.zj365.health.vm.PayCancerVm
import com.xty.network.model.CancerGoodsBean
import java.io.File

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

    var result = mutableListOf<String>()
    override fun initView() {
        super.initView()
        binding.mSubmit.setOnClickListener {
            Toast.makeText(context,"已下载到路径"+filePath,Toast.LENGTH_SHORT).show()
        }
    }
    var order: CancerGoodsBean? = null
    var status: Int? = null
    val uploadManager by lazy{ DownloadFile(context as Activity) }
    private var filePath: String? = null
    override fun initData() {
        super.initData()
        var result =  arguments?.getString("order")
        result?.let {
            order = GsonUtils.fromJson(it,CancerGoodsBean::class.java)
        }
        order?.let {
            val reportUrl =  it.reportUrl
            filePath = FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "pdf1" + File.separator + "report.pdf"
            var file = File(filePath)
            if (file.exists()){
                file.delete()
            }
            showData(!reportUrl.isNullOrEmpty())
            reportUrl?.let {
                downloadId1 = createDownloadTask(1,it)!!.start()

            }

        }

    }

    private fun createDownloadTask(position: Int,url:String): BaseDownloadTask? {
        var isDir = false
        when (position) {
            1 -> {

//                path = filePath!!

            }
            2 -> {
//                url = Constant.LIULISHUO_APK_URL
//                tag = com.liulishuo.filedownloader.demo.SingleTaskTestActivity.ViewHolder(
//                    WeakReference<com.liulishuo.filedownloader.demo.SingleTaskTestActivity>(this),
//                    progressBar2,
//                    null,
//                    speedTv2,
//                    2
//                )
//                path = llsApkDir
//                isDir = true
//                tag.setFilenameTv(filenameTv2)
            }

        }
        return FileDownloader.getImpl().create(url)
            .setPath(filePath!!, false)
            .setCallbackProgressTimes(300)
            .setMinIntervalUpdateSpeed(400)
            .setTag(tag)
            .setListener(object : FileDownloadSampleListener() {
                override fun pending(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    super.pending(task, soFarBytes, totalBytes)
//                    (task.tag as com.liulishuo.filedownloader.demo.SingleTaskTestActivity.ViewHolder).updatePending(
//                        task
//                    )
                }

                override fun progress(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    super.progress(task, soFarBytes, totalBytes)
//                    (task.tag as com.liulishuo.filedownloader.demo.SingleTaskTestActivity.ViewHolder).updateProgress(
//                        soFarBytes, totalBytes,
//                        task.speed
//                    )
                }

                override fun error(task: BaseDownloadTask, e: Throwable) {
                    super.error(task, e)
//                    (task.tag as com.liulishuo.filedownloader.demo.SingleTaskTestActivity.ViewHolder).updateError(
//                        e,
//                        task.speed
//                    )
                }

                override fun connected(
                    task: BaseDownloadTask,
                    etag: String,
                    isContinue: Boolean,
                    soFarBytes: Int,
                    totalBytes: Int
                ) {
                    super.connected(task, etag, isContinue, soFarBytes, totalBytes)
//
                }

                override fun paused(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    super.paused(task, soFarBytes, totalBytes)
//
                }

                override fun completed(task: BaseDownloadTask) {
                    super.completed(task)
//                    (task.tag as com.liulishuo.filedownloader.demo.SingleTaskTestActivity.ViewHolder).updateCompleted(
//                        task
//                    )

                    binding.pdfView.fromFile(File(filePath))
//                        .pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default指定显示页面默认全部展示
                        .enableSwipe(true) // allows to block changing pages using swipe
                        .swipeHorizontal(false)
                        .enableDoubletap(true)
                        .defaultPage(0)
                        // allows to draw something on the current page, usually visible in the middle of the screen
                        .enableAnnotationRendering(false) // render annotations (such as comments, colors or forms)
                        .password(null)
                        .scrollHandle(null)
                        .enableAntialiasing(true) // improve rendering a little bit on low-res screens
                        // spacing between pages in dp. To define spacing color, set view background
                        .spacing(0)
                        .load()
                }

                override fun warn(task: BaseDownloadTask) {
                    super.warn(task)
//                    (task.tag as com.liulishuo.filedownloader.demo.SingleTaskTestActivity.ViewHolder).updateWarn()
                }
            })
    }
    private var downloadId1 = 0
    fun newInstance(data: CancerGoodsBean?): EstimateReportFrag {

        val fragment = EstimateReportFrag()
        var bundle = Bundle()
        data?.let {
            bundle.putString("order",GsonUtils.toJson(it))
        }
        fragment.arguments = bundle
        return fragment
    }
    private fun showData(showData: Boolean) {
        if (showData) {
            binding.pdfView.visibility = View.VISIBLE
            binding.mSubmit.visibility = View.VISIBLE
            binding.viewNone.rlRoot.visibility = View.GONE
        } else {
            binding.mSubmit.visibility = View.GONE
            binding.pdfView.visibility = View.GONE
            binding.viewNone.rlRoot.visibility = View.VISIBLE
        }

    }

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

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

}