package com.yidianling.consultant.preview

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.SeekBar
import androidx.annotation.CallSuper
import androidx.core.view.ViewCompat
import androidx.fragment.app.Fragment
import com.dou361.ijkplayer.widget.IjkVideoView
import com.ydl.ydlcommon.ui.Loading.close
import com.ydl.ydlcommon.ui.Loading.show
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.common.tools.RxNetTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.consultant.R
import com.yidianling.consultant.preview.SmoothImageView.*
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import tv.danmaku.ijk.media.player.IMediaPlayer
import java.util.concurrent.TimeUnit

/**
 * @author rainb
 * Deprecated: 图片预览单个图片的fragment
 */
class BasePhotoFragment : Fragment() {
    var beanViewInfo: IThumbViewInfo? = null
        private set
    private var isTransPhoto = false
    protected var imageView: SmoothImageView? = null
    protected var rootView: View? = null
    protected var loading: View? = null
    protected var mySimpleTarget: MySimpleTarget? = null
    protected var btnVideo: View? = null
    private var btnLL: RelativeLayout? = null
    private var videoContainer: RelativeLayout? = null
    private var videoView: IjkVideoView? = null
    private var disposable: Disposable? = null
    private var seekBar: SeekBar? = null
    private var ivPlay: View? = null
    private var isPrepared = false
    private var ivImg: ImageView? = null

    private val keySp = "check_network_continue"

