package com.yidianling.course

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.ydl.ydlcommon.actions.share.ShareUtils
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.utils.ImageUtil
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.view.dialog.YDLShareDialog
import com.yidianling.common.tools.ToastUtil
import com.yidianling.course.bean.PostersShareBean
import com.yidianling.course.net.CourseRetrofitUtils
import com.yidianling.course.widget.CoursePosterTemplate
import com.yidianling.course.widget.CustomPagerTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_course_poster.*


/**
 * @author jiucheng
 * @描述:课程生成海报
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2019/8/6
 */
@Route(path = "/course/poster")
class CoursePosterActivity : BaseActivity() {
    private val posterLayoutList = ArrayList<View>()
    private var courseId: String? = null
    private var bean: PostersShareBean? = null
    private lateinit var posterView: CoursePosterTemplate
    private lateinit var posterView2: CoursePosterTemplate

    companion object {
        private const val COURSE_ID = "course_id"
        fun startActivity(activity: Activity, courseId: String) {
            var intent = Intent(activity, CoursePosterActivity::class.java)
            intent.putExtra(COURSE_ID, courseId)
            activity.startActivity(intent)
        }
    }

    override fun layoutResId(): Int {
        window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        return R.layout.activity_course_poster
    }

    override fun initDataAndEvent() {
        courseId = intent.getStringExtra(COURSE_ID)
        StatusBarUtils.setWindowStatusBarColor(mContext, R.color.course_color_66000000)
        if (TextUtils.isEmpty(courseId)) {
            ToastUtil.toastShort("参数错误")
            return
        }

        iv_back.setOnClickListener {
            finish()
        }

        getData()

        posterView = CoursePosterTemplate(this)
        posterLayoutList.add(posterView)

        posterView2 = CoursePosterTemplate(this)
        posterLayoutList.add(posterView2)

        viewpager.setPageTransformer(false, CustomPagerTransformer(this))
        viewpager.adapter = PosterPagerAdapter()
        viewpager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                if (position == 0) {
                    radio_group.check(R.id.rb_one)
                } else {
                    radio_group.check(R.id.rb_two)
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })

        radio_group.setOnCheckedChangeListener { _, checkedId ->
            if (checkedId == R.id.rb_two) {
                viewpager.currentItem = 1
            } else {
                viewpager.currentItem = 0
            }
        }

        tv_share.setOnClickListener {
            showShareDialog()
        }
    }

    @SuppressLint("CheckResult")
    private fun getData() {
        CourseRetrofitUtils.getPosterData(courseId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp ->
                dismissProgressDialog()
                if (resp.code == 200) {
                    bean = resp.data
                    initViewData()
                } else {
                    ToastUtil.toastShort(resp.msg)
                }
            }, { t ->
                dismissProgressDialog()
                ToastUtil.toastShort(t.localizedMessage)
            })
    }

    private fun initViewData() {
        if (bean == null) {
            ToastUtil.toastShort("数据错误")
            return
        }
        posterView.setData(bean!!, true)
        posterView2.setData(bean!!, false)
    }


    private fun showShareDialog() {
        if (bean!!.shareData == null) {
            ToastUtil.toastShort("分享参数错误")
            return
        }

        val dialog = YDLShareDialog.style6(
            this,
            bean!!.shareData!!.title,
            bean!!.shareData!!.share_url,
            bean!!.shareData!!.desc,
            bean!!.shareData!!.cover
        )
        dialog.setCallBack(object : YDLShareDialog.ICallBack {
            override fun callBack(type: Int) {
                if (type == 6) {
                    ImageUtil.savePicture(
                        this@CoursePosterActivity,
                        createViewBitmap(if (viewpager.currentItem == 0) posterView else posterView2)
                    )
                }
                if (type == 7) {
                    ShareUtils.sharePicToWeiXin(
                        this@CoursePosterActivity,
                        createViewBitmap(if (viewpager.currentItem == 0) posterView else posterView2)
                    )
                    dialog.dismiss()
                }
            }
        })
        dialog.show(fragmentManager, "lose")
    }

    private fun createViewBitmap(v: View): Bitmap? {
        if (this.isFinishing) {
            return null
        }
        var bitmap = Bitmap.createBitmap(v.width, v.height, Bitmap.Config.ARGB_8888)
        var canvas = Canvas(bitmap)
        v.draw(canvas)
        return bitmap
    }

    internal inner class PosterPagerAdapter : PagerAdapter() {

        override fun getCount(): Int {
            return posterLayoutList.size
        }

        override fun isViewFromObject(view: View, `object`: Any): Boolean {
            return view === `object`
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val view = posterLayoutList[position]
            container.addView(view)
            return view
        }

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View)
        }
    }
}