package com.yzx.ebrand.fragment

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.bumptech.glide.Glide
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.wgw.photo.preview.PhotoPreview
import com.yzx.ebrand.R
import com.yzx.ebrand.activity.LoginActivity
import com.yzx.ebrand.fragment.base.BaseFragment
import com.yzx.ebrand.model.*
import com.yzx.ebrand.presenter.ClassBrandPresenter
import com.yzx.ebrand.presenter.ClassBrandView
import com.yzx.ebrand.utils.getImgUrl
import com.yzx.ebrand.utils.hideNavigationBar
import com.yzx.ebrand.utils.setSrc
import com.yzx.ebrand.utils.toTime
import com.yzx.ebrand.utils.zhCn
import kotlinx.android.synthetic.main.fragment_class_brand.*
import kotlinx.android.synthetic.main.layout_brand_active_info.*
import kotlinx.android.synthetic.main.layout_brand_class_info.*
import kotlinx.android.synthetic.main.layout_brand_image_info.*
import kotlinx.android.synthetic.main.layout_brand_tea_info.*
import kotlinx.android.synthetic.main.layout_brand_timetable_info.*
import kotlinx.android.synthetic.main.layout_class_active_item.view.*
import kotlinx.android.synthetic.main.layout_class_tea_item.view.*
import kotlinx.android.synthetic.main.layout_time_table_item.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.support.v4.act
import org.jetbrains.anko.support.v4.ctx

class ClassBrandFragment : BaseFragment<ClassBrandPresenter>(), ClassBrandView {

    companion object {

        val CAMER_REQUEST_CODE = 0x01

        @JvmStatic
        fun getNewInstance() =
            ClassBrandFragment()
    }

    private var headClassList: MutableList<HeadClassInfo> = mutableListOf()
    private var imgIndex = 0
    private var imgLoopRunnable: Runnable? = null
    private var currClass = HeadClassInfo()
    private val styleImgList: MutableList<ClassStylePic> = mutableListOf()
    private val styleImgUrlList: MutableList<String> = mutableListOf()

    private val mClassInfoLoopTime = 10 * 60 * 1000L
    private val mClassInfoHandler = Handler(Looper.getMainLooper())
    private val mClassInfoRunnable = object : Runnable {
        override fun run() {
            mClassInfoHandler.removeCallbacks(this)
            mClassInfoHandler.postDelayed(this, mClassInfoLoopTime)
            getClassInfo()
        }
    }

    private val mTimeHandler = Handler(Looper.getMainLooper())
    private val timeRunnable = object : Runnable {
        override fun run() {
            mTimeHandler.removeCallbacks(this)
            mTimeHandler.postDelayed(this, 6000)
            loopImg(this@ClassBrandFragment.styleImgList)
        }
    }

    override val inflateId: Int
        get() = R.layout.fragment_class_brand

    private var clickCount = 0

    override fun initView() {
        btnRefresh.setOnClickListener {
            clickCount++
            if (clickCount >= 2) {
                clickCount = 0
                initData()
            }
        }
        userNameLayout.setOnClickListener {
            val tipDialog = QMUIDialog.MessageDialogBuilder(activity)
                .setTitle("温馨提示")
                .setMessage("是否确定退出？")
                .addAction("暂不退出") { dialog, index ->
                    dialog.dismiss()
                }
                .addAction("立即退出") { dialog, index ->
                    dialog.dismiss()
                    User.clearUserInfo()
                    LoginActivity.active(act)
                    activity?.apply {
                        ActivityUtils.finishActivity(this)
                    }
                }
                .create()
            tipDialog.show()
            tipDialog.hideNavigationBar()
        }

        styleImg0.setOnClickListener {
            LogUtils.d("styleImg0Click", this.imgIndex)
            previewImg(0, it)
        }
        styleImg1.setOnClickListener {
            previewImg(1, it)
        }
        styleImg2.setOnClickListener {
            previewImg(2, it)
        }
        styleImg3.setOnClickListener {
            previewImg(3, it)
        }

        classNameLayout.setOnClickListener {
            val builder = QMUIDialog.MenuDialogBuilder(ctx)
            headClassList.forEach {
                builder.addItem(
                    "${it.grade_name}${it.class_name}"
                ) { dialog, which ->
                    LogUtils.d("itemClick", which)
                    currClass = headClassList[which]
                    showLoading("加载中...")
                    getOtherData()
                    dialog.dismiss()
                    classNameTv.text = "${currClass.grade_name}${currClass.class_name}"
                    SPUtils.getInstance().put("local_class_id", currClass.class_id)
                }
            }
            builder.show()
        }
//        mViewPager = find(R.id.bottomBannerView)
//        mViewPager.setLifecycleRegistry(lifecycle)
//            .setAdapter(BannerAdapter())
//            .setPageStyle(PageStyle.MULTI_PAGE_SCALE,1f)
//            .setInterval(6000)
//            .setScrollDuration(500)
//            .setRevealWidth(dip(300))
//            .setPageMargin(dip(20))
//            .create()
    }

