package com.jld.vod.view

import android.app.ProgressDialog
import android.content.Context
import android.os.Handler
import android.os.Message
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.observe
import com.jld.vod.R
import com.jld.vod.base.BaseActivity
import com.jld.vod.config.Config
import com.jld.vod.model.bean.BaseBean
import com.jld.vod.model.bean.GameResByNotUploaded
import com.jld.vod.model.bean.MovieResByNotUploaded
import com.jld.vod.model.bean.MusicResByNotUploaded
import com.jld.vod.model.event.UsbStatusChangeEvent
import com.jld.vod.utils.LogUtils
import com.jld.vod.utils.http.HttpFileUtil
import com.jld.vod.utils.http.ProgressListener
import com.jld.vod.utils.http.RetrofitCallback
import com.jld.vod.viewmodel.MainViewModel
import com.jld.vod.viewmodel.PostFileViewModel
import com.jld.vod.viewmodel.SplashViewModel
import okhttp3.Callback
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.Call
import retrofit2.Response
import java.io.File
import java.io.IOException

/**
 * @author ZhaoFuXin
 * @Email：18276061387@163.com
 * @description:
 * @date :2020/7/27 11:09
 */
class PostFileActivity : BaseActivity() {

    private var strFilePath:String? = null
    private lateinit var postFileViewModel: PostFileViewModel
    private lateinit var mainViewModel: MainViewModel
    private var progressdialog: ProgressDialog? = null
    private var totalitem = 0//数据大小
    private var lenitem = 1//当前上传数据下标
    private var flag = true
    private var context:Context? = null
    private val mHandler = Handler(Handler.Callback {
        when(it.what)
        {
             0->{
                 val id: Int = it.arg1
                 val file = it.obj as String

                 progressdialog!!.setTitle("Uploading Movie ( $lenitem/$totalitem )")
                 progressdialog!!.progress = id
                 progressdialog!!.setMessage(file)
                 progressdialog!!.setCancelable(false)
                 progressdialog!!.setCanceledOnTouchOutside(false)
                 progressdialog!!.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
                 progressdialog!!.show()

                 if (id == 100)
                 {
                     progressdialog!!.dismiss()
                 }
             }
            1->{
                val id: Int = it.arg1
                val file = it.obj as String
                progressdialog!!.setTitle("Uploading Music ( $lenitem/$totalitem )")
                progressdialog!!.progress = id
                progressdialog!!.setMessage(file)
                progressdialog!!.setCancelable(false)
                progressdialog!!.setCanceledOnTouchOutside(false)
                progressdialog!!.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
                progressdialog!!.show()

                if (id == 100)
                {
                    progressdialog!!.dismiss()
                }
            }
            2->{
                val id: Int = it.arg1
                val file = it.obj as String

                progressdialog!!.setTitle("Uploading Game ( $lenitem/$totalitem )")
                progressdialog!!.progress = id
                progressdialog!!.setMessage(file)
                progressdialog!!.setCancelable(false)
                progressdialog!!.setCanceledOnTouchOutside(false)
                progressdialog!!.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
                progressdialog!!.show()

                if (id == 100)
                {
                    progressdialog!!.dismiss()
                }
            }
        }
        false
    })


    override fun getLayoutId(): Int {
        return R.layout.activity_postfile
    }


    override fun initView() {
        super.initView()

        context = this
        progressdialog = ProgressDialog(this@PostFileActivity)
    }
    override fun initData() {
        super.initData()
        //u盘路径
        val mIntent = intent
        strFilePath = mIntent.getStringExtra("path")

        //接收U盘广播值
        EventBus.getDefault().register(this)

        //初始化viewmodel
        postFileViewModel = ViewModelProvider.AndroidViewModelFactory(application).create(PostFileViewModel::class.java)


        //获取未上传电影列表
        postFileViewModel.findResByNotUploadedmovie()

        //初始化电影列表
        initMovieList()
        //初始化音乐列表
        initMusicList()
        //初始化游戏列表
        initGameList()
    }

