package com.yidianling.course.widget

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.graphics.Paint
import androidx.constraintlayout.widget.ConstraintLayout
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import com.alibaba.android.arouter.launcher.ARouter
import com.lzf.easyfloat.permission.PermissionUtils
import com.ydl.media.audio.AudioPlayer
import com.ydl.media.audio.model.Music
import com.ydl.media.view.PlayTypeEnum
import com.ydl.media.view.PlayerFloatHelper
import com.ydl.media.view.PlayerFloatView
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_image.module.GlideApp
import com.ydl.ydlcommon.modular.ModularServiceManager.provide
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.yidianling.common.tools.RxImageTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.consultant.api.IConsultantService
import com.yidianling.course.CourseConstants
import com.yidianling.course.R
import com.yidianling.course.bean.Course
import com.yidianling.course.constants.CourseBIConstants
import kotlinx.android.synthetic.main.item_course_new_list_view.view.*

/**
 * @author jiucheng
 * @描述:课程列表页改版后的itemView
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2019/8/13
 */
class CourseItemNewView : ConstraintLayout {
    private var mContext: Context
    private lateinit var course: Course
    private var statusListener: PlayerFloatView.FloatViewPlayListener? = null
    private var headUrl: String = ""
    private var doctorName: String = ""

    constructor(mContext: Context) : super(mContext) {
        this.mContext = mContext
        initView()
    }

    constructor(mContext: Context, attr: AttributeSet) : super(mContext, attr) {
        this.mContext = mContext
        initView()
    }


    fun initView() {
        View.inflate(mContext, R.layout.item_course_new_list_view, this)
        val params = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
        layoutParams = params
        setPadding(RxImageTool.dp2px(13f), 0, RxImageTool.dp2px(15f), 0)
    }

    @SuppressLint("SetTextI18n")
    fun setData(course: Course) {
        this.course = course
        if (!TextUtils.isEmpty(course.hostListPic)) {
            headUrl = course.hostListPic
        } else {
            if (course.courseHostInfo != null && !TextUtils.isEmpty(course.courseHostInfo.doctorHead)) {
                headUrl = course.courseHostInfo.doctorHead
            }
        }

        GlideApp.with(mContext)
            .load(headUrl)
            .into(iv_head)

        //活动标签
        if (course.joinActivity && !TextUtils.isEmpty(course.activityImg)) {
            img_activity.visibility = View.VISIBLE
            GlideApp.with(context).load(course.activityImg).into(img_activity)
            tv_title.text = "\u3000\u3000\u3000\u0020" + course.title
        } else {
            img_activity.visibility = View.GONE
            tv_title.text = course.title
        }

        if (!TextUtils.isEmpty(course.doctorName)) {
            doctorName = course.doctorName
        } else {
            if (course.courseHostInfo != null && !TextUtils.isEmpty(course.courseHostInfo.doctorName)) {
                doctorName = course.courseHostInfo.doctorName
            }
        }
        var info = ""
        if (!TextUtils.isEmpty(course.hostInfo)) {
            info = course.hostInfo
        } else {
            if (course.courseHostInfo != null && !TextUtils.isEmpty(course.courseHostInfo.title)) {
                info = course.courseHostInfo.title
            }
        }

        if (TextUtils.isEmpty(doctorName) || TextUtils.isEmpty(info)) {
            tv_doctor_info.text = "壹点灵课程精选讲师"
        } else {
            tv_doctor_info.text = "$doctorName · $info"
        }

        tv_course_info.text = "共${course.subCourseNum}讲"
        tv_course_num.text = "${course.joinNum}人已学"
        if (course.subCourseNum == 0) {
            tv_course_info.visibility = View.GONE
            view_line.visibility = View.GONE
        } else {
            tv_course_info.visibility = View.VISIBLE
            view_line.visibility = View.VISIBLE
        }

        if (course.isInvite == 0) {
            tv_fan_li.visibility = View.GONE
        } else {
            tv_fan_li.visibility = View.VISIBLE
        }

        if (course.newCourse == 1) {
            iv_new.visibility = View.VISIBLE
        } else {
            iv_new.visibility = View.GONE
        }

        if (course.recommend == 2) {
            iv_hot.visibility = View.VISIBLE
        } else {
            iv_hot.visibility = View.GONE
        }

        if (course.demoType == 0) {
            iv_play.visibility = View.GONE
        } else {
            iv_play.visibility = View.VISIBLE
        }

        iv_play.setOnClickListener {
            playMedia()

            ActionCountUtils.count(
                CourseBIConstants.CourseListEvent.POSITION_COURSE_LIST_AUDITION_CLICK,
                course.id
            )
        }

        tv_view_course.setOnClickListener {
            if (TextUtils.equals(course.courseType, "1") || TextUtils.equals(
                    course.courseType,
                    "7"
                ) || TextUtils.equals(course.courseType, "6")
            ) {
                ARouter.getInstance()
                    .build("/course/play")
                    .withInt("course_id", course.id.toInt())
                    .navigation()
            } else {
                val h5Params = H5Params(CourseConstants.COURSE_DETAIL_H5 + course.id, "课程详情")
                NewH5Activity.start(mContext, h5Params)
            }

            ActionCountUtils.count(CourseBIConstants.CourseListEvent.POSITION_COURSE_LIST_XXX_CLICK + course.id + "_click")
        }


        if (!TextUtils.isEmpty(course.applyFee)) {
            if (course.applyFee.contains(".")) {
                tv_price.text = course.applyFee.split(".")[0]
                tv_price_decimal.text = "." + course.applyFee.split(".")[1]
            } else {
                tv_price.text = course.applyFee
                tv_price_decimal.text = ".00"
            }
        }

        if (TextUtils.equals("1", course.isPromotion) || TextUtils.equals(
                "3",
                course.isPromotion
            )
        ) {
            tv_cu_xiao.visibility = View.VISIBLE
            if (TextUtils.equals("1", course.isPromotion)) {
                if (course.promotionApplyFee.contains(".")) {
                    tv_price.text = course.promotionApplyFee.split(".")[0]
                    tv_price_decimal.text = "." + course.promotionApplyFee.split(".")[1]
                } else {
                    tv_price.text = course.promotionApplyFee
                    tv_price_decimal.text = ".00"
                }
            }
        } else {
            tv_cu_xiao.visibility = View.GONE
        }

        if (course.isBuy) {
            tv_view_course.visibility = View.VISIBLE
            if (TextUtils.equals(course.courseType, "1") || TextUtils.equals(
                    course.courseType,
                    "7"
                ) || TextUtils.equals(course.courseType, "6")
            ) {
                tv_view_course.text = "立即听课"
            } else {
                tv_view_course.text = "查看课程"
            }


            tv_original_price.visibility = View.GONE
            tv_price_si.visibility = View.GONE
            tv_price.visibility = View.GONE
            tv_price_decimal.visibility = View.GONE
        } else {
            tv_view_course.visibility = View.GONE

            tv_original_price.visibility = View.VISIBLE
            tv_price_si.visibility = View.VISIBLE
            tv_price.visibility = View.VISIBLE
            tv_price_decimal.visibility = View.VISIBLE


            if (TextUtils.isEmpty(course.originalApplyFee) || TextUtils.equals(
                    course.originalApplyFee,
                    "0"
                ) || TextUtils.equals(
                    course.originalApplyFee,
                    "0.0"
                ) || TextUtils.equals(course.originalApplyFee, "0.00")
            ) {
                tv_original_price.visibility = View.GONE
            } else {
                tv_original_price.visibility = View.VISIBLE
            }
            tv_original_price.text = "¥" + course.originalApplyFee
            tv_original_price.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG

        }
    }


