package com.yidianling.consultant.preview

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.yidianling.consultant.R
import com.yidianling.consultant.constants.ConsultBIConstants
import com.yidianling.consultant.preview.GPreviewBuilder.IndicatorType
import com.yidianling.consultant.preview.SmoothImageView.onTransformListener
import com.yidianling.im.api.listener.ApiStringResponseCallback
import com.yidianling.im.api.service.IImService
import kotlinx.android.synthetic.main.consultant_image_preview_photo.*
import java.util.*

/**
 * @author rainb
 */
class GPreviewActivity : AppCompatActivity() {
    protected var isTransformOut = false

    /*** 图片的地址 */
    private var imgUrls: MutableList<IThumbViewInfo>? = null

    /*** 当前图片的位置  */
    protected var currentIndex = 0

    /***指示器类型枚举 */
    private var type: IndicatorType? = null

    /***默认显示 */
    private var isShow = true

    private var toUid: String? = null

    private var doctorId: String? = null
    /***
     * 得到PhotoViewPager
     * @return PhotoViewPager
     */
    /*** 展示图片的viewPager  */
    var viewPager: PhotoViewPager? = null
        private set

    /*** 图片的展示的Fragment */
    private var fragments: MutableList<BasePhotoFragment>? = ArrayList()
    private var backIv: View? = null
    private var btnLL: View? = null
    private var titleBar: View? = null
    private var selectPosition: TextView? = null
    private var total: TextView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initData()
        setContentView(R.layout.consultant_image_preview_photo)
        setWindowStatusBarColor()
        initView()
    }

    /**
     * 初始化状态栏位置
     */

    private fun setWindowStatusBarColor() {
        StatusBarUtils.Companion.setWindowStatusBarColor(this, R.color.black)
        StatusBarUtils.Companion.setStatusBarLightMode(this, false)
    }

    private fun initView() {
        viewPager = findViewById(R.id.viewPager)
        //viewPager的适配器
        val adapter = PhotoPagerAdapter(supportFragmentManager)
        viewPager?.adapter = adapter
        viewPager?.currentItem = currentIndex
        backIv = findViewById(R.id.ivBack)
        btnLL = findViewById(R.id.btnLL)
        selectPosition = findViewById(R.id.select_position)
        total = findViewById(R.id.total)
        titleBar = findViewById(R.id.titleBar)

        chatBtn.setOnClickListener {
            //私聊
            if (!toUid.isNullOrBlank()) {
                ModularServiceManager.provide(IImService::class.java)
                    .startChat(this@GPreviewActivity, toUid.toString(), 0x001, 0, 0, false)

                Timer().schedule(object : TimerTask() {
                    override fun run() {
                        runOnUiThread {
                            if (fragments != null && currentIndex < fragments!!.size) {
                                fragments!![currentIndex].stopVideo()
                            }
                        }
                    }
                }, 2000)

                ActionCountUtils.count(
                    ConsultBIConstants.Experts.EXPERT_BANNER_PRIVATE_CHAT_CLICK,
                    toUid.toString()
                )

            }
        }


        bookingBtn.setOnClickListener {
            toUid?.let { toUid ->
                doctorId?.let { doctorId ->
                    ModularServiceManager.provide(IImService::class.java)
                        .showConsultServiceDialog(
                            activity = this,
                            toUid = toUid,
                            doctorId = doctorId
                        )
                }
                ActionCountUtils.count(
                    ConsultBIConstants.Experts.EXPERT_BANNER_IMMEDIATELY_BOOKING_CLICK,
                    toUid
                )
            }


        }


        backIv?.setOnClickListener(View.OnClickListener {
            transformOutAnim()
            transformOut()
        })
        selectPosition?.setText((currentIndex + 1).toString() + "")
        total?.setText(if (imgUrls == null) "0" else imgUrls!!.size.toString() + "")
        viewPager?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                currentIndex = position;
                selectPosition?.setText((position + 1).toString() + "")
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
//        viewPager.setOffscreenPageLimit(3);
    }

    override fun onResume() {
        super.onResume()
        if (toUid != null) {
            //在uid用户类型确定为专家的情况下，根据uid调用接口判断是进入专家私聊还是助理私聊
            try {
                ModularServiceManager.provide(IImService::class.java)
                    .getChatUid(context = this, uid = toUid!!, callback = object :
                        ApiStringResponseCallback {
                        override fun onUidCallback(uid: String) {
                            val unReadNum =
                                ModularServiceManager.provide(IImService::class.java)
                                    .getUnReadByUid(uid!!)
                            when {
                                unReadNum <= 0 -> {
                                    un_read_num_ll.visibility = View.GONE
                                }
                                unReadNum > 99 -> {
                                    un_read_num_ll.visibility = View.VISIBLE
                                    un_read_num.text = "99"
                                }
                                else -> {
                                    un_read_num_ll.visibility = View.VISIBLE
                                    un_read_num.text = unReadNum.toString()
                                }
                            }
                        }
                    })
            } catch (e: Exception) {
            }
        }
    }

    private fun initData() {
        imgUrls = intent.getParcelableArrayListExtra("imagePaths")
        currentIndex = intent.getIntExtra("position", -1)
        type = intent.getSerializableExtra("type") as IndicatorType
        isShow = intent.getBooleanExtra("isShow", true)
        toUid = intent.getStringExtra("toUid")
        doctorId = intent.getStringExtra("doctorId")

        val isScale = intent.getBooleanExtra("isScale", false)
        SmoothImageView.setIsScale(isScale)
        initFragment(imgUrls, currentIndex, BasePhotoFragment::class.java)


    }

    private fun initFragment(
        imgUrls: List<IThumbViewInfo>?,
        currentIndex: Int,
        className: Class<BasePhotoFragment>
    ) {
        if (imgUrls != null) {
            val size = imgUrls.size
            for (i in 0 until size) {
                fragments!!.add(
                    BasePhotoFragment.getInstance(
                        className, imgUrls[i],
                        currentIndex == i,
                        intent.getBooleanExtra("isSingleFling", false),
                        intent.getBooleanExtra("isDrag", false),
                        intent.getFloatExtra("sensitivity", 0.5f)
                    )
                )
            }
        } else {
            finish()
        }
    }

    override fun onDestroy() {
        ZoomMediaLoader.getInstance().loader.clearMemory(this)
        if (viewPager != null) {
            viewPager!!.adapter = null
            viewPager!!.clearOnPageChangeListeners()
            viewPager!!.removeAllViews()
            viewPager = null
        }
        if (fragments != null) {
            fragments!!.clear()
            fragments = null
        }
        if (imgUrls != null) {
            imgUrls!!.clear()
            imgUrls = null
        }
        super.onDestroy()
    }

    /***
     * 得到PhotoViewPager
     * @return PhotoViewPager
     */
    @JvmName("getViewPager1")
    fun getViewPager(): PhotoViewPager? {
        return viewPager
    }

    fun transformOut() {
        if (isTransformOut) {
            return
        }
        viewPager!!.isEnabled = false
        isTransformOut = true
        val currentItem = viewPager!!.currentItem
        if (currentItem < imgUrls!!.size) {
            if (imgUrls!![currentItem].sourcesType == 1) {
                val fragment = fragments!![currentItem]
                fragment.changeBg(Color.TRANSPARENT)
                fragment.transformOut(onTransformListener {
                    getViewPager()?.setEnabled(true)
                    exit()
                })
            } else if (imgUrls!![currentItem].sourcesType == 2) {
                exitNormal()
            }
        } else {
            exit()
        }
    }

    /**
     * 关闭页面
     */
    private fun exit() {
        finish()
        overridePendingTransition(0, 0)
    }

    private fun exitNormal() {
        finish()
    }

    override fun onBackPressed() {
        isTransformOut = false
        transformOutAnim()
        transformOut()
    }

    override fun finish() {
//        BasePhotoFragment.listener=null;
        super.finish()
    }

    /**
     * pager的适配器
     */
    private inner class PhotoPagerAdapter internal constructor(fm: FragmentManager?) :
        FragmentStatePagerAdapter(fm!!) {
        override fun getItem(position: Int): Fragment {
            return fragments!![position]
        }

        override fun getCount(): Int {
            return if (fragments == null) 0 else fragments!!.size
        }
    }

    fun hindView() {
        titleBar!!.visibility = View.GONE
        btnLL!!.visibility = View.GONE
    }

    fun showView() {
        titleBar!!.visibility = View.VISIBLE
        btnLL!!.visibility = View.VISIBLE
    }

    @SuppressLint("ObjectAnimatorBinding")
    fun transformOutAnim() {
        val animator1 = ObjectAnimator.ofFloat(titleBar, "alpha", 1.0f, 0.0f)
        animator1.duration = 200
        animator1.start()
        val animator2 = ObjectAnimator.ofFloat(btnLL, "alpha", 1.0f, 0.0f)
        animator2.duration = 200
        animator2.start()
    }
}