    /**
     * 初始化游戏列表
     */
    private fun initGameList() {
        //监听游戏列表
        postFileViewModel.findResByNotUploadedgameliveData.observe(this){res->
            LogUtils.logD("game"+res)
            when (res?.code) {
                BaseBean.SUCCESS -> {
                    finishLoading()

                    if (res.data!!.size != 0)
                    {
                        for ((index,data) in res.data.withIndex())
                        {
                            val file = File(strFilePath, data.gid.toString()+".apk")
                            val mid = data.mid
                            val resId = data.gid
                            if (file.exists())
                            {
                                //上传游戏
                                postFileGame(file,mid,resId)
                            }
                        }
                    }else{
                        LogUtils.logD("上传数据为空")
                    }
                }
                BaseBean.ERROR -> {
                    finishLoading()
                    Toast.makeText(this, res.message, Toast.LENGTH_SHORT).show()
                }
                BaseBean.LOADING -> showLoading()
            }
        }
    }

    /**
     * 初始化音乐列表
     */
    private fun initMusicList() {
        postFileViewModel.findResByNotUploadedmusicliveData.observe(this){res->
            when (res?.code) {
                BaseBean.SUCCESS -> {
                    flag = true
                    finishLoading()
                    if (res.data!!.size != 0)
                    {
                        for ((index,data) in res.data.withIndex())
                        {
                            val file = File(strFilePath, data.musicId.toString()+".mp3")
                            val mid = data.mid
                            val resId = data.musicId
                            if (file.exists())
                            {
                                //上传音乐
                                postFileMusic(file,mid,resId)
                            }else{
                                if (flag)
                                {
                                    flag = false
                                    postFileViewModel.findResByNotUploadedgame()//继续获取未上传游戏列表
                                }
                            }
                        }
                    }else{
                        postFileViewModel.findResByNotUploadedgame()//继续获取未上传游戏列表
                    }
                }
                BaseBean.ERROR -> {
                    finishLoading()
                    Toast.makeText(this, res.message, Toast.LENGTH_SHORT).show()
                }
                BaseBean.LOADING -> showLoading()
            }
        }
    }

    /**
     * 初始化电影列表
     */
    private fun initMovieList() {
        postFileViewModel.findResByNotUploadedmovieliveData.observe(this){res->
            LogUtils.logD("movie"+res)
            when (res?.code) {
                BaseBean.SUCCESS -> {
                    finishLoading()
                    if (res.data!!.size != 0)
                    {
                        for ((index,data) in res.data.withIndex())
                        {
                            val file = File(strFilePath, data.movieId.toString()+".mp4")
                            val mid = data.mid
                            val resId = data.movieId
                            if (file.exists())
                            {
                                //上传电影
                                postFileMovie(file,mid,resId)
                            }else{
                                if (flag)
                                {
                                    flag = false
                                    postFileViewModel.findResByNotUploadedmusic()//继续获取未上传音乐列表
                                }

                            }
                        }
                    }else{
                        postFileViewModel.findResByNotUploadedmusic()//继续获取未上传音乐列表
                    }
                }
                BaseBean.ERROR -> {
                    finishLoading()
                    Toast.makeText(this, res.message, Toast.LENGTH_SHORT).show()
                }
                BaseBean.LOADING -> showLoading()
            }
        }
    }