    @Volatile
    private var isTouch = false
    private var isCompletion = false
    private var isVisiable = false
    private val ivBack: View? = null
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_image_photo_layout, container, false)
    }

    @CallSuper
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(view)
        initData()
    }

    @CallSuper
    override fun onStop() {
        ZoomMediaLoader.getInstance().loader.onStop(this)
        super.onStop()
    }

    @CallSuper
    override fun onDestroyView() {
        super.onDestroyView()
        release()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        isVisiable = isVisibleToUser
        if (!isVisibleToUser && beanViewInfo != null) {
            videoView!!.seekTo(0)
            seekBar!!.progress = 0
            videoView!!.pause()
            if (ivPlay != null && beanViewInfo?.sourcesType == 2) {
                ivPlay?.visibility = VISIBLE
//                if (ivImg != null) {
//                    ivImg?.visibility = VISIBLE
//                }
            } else if (ivPlay != null && beanViewInfo?.sourcesType == 1) {
                ivPlay?.visibility = GONE
                if (ivImg != null) {
                    ivImg!!.visibility = GONE
                }
            }
            stopTiming()
        }else if (isVisibleToUser && beanViewInfo != null && beanViewInfo?.sourcesType == 2) {
            if (videoView != null) {
                checkNetwork()
            }
        }

        if (!isVisiable) {
            videoView?.visibility = INVISIBLE
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ZoomMediaLoader.getInstance().loader.clearMemory(requireActivity())
    }

    fun release() {
        isTransPhoto = false
        if (videoView != null) {
            videoView!!.release(true)
            stopTiming()
        }
    }

    /**
     * 初始化控件
     */
    private fun initView(view: View) {
        loading = view.findViewById(R.id.loading)
        imageView = view.findViewById(R.id.photoView)
        btnVideo = view.findViewById(R.id.btnVideo)
        rootView = view.findViewById(R.id.rootView)
        rootView?.setDrawingCacheEnabled(false)
        imageView?.setDrawingCacheEnabled(false)
        btnLL = view.findViewById(R.id.btnLL)
        imageView?.setOnDragListener(object : OnDragListener {
            override fun drag() {
                (activity as GPreviewActivity?)!!.hindView()
            }

            override fun actionCancel() {
                (activity as GPreviewActivity?)!!.showView()
            }
        })
        videoContainer = view.findViewById(R.id.videoContainer)
        videoView = view.findViewById(R.id.videoView)
        seekBar = view.findViewById(R.id.seekbar)
        ivPlay = view.findViewById(R.id.ivPlay)
        ivImg = view.findViewById(R.id.ivImage)
        mySimpleTarget = object : MySimpleTarget {
            override fun onResourceReady() {
                loading?.setVisibility(GONE)
                imageView?.setBackgroundResource(R.color.transparent)
                //                String video = beanViewInfo.getVideoUrl();
//                if (video != null && !video.isEmpty()) {
//                    btnVideo.setVisibility(View.VISIBLE);
//                    ViewCompat.animate(btnVideo).alpha(1).setDuration(1000).start();
//                } else {
//                    btnVideo.setVisibility(View.GONE);
//                }
            }

            override fun onLoadFailed(errorDrawable: Drawable?) {
                loading?.setVisibility(GONE)
                imageView?.setBackgroundResource(R.color.transparent)
                if (isVisiable) {
                    ToastUtil.toastShort(activity, "加载失败")
                }
                if (errorDrawable != null) {
                    imageView?.setImageDrawable(errorDrawable)
                }
            }
        }
    }

    /**
     * 初始化数据
     */
    private fun initData() {
        val bundle = arguments
        var isSingleFling = true
        // 非动画进入的Fragment，默认背景为黑色
        if (bundle != null) {
            isSingleFling = bundle.getBoolean(KEY_SING_FILING)
            //地址
            beanViewInfo = bundle.getParcelable(KEY_PATH)
            assert(beanViewInfo != null)
            //imageView.setDrag(bundle.getBoolean(KEY_DRAG), bundle.getFloat(KEY_SEN));
            imageView!!.setThumbRect(beanViewInfo?.getBounds())
            rootView!!.tag = beanViewInfo?.getUrl()
            //是否展示动画
            isTransPhoto = bundle.getBoolean(KEY_TRANS_PHOTO, false)
            if (beanViewInfo?.sourcesType == 1) {
                ivPlay!!.visibility = GONE
                if (beanViewInfo!!.getUrl().toLowerCase().contains(".gif")) {
                    imageView!!.visibility = VISIBLE
                    videoContainer!!.visibility = GONE
                    imageView!!.setZoomable(false)
                    //加载图
                    ZoomMediaLoader.getInstance().loader.displayGifImage(
                        this, beanViewInfo!!.getUrl(), imageView,
                        mySimpleTarget!!
                    )
                } else {
                    //加载图
                    ZoomMediaLoader.getInstance().loader.displayImage(
                        this, beanViewInfo!!.getUrl(), imageView,
                        mySimpleTarget!!
                    )
                }
            } else if (beanViewInfo?.sourcesType == 2) {
//                ivPlay!!.visibility = VISIBLE
                videoContainer!!.visibility = VISIBLE
                imageView!!.visibility = GONE
                ZoomMediaLoader.getInstance().loader.displayImage(
                    this, beanViewInfo!!.cover, ivImg,
                    mySimpleTarget!!
                )
                val videoUlr = beanViewInfo!!.url
                if (!TextUtils.isEmpty(videoUlr)) {
                    rootView!!.setBackgroundColor(Color.BLACK)
                    seekBar!!.visibility = VISIBLE
                    videoView!!.setVideoURI(Uri.parse(videoUlr))
                    videoView!!.setOnPreparedListener { iMediaPlayer ->
                        loading!!.visibility = GONE
                        isPrepared = true
                        val maxProgress = iMediaPlayer.duration.toInt()
                        if (maxProgress > 0) {
                            seekBar!!.max = maxProgress
                        } else {
                            seekBar!!.visibility = GONE
                        }
                    }
                    videoView!!.setOnCompletionListener {
                        isCompletion = true
                        videoView!!.seekTo(0)
                        stopTiming()
                        ivPlay!!.visibility = VISIBLE
                    }
                    videoView!!.setOnInfoListener { iMediaPlayer, what, extra ->
                        if (what == IMediaPlayer.MEDIA_INFO_BUFFERING_START && !isCompletion && isVisiable) {
                            show(context, "正在加载")
                        } else if (what == IMediaPlayer.MEDIA_INFO_BUFFERING_END) {
                            close()
                        }
                        true
                    }

                    if (isVisiable) {
                        ivPlay?.visibility = VISIBLE
                        checkNetwork()
                    }else {
                        ivPlay?.visibility = GONE
                    }

                    ivPlay!!.setOnClickListener {
                        checkNetwork()
                    }
                    videoContainer!!.setOnClickListener {
                        if (videoView!!.isPlaying) {
                            ivPlay!!.visibility = VISIBLE
                            stopTiming()
                            videoView!!.pause()
                        }
                    }
                    seekBar!!.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
                        override fun onProgressChanged(
                            seekBar: SeekBar,
                            progress: Int,
                            fromUser: Boolean
                        ) {
                        }

                        override fun onStartTrackingTouch(seekBar: SeekBar) {
                            isTouch = true
                        }

                        override fun onStopTrackingTouch(seekBar: SeekBar) {
                            isTouch = false
                            if (seekBar != null) {
                                videoView!!.seekTo(seekBar.progress)
                                videoView!!.start()
                                ivPlay!!.visibility = GONE
                                isCompletion = false
                            }
                        }
                    })
                }
            }
        }
        if (!isTransPhoto) {
            rootView!!.setBackgroundColor(Color.BLACK)
        } else {
            imageView!!.minimumScale = 0.7f
        }
        if (isSingleFling) {
            imageView!!.setOnViewTapListener { view, x, y -> }
            imageView!!.setOnViewTapListener { view, x, y ->
                if (imageView!!.checkMinScale()) {
                    (activity as GPreviewActivity?)!!.transformOut()
                }
            }
        } else {
            imageView!!.setOnPhotoTapListener(object : PhotoViewAttacher.OnPhotoTapListener {
                override fun onPhotoTap(view: View, x: Float, y: Float) {
                    if (imageView!!.checkMinScale()) {
                        (activity as GPreviewActivity?)!!.transformOutAnim()
                        (activity as GPreviewActivity?)!!.transformOut()
                    }
                }

                override fun onOutsidePhotoTap() {}
            })
        }
        imageView!!.setAlphaChangeListener { alpha ->
            if (alpha == 255) {
                val video = beanViewInfo!!.url
                if (video != null && !video.isEmpty()) {
                    btnVideo!!.visibility = VISIBLE
                } else {
                    btnVideo!!.visibility = GONE
                }
            } else {
                btnVideo!!.visibility = GONE
            }
            rootView!!.setBackgroundColor(
                getColorWithAlpha(
                    alpha / 255f,
                    Color.BLACK
                )
            )
        }
        imageView!!.setTransformOutListener { (activity as GPreviewActivity?)!!.transformOut() }
    }


    internal fun checkNetwork() {
        val lastCheck =
            context?.getSharedPreferences("temp_test", Context.MODE_PRIVATE)?.getLong(keySp, 0)
        val duration = System.currentTimeMillis() - lastCheck!!
        if (!RxNetTool.isWifi(requireActivity()!!) && duration > 24 * 60 * 60 * 1000) {
            val dialog = CommonDialog.create(context)
                .setTitle("提示")
                .setMessage("当前处于非wifi环境下，播放会消耗流量，确定继续播放？")
                .setLeftOnclick("继续播放") {
                    if (!isPrepared) {
                        loading?.visibility = VISIBLE
                    }
                    ivImg?.visibility = GONE
                    ivPlay?.visibility = GONE
                    startTiming()
                    videoView?.visibility = VISIBLE
                    videoView?.start()
                    isCompletion = false

                    context?.getSharedPreferences("temp_test", Context.MODE_PRIVATE)?.edit()
                        ?.putLong(keySp, System.currentTimeMillis())?.apply()
                }
                .setLeftButton_color(R.color.platform_but_text_color_selected)
                .setRightButton_color(R.color.platform_text_bright_color)
                .setRightClick("取消") {
                }
                .setCancelAble(true)
            dialog.setOnCancelListener {
                dialog.dismiss()
            }
            dialog.show()
        } else {
            if (!isPrepared) {
                loading?.visibility = VISIBLE
            }
            ivImg?.visibility = GONE
            ivPlay?.visibility = GONE
            startTiming()
            videoView?.visibility = VISIBLE
            videoView?.start()
            isCompletion = false
        }
    }

    fun transformIn() {
        assert(imageView != null)
        imageView!!.transformIn { rootView!!.setBackgroundColor(Color.BLACK) }
    }

    fun transformOut(listener: onTransformListener?) {
        assert(imageView != null)
        imageView!!.transformOut(listener)
    }

    fun changeBg(color: Int) {
        ViewCompat.animate(btnVideo!!).alpha(0f).setDuration(getDuration().toLong()).start()
        rootView!!.setBackgroundColor(color)
    }

    private fun startTiming() {
        disposable = Observable.interval(3, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.computation())
            .subscribe { //                        val pos = (video?.mMediaPlayer as IjkMediaPlayer?)?.currentPosition ?: 0
                //                        if (pos > 0) {
                ////                    if (vm?.isVideo == true) {
                ////                        binding.ivCover.visibility = View.GONE
                ////                    }
                //                            if (!isTouch) {
                //                                binding.seekbar.progress = pos.toInt()// video.bufferPercentage
                //                            }
                //                            if (video?.isPlaying == true) {
                //                                when (vm?.isVideo) {
                //                                    true -> {
                //                                        binding.ivPlay.visibility = View.GONE
                //                                    }
                //                                    false -> {
                //                                        binding.voicePlay.start()
                //                                    }
                //                                }
                //                            }
                //                        }
                if (videoView != null && !isTouch) {
                    val currentPosition = videoView!!.currentPosition
                    seekBar!!.progress = currentPosition
                }
            }
    }

    private fun stopTiming() {
        if (disposable != null) {
            disposable!!.dispose()
            disposable = null
        }
    }

    interface OnDragListener {
        fun drag()
        fun actionCancel()
    }

    fun stopVideo() {
        if (videoView != null && videoView!!.isPlaying) {
            ivPlay!!.visibility = VISIBLE
            stopTiming()
            videoView!!.pause()
        }
    }

    companion object {
        /**
         * 预览图片 类型
         */
        private const val KEY_TRANS_PHOTO = "is_trans_photo"
        private const val KEY_SING_FILING = "isSingleFling"
        private const val KEY_PATH = "key_item"
        private const val KEY_DRAG = "isDrag"
        private const val KEY_SEN = "sensitivity"

        //    public static VideoClickListener listener;
        fun getInstance(
            fragmentClass: Class<out BasePhotoFragment>,
            item: IThumbViewInfo?,
            currentIndex: Boolean,
            isSingleFling: Boolean,
            isDrag: Boolean,
            sensitivity: Float
        ): BasePhotoFragment {
            val fragment: BasePhotoFragment
            fragment = try {
                fragmentClass.newInstance()
            } catch (e: Exception) {
                BasePhotoFragment()
            }
            val bundle = Bundle()
            bundle.putParcelable(KEY_PATH, item)
            bundle.putBoolean(KEY_TRANS_PHOTO, currentIndex)
            bundle.putBoolean(KEY_SING_FILING, isSingleFling)
            bundle.putBoolean(KEY_DRAG, isDrag)
            bundle.putFloat(KEY_SEN, sensitivity)
            fragment.arguments = bundle
            return fragment
        }

        fun getColorWithAlpha(alpha: Float, baseColor: Int): Int {
            val a = Math.min(255, Math.max(0, (alpha * 255).toInt())) shl 24
            val rgb = 0x00ffffff and baseColor
            return a + rgb
        }
    }
}