    fun setGuideData(pic: String, location: String) {
        view_bottom_line.visibility = View.INVISIBLE
        iv_guide_image.visibility = View.VISIBLE

        GlideApp.with(mContext)
            .load(pic)
            .into(iv_guide_image)

        iv_guide_image.setOnClickListener {
            provide(IConsultantService::class.java).jumpConsultAssistant(
                mContext as Activity,
                location.toInt()
            )
        }
    }


    fun setGuideGone(){
        iv_guide_image.visibility = View.GONE
    }


    fun isGuideVisible(): Boolean {
        return iv_guide_image.visibility == View.VISIBLE
    }


    private fun playMedia() {
        if (PlayerFloatHelper.isShow(mContext)) {
            PlayerFloatHelper.hide()
            PlayerFloatHelper.removeView(mContext)
            AudioPlayer.get().stopPlayer()
        } else {
            PlayerFloatHelper.removeView(mContext)
        }

        val music = Music()
        music.title = course.title
        music.artist = doctorName
        music.coverPath = if (!TextUtils.isEmpty(course.image)) course.image else course.pic
        PlayerFloatHelper.isCanClick = false


        if (course.demoType == 1) {
            music.path = course.demoFile

            val hashMap = HashMap<String, String>()
            PlayerFloatHelper.playTempData.clear()
            hashMap["course_id"] = course.id.toString()
            AudioPlayer.get().singlePlay(music)
            PlayerFloatHelper.show(
                mContext,
                playTypeEnum = PlayTypeEnum.PLAY_TYPE_COURSE,
                playData = hashMap
            )
            VideoFloatHelper.dismissFloat(mContext as Activity)
        }
        if (course.demoType == 2) {
            VideoFloatHelper.setVideoInfo(
                course.id.toString(),
                course.demoFile,
                false
            )
            checkPermission()

            if (PlayerFloatHelper.isShow(mContext)) {
                PlayerFloatHelper.hide()
                PlayerFloatHelper.removeView(mContext)
                AudioPlayer.get().stopPlayer()
            }
        }


        if (statusListener == null) {
            statusListener = object : PlayerFloatView.FloatViewPlayListener {
                override fun onStartClick() {
                }

                override fun onPlayFinish() {
                    PlayerFloatHelper.hide()
                    AudioPlayer.get().stopPlayer()
                }

                override fun onPauseClick() {
                }

            }
            PlayerFloatHelper.addClickListener(statusListener as PlayerFloatView.FloatViewPlayListener)
        }
    }


    fun setBottomLineGone() {
        view_bottom_line.visibility = View.INVISIBLE
    }

    fun setBottomLineVisible() {
        view_bottom_line.visibility = View.VISIBLE
    }

    fun hideListenerButton() {
        tv_view_course.visibility = View.GONE
    }

    /**
     * 检测浮窗权限是否开启，若没有给与申请提示框（非必须，申请依旧是EasyFloat内部内保进行）
     */
    private fun checkPermission() {
        if (PermissionUtils.checkPermission(mContext)) {

            VideoFloatHelper.showVideoFloat(mContext as Activity)
        } else {
            AlertDialog.Builder(mContext)
                .setMessage("使用浮窗功能，需要您授权悬浮窗权限。")
                .setPositiveButton("去开启") { _, _ ->
                    VideoFloatHelper.showVideoFloat(mContext as Activity)
                }
                .setNegativeButton("取消") { _, _ ->
                    ToastUtil.toastLong(
                        mContext,
                        "App正常工作需要内部存储使用权限，请开启"
                    )
                }
                .show()
        }
    }
}