    private fun previewImg(imgIndex: Int, view: View) {
//        val url =
//            styleImgList[this.imgIndex + imgIndex].identity.getImgUrl(styleImgList[this.imgIndex + imgIndex].picture_id)
        val url = view.getTag(R.id.image_src_tag).toString()
        LogUtils.d("previewImg", imgIndex)
        val photoPreview = PhotoPreview.with(this)
            .sources(styleImgUrlList)
            .onDismissListener {
                if (this.styleImgList.size > 4) {
                    styleImgBox.postDelayed(imgLoopRunnable, 6000)
                }
            }
            .build()
        photoPreview.setDefaultShowPosition(styleImgUrlList.indexOf(url))
        photoPreview.show(view)
        if (imgLoopRunnable != null && this.styleImgList.size > 4) {
            styleImgBox.removeCallbacks(imgLoopRunnable)
        }

    }

    override fun initData() {
        PhotoPreview.setGlobalImageLoader { position, source, imageView ->
            Glide.with(imageView)
                .load(source.toString())
                .into(imageView)
        }
        setClassInfo()
        mPresenter?.getHeadClassList()

    }

    private fun getClassInfo(){
        mPresenter?.getClassInfo(currClass.class_id.toString())
        LogUtils.d("请求时间",TimeUtils.getNowString())
    }

    private fun getOtherData() {
        mPresenter?.getImageInfo(currClass.class_id.toString())
        unitName.postDelayed({
            mPresenter?.getTeaList(currClass.class_id.toString())
            mPresenter?.getTimeTable(currClass.class_id.toString())
            mPresenter?.getActiveInfo(currClass.class_id.toString())
        }, 300)
    }

    override fun onHeadClassSuccess(list: MutableList<HeadClassInfo>) {
        if (list.size > 0) {
            LogUtils.d("有班级")
            val localClassId = SPUtils.getInstance().getInt("local_class_id", 0)
            currClass = if (currClass.class_id > 0) {
                list.find { it.class_id == currClass.class_id } ?: list[0]
            } else if (localClassId > 0) {
                list.find { it.class_id == localClassId } ?: list[0]
            } else {
                list[0]
            }

            headClassList = list
            getOtherData()
            mClassInfoHandler.removeCallbacks(mClassInfoRunnable)
            getClassInfo()
            mClassInfoHandler.postDelayed(mClassInfoRunnable,mClassInfoLoopTime)
            classNameTv.text = "${currClass.grade_name}${currClass.class_name}"

            classSwIcon.visibility = if (list.size > 1) {
                View.VISIBLE
            } else {
                View.GONE
            }
        } else {
            classSwIcon.visibility = View.GONE
            val tipDialog = QMUIDialog.MessageDialogBuilder(activity)
                .setTitle("温馨提示")
                .setMessage("您没有班主任身份，无法使用电子班牌！")
                .addAction("知道了") { dialog, index ->
                    dialog.dismiss()
                    User.clearUserInfo()
                    LoginActivity.active(act)
                    activity?.apply {
                        ActivityUtils.finishActivity(this)
                    }
                }
                .addAction("立即退出") { dialog, index ->
                    dialog.dismiss()
                    User.clearUserInfo()
                    LoginActivity.active(act)
                    activity?.apply {
                        ActivityUtils.finishActivity(this)
                    }
                }
                .create()
            tipDialog.show()
            tipDialog.hideNavigationBar()
        }
    }

    private fun setClassInfo() {
        val user = User.getUser();
        unitName.text = user.unit_name
        loginUserNameTv.text = user.user_name
    }


    override fun onAvatarSuccess(identity: String, head_portrait: String) {
        headImgView?.setSrc(identity, head_portrait)
    }

