package com.dlc.exam.ui.me

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dlc.exam.ExamApp
import com.dlc.exam.R
import com.dlc.exam.common.ExamType
import com.dlc.exam.common.ViolationType
import com.dlc.exam.databinding.ActivityPersonalCenterBinding
import com.dlc.exam.ui.MainActivity
import com.dlc.exam.ui.common.BaseCountDownActivity
import com.dlc.exam.ui.common.DateChooseDialog
import com.dlc.exam.ui.exam.ExamActivity
import com.dlc.exam.ui.exam.SafetyExamHomeActivity
import com.dlc.exam.ui.learn.SafetyLearnActivity
import com.dlc.exam.ui.mock.SelectedMockTypeActivity
import com.dlc.exam.ui.widget.ListPageView
import com.dlc.exam.ui.widget.TitleBar
import com.rc.core.log.RcLog
import com.rc.core.ui.widget.decoration.GridSpacingItemDecoration
import com.rc.core.util.DeviceUtils
import com.rc.httpcore.HttpClient
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.ViolationReq
import com.rc.httpcore.vo.response.UserInfo
import com.rc.httpcore.vo.response.ViolationBean

/**
 * 个人中心
 *
 * @author ReiChin_
 */
class PersonalCenterActivity : BaseCountDownActivity<ActivityPersonalCenterBinding>(),
    TitleBar.TitleListener {

    private val mBreachContentAdapter by lazy { BreachContentAdapter() }

    override fun createViewBinding() =
        ActivityPersonalCenterBinding.inflate(LayoutInflater.from(this))

    private var mCurrentPage = ListPageView.FIRST_PAGE

    private lateinit var mUserStatus: String // 用户状态, 1:正常 2:负面清单 3:黑名单

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.setUsername(ExamApp.sLearnLoginVo?.userName)

        // 违规处理
        viewBinding.breachContent.layoutManager = LinearLayoutManager(this)
        mBreachContentAdapter.setHandListener { type ->
            dispatchViolationHand(type)
        }
        mBreachContentAdapter.loadMoreModule.setOnLoadMoreListener {
            val dataSize = mBreachContentAdapter.data.size
            if (dataSize < ListPageView.PAGE_SIZE) {
                mBreachContentAdapter.loadMoreModule.loadMoreEnd(false)
            } else {
                if (dataSize % ListPageView.PAGE_SIZE != 0) {
                    mBreachContentAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mCurrentPage++
                    callQueryApi()
                }
            }
        }
        mBreachContentAdapter.loadMoreModule.isAutoLoadMore = true
        // 当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        mBreachContentAdapter.loadMoreModule.isEnableLoadMoreIfNotFullPage = true
        mBreachContentAdapter.animationEnable = true
        mBreachContentAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInBottom)
        viewBinding.breachContent.adapter = mBreachContentAdapter
    }

    private fun dispatchViolationHand(type: String?) {
        when (type) {
            ViolationType.LEARN.type -> {
                // 点击去学习按钮，应该跳转到学习页面，并根据当前账号的状态（负面清单，黑名单）自动选择学习类型（负面清单，黑名单）
                val intent = Intent(this, SafetyLearnActivity::class.java)
                decodeExamType()?.let { intent.putExtra("exam_type", it) }
                startActivity(intent)
            }
            ViolationType.TEST.type -> {
                startActivity(Intent(this, SelectedMockTypeActivity::class.java))
            }
            ViolationType.EXAM.type -> {
                // 点击去考试，根据当前账号状态（负面清单，黑名单）自动跳转到相应的考试界面（负面清单，黑名单）
                val examType = decodeExamType()
                if (null == examType) {
                    startActivity(Intent(this, SafetyExamHomeActivity::class.java))
                } else {
                    val intent = Intent(this, ExamActivity::class.java)
                    intent.putExtra("exam_type", examType)
                    startActivity(intent)
                }
            }
        }
    }

    private fun decodeExamType(): String? {
        // 用户状态, 1:正常 2:负面清单 3:黑名单
        return when (mUserStatus) {
            "2" -> ExamType.NEGATIVE.type
            "3" -> ExamType.BLACK_LIST.type
            else -> null
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initListener() {
        super.initListener()
        // 选择状态
        viewBinding.status.setOnClickListener {
            val items = arrayOf("全部状态", "已处理", "未处理")
            AlertDialog.Builder(this)
                .setItems(items) { _, which ->
                    viewBinding.status.text = items[which]
                }.show()
        }
        // 选择时间段
        viewBinding.timeSlot.setOnClickListener {
            val data = viewBinding.timeSlot.text.split(" 至 ")
            val sDate = if (data.size == 2) data[0] else ""
            val eDate = if (data.size == 2) data[1] else ""
            DateChooseDialog(this, sDate, eDate) { startDate, endDate ->
                viewBinding.timeSlot.text = "$startDate 至 $endDate"
                true
            }.show()
        }
        // 查询
        viewBinding.query.setOnClickListener {
            mCurrentPage = ListPageView.FIRST_PAGE
            callQueryApi(true)
        }
        // 重置
        viewBinding.reset.setOnClickListener {
            viewBinding.status.text = null
            viewBinding.timeSlot.text = null
            mCurrentPage = ListPageView.FIRST_PAGE
            callQueryApi(true)
        }
    }


    private fun callQueryApi(loading: Boolean = false) {
        if (loading) showLoading("查询中...")
        val data = viewBinding.timeSlot.text.split(" 至 ")
        val sDate = if (data.size == 2) data[0] else ""
        val eDate = if (data.size == 2) data[1] else ""
        val param = ViolationReq().apply {
            pageNum = mCurrentPage
            pageSize = ListPageView.PAGE_SIZE
            statTime = sDate
            endTime = eDate
            overStatus = encodeStatus()
        }
        val disposable = ApiRepository.queryViolationList(param)
            .subscribe({ response ->
                dismissLoading()
                dispatchLoadDataSuccess(response?.toMutableList())
            }, { throwable ->
                dismissLoading()
                dispatchLoadDataFailure(throwable)
            })
        addDisposable(disposable)
    }

    // 查询条件：状态：1:已完成，0:未完成，-1:全部
    private fun encodeStatus(): String {
        // val items = arrayOf("全部状态", "已处理", "未处理")
        return when (viewBinding.status.text.toString()) {
            "已处理" -> "1"
            "未处理" -> "0"
            else -> "-1"
        }
    }

    private fun dispatchLoadDataSuccess(data: List<ViolationBean>?) {
        if (isDestroyed) return

        if (ListPageView.FIRST_PAGE == mCurrentPage) {
            if (data.isNullOrEmpty()) {
                mBreachContentAdapter.setEmptyView(com.rc.core.R.layout.view_list_empty)
            }
            mBreachContentAdapter.setNewInstance(data?.toMutableList())
            mBreachContentAdapter.loadMoreModule.loadMoreComplete()
            if (null == data || data.size < ListPageView.PAGE_SIZE) {
                mBreachContentAdapter.loadMoreModule.loadMoreEnd(false)
            }
        } else {
            if (null == data || data.size < ListPageView.PAGE_SIZE) {
                if (null != data) {
                    mBreachContentAdapter.addData(data)
                }
                mBreachContentAdapter.loadMoreModule.loadMoreEnd(false)
            } else {
                mBreachContentAdapter.addData(data)
                mBreachContentAdapter.loadMoreModule.loadMoreComplete()
            }
        }
    }

    private fun dispatchLoadDataFailure(throwable: Throwable) {
        if (isDestroyed) return

        if (ListPageView.FIRST_PAGE == mCurrentPage) {
            mBreachContentAdapter.setEmptyView(com.rc.core.R.layout.view_list_empty)
        } else {
            mCurrentPage =
                if (mCurrentPage-- < ListPageView.FIRST_PAGE) ListPageView.FIRST_PAGE else mCurrentPage
            mBreachContentAdapter.loadMoreModule.loadMoreEnd(false)
        }
        throwable.printStackTrace()
        showNetError(throwable)
    }


    override fun initData() {
        callQueryUserInfoApi()
    }

    private fun callQueryUserInfoApi() {
        showLoading("加载中...")
        val disposable = ApiRepository.queryUserInfo()
            .subscribe({
                dismissLoading()
                mUserStatus = it?.status ?: ""
                updateUserInfoViews(it)
            }, { throwable ->
                dismissLoading()
                mUserStatus = ""
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    @SuppressLint("SetTextI18n")
    private fun updateUserInfoViews(data: UserInfo?) {
        data?.let {
            // 头像
            var url = ""
            if (it.avatar != null) {
                url = if (it.avatar.startsWith("http")) {
                    it.avatar
                } else {
                    HttpConfig.API_BASE_IMG_URL + it.avatar
                }
            }
            RcLog.info("====路径 $url")
            Glide.with(this)
//                .load(it.avatar)
                .load(url)
                .placeholder(R.mipmap.img_bg_jzz)
                .error(R.mipmap.img_def_person)
                .into(viewBinding.pPhoto)
            // 姓名
//            viewBinding.pName.text = it.userName
            viewBinding.pName.text = it.joinUserName
            // 标记 1:正常，2：负面清单,3,黑名单
            when (it.status) {
                "1" -> {
                    viewBinding.pTag.visibility = View.VISIBLE
                    viewBinding.pTag.text = "正常"
                    viewBinding.pTag.setBackgroundResource(R.drawable.shape_rect_round_3_solid_blue)
                    viewBinding.pTag.setTextColor(Color.WHITE)
                }
                "2" -> {
                    viewBinding.pTag.visibility = View.VISIBLE
                    viewBinding.pTag.text = "负面清单"
                    viewBinding.pTag.setBackgroundResource(R.drawable.shape_rect_round_3_solid_ffae01)
                    viewBinding.pTag.setTextColor(Color.WHITE)
                }
                "3" -> {
                    viewBinding.pTag.visibility = View.VISIBLE
                    viewBinding.pTag.text = "黑名单"
                    viewBinding.pTag.setBackgroundResource(R.drawable.shape_rect_round_3_solid_a2)
                    viewBinding.pTag.setTextColor(Color.parseColor("#333333"))
                }
                else -> viewBinding.pTag.visibility = View.GONE
            }
            viewBinding.collegeName.text = it.deptName
            viewBinding.violationCount.text = "违规次数：${it.violatioNum ?: "0"}"
//            viewBinding.negativeCount.text = "进入负面清单次数：${it.negativeListCount ?: "0"}"
            viewBinding.negativeCount.text = "进入负面清单次数：${it.negativeListNum ?: "0"}"
            viewBinding.blackListCount.text = "进入黑名单次数：${it.blackListNum ?: "0"}"
            viewBinding.learnDuration.text = "已学习时长：${it.studyLen ?: ""}"
            // 奖励分
            viewBinding.bonusScore.text = it.bonusPoints
            // 信用分
//            viewBinding.creditScore.text = it.totalPoints
            viewBinding.creditScore.text = it.creditScore
        }
    }

    override fun onResume() {
        super.onResume()
        mCurrentPage = ListPageView.FIRST_PAGE
        callQueryApi(true)
        callQueryUserInfoApi()
    }

    override fun onHomeViewClicked(view: View) {
        startActivity(Intent(this, MainActivity::class.java))
    }

    override fun onLogoutViewClicked(view: View) {
        callLogoutApi {
            showToast("已退出登录")

            ExamApp.sLearnLoginVo = null
            HttpClient.token = null

            startActivity(Intent(this, MainActivity::class.java))
        }
    }

    override fun onBackViewClicked(view: View) {
        finish()
    }

    override fun onUserViewClicked(view: View) {
    }

}

private class BreachContentAdapter :
    BaseQuickAdapter<ViolationBean, BaseViewHolder>(R.layout.item_breach_content),
    LoadMoreModule {

    private var _handListener: ((type: String?) -> Unit)? = null

    fun setHandListener(listener: (type: String?) -> Unit) {
        this._handListener = listener
    }

    override fun convert(holder: BaseViewHolder, item: ViolationBean) {
        holder.setText(R.id.position, "${holder.adapterPosition + 1}")
            .setText(R.id.breachTime, item.createTime)
            .setText(R.id.breachInfo, item.remake)

        holderBreachHandling(holder.getView(R.id.breachHandling), item.violationList)
    }

    private fun holderBreachHandling(recyclerView: RecyclerView, data: List<ViolationBean.Item>?) {
        val handlingAdapter = BreachHandlingAdapter(data?.toMutableList())
        handlingAdapter.addChildClickViewIds(R.id.action)
        handlingAdapter.setOnItemChildClickListener { _, _, position ->
            _handListener?.invoke(handlingAdapter.getItem(position).type)
        }
        recyclerView.layoutManager = GridLayoutManager(context, 2)
        if (recyclerView.itemDecorationCount == 0) {
            val decor = GridSpacingItemDecoration(
                2,
                DeviceUtils.dip2px(context, 30.0f),
                DeviceUtils.dip2px(context, 8.0f),
                false
            )
            recyclerView.addItemDecoration(decor)
        }
        recyclerView.adapter = handlingAdapter
        handlingAdapter.setEmptyView(com.rc.core.R.layout.view_list_empty)
    }

}

private class BreachHandlingAdapter(data: MutableList<ViolationBean.Item>?) :
    BaseQuickAdapter<ViolationBean.Item, BaseViewHolder>(R.layout.item_breach_handling, data) {

    override fun convert(holder: BaseViewHolder, item: ViolationBean.Item) {
        holder.setImageResource(R.id.icon, formatIconRes(item.type))
            .setText(R.id.info, item.content)
            .setGone(R.id.completed, "0" == item.status) // 0:未完成;1已完成
            .setGone(R.id.action, goneAction(item.type, item.status))
            .setText(R.id.action, formatActionText(item.type))
    }

    private fun formatActionText(type: String?): String {
        return when (type) {
            ViolationType.LEARN.type -> "去学习"
            ViolationType.TEST.type -> "去做题"
            ViolationType.EXAM.type -> "去考试"
            else -> ""
        }
    }

    private fun goneAction(type: String?, status: String?): Boolean {
        if (ViolationType.LEARN.type == type
            || ViolationType.TEST.type == type
            || ViolationType.EXAM.type == type
        ) {
            return "1" == status
        }
        return true
    }

    private fun formatIconRes(type: String?): Int {
        return when (type) {
            ViolationType.WARNING.type -> R.mipmap.icon_wgcl_wg
            ViolationType.INTERVIEW.type -> R.mipmap.icon_wgcl_yt
            ViolationType.LEARN.type -> R.mipmap.icon_wgcl_xxzx
            ViolationType.TEST.type -> R.mipmap.icon_wgcl_mnlx
            ViolationType.EXAM.type -> R.mipmap.icon_wgcl_fmqd
            else -> R.mipmap.icon_wgcl_wg
        }
    }

}