    /**
     * 上传游戏
     */
    private fun postFileGame(file: File,mid : Long,resId:Long) {
        totalitem++
        HttpFileUtil.postFile(this, Config.ApiBaseUrl + "/game/upload",
            object : ProgressListener {
                override fun onProgress(currentBytes: Long, contentLength: Long, done: Boolean) {
                    //  Log.i(TAG, "file="+file.getName()+"id="+id+"currentBytes==" + currentBytes + "==contentLength==" + contentLength + "==done==" + done);
                    val progress = (currentBytes * 100 / contentLength).toInt()
                    if (done == true) {
                        lenitem++
                        if (lenitem == totalitem)
                        {
                            //数据下标重置
                            lenitem = 1
                            totalitem = 0
                            //postFileViewModel.findResByNotUploadedgame()//继续获取未上传游戏列表
                        }
                    }
                    val msg: Message = mHandler.obtainMessage()
                    msg.arg1 = progress
                    msg.what = 2
                    msg.obj = file.name
                    mHandler.sendMessage(msg)
                }
            }, object : Callback {
                override fun onFailure(call: okhttp3.Call, e: IOException) {
                    LogUtils.logE(e.toString())
                }

                @Throws(IOException::class)
                override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
                    val result = response.body!!.string()
                    LogUtils.logD(result.toString())
                }
            }, file,mid,resId)
    }

    /**
     * 上传音乐
     */
    private fun postFileMusic(file: File,mid : Long,resId:Long) {
        totalitem++
        HttpFileUtil.postFile(this, Config.ApiBaseUrl + "/music/upload",
            object : ProgressListener {
                override fun onProgress(currentBytes: Long, contentLength: Long, done: Boolean) {
                    //  Log.i(TAG, "file="+file.getName()+"id="+id+"currentBytes==" + currentBytes + "==contentLength==" + contentLength + "==done==" + done);
                    val progress = (currentBytes * 100 / contentLength).toInt()
                    if (done == true) {
                        lenitem++
                        if (lenitem == totalitem)
                        {
                            //数据下标重置
                            lenitem = 1
                            totalitem = 0
                            postFileViewModel.findResByNotUploadedgame()//继续获取未上传游戏列表
                        }
                    }
                    val msg: Message = mHandler.obtainMessage()
                    msg.arg1 = progress
                    msg.what = 1
                    msg.obj = file.name
                    mHandler.sendMessage(msg)
                }
            }, object : Callback {
                override fun onFailure(call: okhttp3.Call, e: IOException) {
                    LogUtils.logE(e.toString())
                }

                @Throws(IOException::class)
                override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
                    val result = response.body!!.string()
                    LogUtils.logD(result.toString())
                }
            }, file,mid,resId)
    }

    /**
     * 上传电影
     */
    private fun postFileMovie(file: File,mid : Long,resId:Long) {
        totalitem++
        HttpFileUtil.postFile(this, Config.ApiBaseUrl + "/movie/upload",
            object : ProgressListener {
                override fun onProgress(currentBytes: Long, contentLength: Long, done: Boolean) {
                    //  Log.i(TAG, "file="+file.getName()+"id="+id+"currentBytes==" + currentBytes + "==contentLength==" + contentLength + "==done==" + done);
                    val progress = (currentBytes * 100 / contentLength).toInt()
                    if (done == true) {
                        lenitem++
                        if (lenitem == totalitem)
                        {
                            //数据下标重置
                            lenitem = 1
                            totalitem = 0
                            postFileViewModel.findResByNotUploadedmusic()//继续获取未上传音乐列表
                        }
                    }
                    val msg: Message = mHandler.obtainMessage()
                    msg.arg1 = progress
                    msg.what = 0
                    msg.obj = file.name
                    mHandler.sendMessage(msg)
                }
            }, object : Callback {
                override fun onFailure(call: okhttp3.Call, e: IOException) {
                    LogUtils.logE(e.toString())
                }

                @Throws(IOException::class)
                override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
                    val result = response.body!!.string()
                    LogUtils.logD(result.toString())
                }
            }, file,mid,resId)
    }

    override fun onDestroy() {
        super.onDestroy()
        progressdialog!!.dismiss()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }


    /**
     * 广播传来值处理
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetworkChangeEvent(event: UsbStatusChangeEvent) {
        if (event.isConnected) {
            finish()
        }
    }

}