    override fun onClassInfoSuccess(info: CBClassInfo) {
        classTeaNameTv?.let {
            classTeaNameTv.text = info.class_teacher.user_name
            classStuCountTv.text = "本班人数：${info.class_student_num}人"
            faceCountTv.text = "刷脸入校：${info.brushed_face_num}人"
            noFaceCountTv.text = "未刷脸：${info.unbrushed_face_num}人"
            leaveCountTv.text = "请假：${info.leave_num}人"

            mClassInfoHandler.removeCallbacks(mClassInfoRunnable)
            mClassInfoHandler.postDelayed(mClassInfoRunnable,mClassInfoLoopTime)
        }
    }

    override fun onTeaListSuccess(list: MutableList<ClassTeaInfo>) {
        classTeaListLL.removeAllViews()
        list.forEachIndexed { index, it ->
            val itemView =
                LayoutInflater.from(activity).inflate(R.layout.layout_class_tea_item, null, false)
            if (index % 2 == 0) {
                itemView.setBackgroundColor(Color.parseColor("#5682ff"))
            } else {
                itemView.setBackgroundColor(Color.parseColor("#005682ff"))
            }
            itemView.teaSubjectNameTv.text = it.subject_name
            val userName = if (it.type == 1) {
                "${it.user_name}（班主任）"
            } else {
                it.user_name
            }
            itemView.teaUserNameTv.text = userName
            classTeaListLL.addView(itemView)
        }
        if (list.size == 0) {
            val emptyView =
                LayoutInflater.from(activity).inflate(R.layout.layout_class_empty, null, false)
            classTeaListLL.addView(emptyView)
        }
    }

    override fun onTimeTableSuccess(list: MutableList<TimeTable>) {
        timeTableLL.removeAllViews()
        list.forEachIndexed { index, it ->
            val itemView =
                LayoutInflater.from(activity).inflate(R.layout.layout_time_table_item, null, false)
            if (index % 2 == 0) {
                itemView.setBackgroundColor(Color.parseColor("#33ffffff"))
            } else {
                itemView.setBackgroundColor(Color.parseColor("#00ffffff"))
            }
            itemView.lessonNoTv.text = it.lesson_name
            itemView.lessonNameTv.text = it.subject_name
            timeTableLL.addView(itemView)
        }
        if (list.size == 0) {
            val emptyView =
                LayoutInflater.from(activity).inflate(R.layout.layout_class_empty, null, false)
            timeTableLL.addView(emptyView)
        }
    }

    private fun previewActiveImg(item: ClassActiveInfo, view: View) {
        val list = item.getImgUrls()
        if (list.size <= 0) {
            this.showDialogToast("暂无可查看照片", icon = QMUITipDialog.Builder.ICON_TYPE_FAIL)
            return
        }
        val photoPreview = PhotoPreview.with(this)
            .sources(list)
            .onDismissListener {

            }
            .build()
        photoPreview.show(view)
    }

    private val mActiveList = mutableListOf<ClassActiveInfo>()
    override fun onActiveInfoSuccess(list: MutableList<ClassActiveInfo>) {
        classActiveLL.removeAllViews()
        mActiveList.clear()
        mActiveList.addAll(list)
        list.forEachIndexed { index, it ->
            val itemView =
                LayoutInflater.from(activity)
                    .inflate(R.layout.layout_class_active_item, null, false)
            itemView.activeContentTv.text = it.getNewContent()
            itemView.addTimeTv.text = it.add_time.toTime()
            itemView.addUserTv.text = it.user_name
            itemView.setTag(R.id.row_index_key, index)
            itemView.setOnClickListener { item ->
                previewActiveImg(it, item)
            }
            classActiveLL.addView(itemView)
        }
        if (list.size == 0) {
            val emptyView =
                LayoutInflater.from(activity).inflate(R.layout.layout_class_empty, null, false)
            classActiveLL.addView(emptyView)
        }
    }

    override fun onResume() {
        setClassInfo()
        super.onResume()
    }

    override fun onDestroy() {
        mTimeHandler.removeCallbacks(timeRunnable)
        mClassInfoHandler.removeCallbacks(mClassInfoRunnable)
        super.onDestroy()
    }

    override fun onImageInfoSuccess(list: MutableList<ClassStylePic>) {
        hideLoading()
        if (list.size > 0) {
            imgEmpty.visibility = View.GONE
            styleImgBox.visibility = View.VISIBLE

//            mViewPager.refreshData(list)
        }
        this.imgIndex = 0
        this.styleImgList.clear()
        this.styleImgList.addAll(list)
        styleImgUrlList.clear()
        list.forEach {
            styleImgUrlList.add(it.identity.getImgUrl(it.picture_id))
        }
        when {
            list.size == 0 -> {
                imgEmpty.visibility = View.VISIBLE
                styleImgBox.visibility = View.GONE
            }

            list.size == 1 -> {
                styleImg0.setSrc(list[0].identity, list[0].picture_id)
                styleImg0.visibility = View.VISIBLE
                styleImgLL.visibility = View.GONE
                styleImg1.visibility = View.GONE
                styleImg2.visibility = View.GONE
                styleImg3.visibility = View.GONE
            }

            list.size == 2 -> {
                styleImg0.setSrc(list[0].identity, list[0].picture_id)
                styleImg1.setSrc(list[1].identity, list[1].picture_id)
                styleImg0.visibility = View.VISIBLE
                styleImgLL.visibility = View.VISIBLE
                styleImg1.visibility = View.VISIBLE
                styleImg2.visibility = View.GONE
                styleImg3.visibility = View.GONE
            }

            list.size == 3 -> {
                styleImg0.setSrc(list[0].identity, list[0].picture_id)
                styleImg1.setSrc(list[1].identity, list[1].picture_id)
                styleImg2.setSrc(list[2].identity, list[2].picture_id)
                styleImg0.visibility = View.VISIBLE
                styleImgLL.visibility = View.VISIBLE
                styleImg1.visibility = View.VISIBLE
                styleImg2.visibility = View.VISIBLE
                styleImg3.visibility = View.GONE
            }

            list.size >= 4 -> {
                styleImg0.setSrc(list[0].identity, list[0].picture_id)
                styleImg1.setSrc(list[1].identity, list[1].picture_id)
                styleImg2.setSrc(list[2].identity, list[2].picture_id)
                styleImg3.setSrc(list[3].identity, list[3].picture_id)
                styleImg0.visibility = View.VISIBLE
                styleImgLL.visibility = View.VISIBLE
                styleImg1.visibility = View.VISIBLE
                styleImg2.visibility = View.VISIBLE
                styleImg3.visibility = View.VISIBLE
            }
        }

        if (list.size > 4) {
            this.imgIndex = 4
//            styleImgBox.removeCallbacks(null)
//            this.loopImg(list)
            mTimeHandler.removeCallbacks(timeRunnable)
            mTimeHandler.postDelayed(timeRunnable,6000)
        }
    }

    private fun groupingList() {
        val topList = mutableListOf<ClassStylePic>()
        val bottomList = mutableListOf<ClassStylePic>()
        styleImgList.forEachIndexed { index, classStylePic ->
            if (index % 4 == 0) {
                topList.add(classStylePic)
            } else {
                bottomList.add(classStylePic)
            }
        }
    }



    private fun loopImg(list: MutableList<ClassStylePic>) {
        if (this.imgIndex + 3 > list.size - 1) {
            this.imgIndex = list.size - 1 - 3
        }
        styleImg0?.let {
            styleImg0.setSrc(list[this.imgIndex + 0].identity, list[this.imgIndex + 0].picture_id)
            styleImg1.setSrc(list[this.imgIndex + 1].identity, list[this.imgIndex + 1].picture_id)
            styleImg2.setSrc(list[this.imgIndex + 2].identity, list[this.imgIndex + 2].picture_id)
            styleImg3.setSrc(list[this.imgIndex + 3].identity, list[this.imgIndex + 3].picture_id)
            this.imgIndex += 4
            if (this.imgIndex > list.size - 1) {
                this.imgIndex = 0
            }
            styleImg0.visibility = View.VISIBLE
            styleImgLL.visibility = View.VISIBLE
            styleImg1.visibility = View.VISIBLE
            styleImg2.visibility = View.VISIBLE
            styleImg3.visibility = View.VISIBLE
        }

    }

    override fun initPresenter(): ClassBrandPresenter = ClassBrandPresenter(this)

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }


    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    //接收消息
    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: TimeShow) {
//        2023年7月31日17:58:37 星期一
        val time =
            TimeUtils.getNowString(TimeUtils.getSafeDateFormat("yyyy年MM月dd日 HH:mm:ss").zhCn())
        timeView.text = "$time ${event.week}"

        if (event.min == "30") {
            this.getOtherData()
        }
    }
}