package com.gh.gamecenter.forum.moderator

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.gh.common.dialog.ApplyModeratorDialogFragment
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.ShellActivity
import com.gh.gamecenter.common.avoidcallback.AvoidOnResultManager
import com.gh.gamecenter.common.avoidcallback.Callback
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.core.utils.ClickUtils
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.FragmentApplyModeratorBinding
import com.gh.gamecenter.entity.ApplyModeratorStatusEntity
import com.gh.gamecenter.entity.ApplyModeratorTaskEntity
import com.gh.gamecenter.forum.detail.ForumDetailActivity
import com.gh.gamecenter.login.user.UserManager
import com.lightgame.utils.AppManager
import com.lightgame.utils.Utils


class ApplyModeratorFragment : ToolbarFragment() {

    private var mBinding: FragmentApplyModeratorBinding? = null
    private var mViewModel: ApplyModeratorViewModel? = null
    private var mAdapter: ModeratorTaskAdapter? = null
    private var mDataList = ArrayList<ApplyModeratorTaskEntity>()
    private var mBbsId = ""
    private var mStatus = ApplyModeratorStatusEntity()

    override fun getInflatedLayout() = FragmentApplyModeratorBinding
        .inflate(layoutInflater, null, false)
        .apply { mBinding = this }
        .root

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBbsId = arguments?.getString(EntranceConsts.KEY_BBS_ID) ?: ""
        mStatus = arguments?.getParcelable("status") ?: ApplyModeratorStatusEntity()
        val factory = ApplyModeratorViewModel.Factory(mBbsId)
        mDataList = getModeratorTaskList()
        mViewModel = viewModelProvider(factory)
        mAdapter = ModeratorTaskAdapter(requireContext())
        mBinding?.run {
            statusBar.layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                DisplayUtils.getStatusBarHeight(requireActivity().resources)
            )
            toolbar.setNavigationOnClickListener {
                requireActivity().finish()
            }
            taskRv.layoutManager = LinearLayoutManager(requireContext())
            taskRv.adapter = mAdapter
            groupTv.setOnClickListener {
                NewLogUtils.logApplyModeratorFApplyOrQQClick("click_QQ_number", UserManager.getInstance().userId)
                DirectUtils.directToQqGroup(
                    requireContext(),
                    mStatus.qqGroupKey
                )
            }
            groupTv.text = mStatus.qqGroup
        }
        mAdapter?.setListData(mDataList)
        mViewModel?.statusEntity?.observe(this, Observer {
            it?.let {
                checkStatus(it)
            }
        })
        if (mStatus.status == "todo") {
            changeToAudit()
        }
    }

    private fun getModeratorTaskList(): ArrayList<ApplyModeratorTaskEntity> {
        return arrayListOf(
            ApplyModeratorTaskEntity().apply {
                taskName = "通过礼仪考试"
                taskIcon = R.drawable.ic_moderator_task_etiquette
                taskAction = View.OnClickListener {
                    val taskState = if (finishedTask) "已完成" else "未完成"
                    NewLogUtils.logApplyModeratorFinishClick(taskName, taskState)
                    if (!finishedTask) {
                        DirectUtils.directToRegulationTestPage(requireContext())
                    }
                }
                finishedTask = mStatus.condition.etiquette
            },

            ApplyModeratorTaskEntity().apply {
                taskName = "完成实名认证"
                taskIcon = R.drawable.ic_moderator_task_id_card
                taskAction = View.OnClickListener {
                    val taskState = if (finishedTask) "已完成" else "未完成"
                    NewLogUtils.logApplyModeratorFinishClick(taskName, taskState)
                    if (!finishedTask) {
                        val currentActivity = AppManager.getInstance().currentActivity()
                        AvoidOnResultManager.getInstance(currentActivity as AppCompatActivity)
                            .startForResult(
                                ShellActivity.getIntent(requireContext(), ShellActivity.Type.REAL_NAME_INFO, null),
                                object :
                                    Callback {
                                    override fun onActivityResult(resultCode: Int, data: Intent?) {
                                        Utils.log(resultCode)
                                    }
                                })
                    }
                }
                finishedTask = mStatus.condition.idCard
            },

            ApplyModeratorTaskEntity().apply {
                taskName = "论坛活跃度"
                taskIcon = R.drawable.ic_moderator_task_activity
                taskDescription = "活跃度=发帖数量+回帖数量+回复数量≥20"
                taskAction = View.OnClickListener {
                    val taskState = if (finishedTask) "已完成" else "未完成"
                    NewLogUtils.logApplyModeratorFinishClick(taskName, taskState)
                    if (!finishedTask) {
                        startActivity(
                            ForumDetailActivity.getIntent(
                                requireContext(),
                                mBbsId,
                                "版主申请"
                            )
                        )
                    }
                }
                finishedTask = mStatus.condition.activity
            },

            ApplyModeratorTaskEntity().apply {
                taskName = "论坛精品帖≥2"
                taskDescription = "查看如何申请精品贴>>"
                taskIcon = R.drawable.ic_moderator_task_choiceness
                taskAction = View.OnClickListener {
                    val taskState = if (finishedTask) "已完成" else "未完成"
                    NewLogUtils.logApplyModeratorFinishClick(taskName, taskState)
                    if (!finishedTask) {
                        startActivity(
                            ForumDetailActivity.getIntent(
                                requireContext(),
                                mBbsId,
                                "版主申请"
                            )
                        )
                    }
                }
                taskDesAction = View.OnClickListener {
                    if (mStatus.guide.type.isNullOrBlank()) {
                        ToastUtils.toast("该内容不存在")
                        return@OnClickListener
                    }
                    DirectUtils.directToLinkPage(
                        requireContext(),
                        mStatus.guide,
                        "版主申请",
                        "申请论坛精品贴"
                    )
                }
                finishedTask = mStatus.condition.choiceness
            }
        )
    }

    private fun checkStatus(status: ApplyModeratorStatusEntity) {
        if (mDataList.size > 0) {
            if (status.condition.etiquette) {
                mDataList.firstOrNull()?.finishedTask = true
                mAdapter?.notifyItemChanged(0)
            }
            if (status.condition.idCard) {
                mDataList.getOrNull(1)?.finishedTask = true
                mAdapter?.notifyItemChanged(1)
            }
            if (status.condition.activity) {
                mDataList.getOrNull(2)?.finishedTask = true
                mAdapter?.notifyItemChanged(2)
            }
            if (status.condition.choiceness) {
                mDataList.getOrNull(3)?.finishedTask = true
                mAdapter?.notifyItemChanged(3)
            }
            var allFinished = true
            for (item in mDataList) {
                if (!item.finishedTask) {
                    allFinished = false
                }
            }
            mBinding?.applyTv?.alpha = if (allFinished) 1F else 0.4F
            val listener = View.OnClickListener {
                if (!ClickUtils.isFastDoubleClick(R.id.applyTv)) {
                    mBinding?.applyTv?.setOnClickListener(null)
                    NewLogUtils.logApplyModeratorFApplyOrQQClick("click_apply", UserManager.getInstance().userId)
                    mViewModel?.applyModerator({
                        ApplyModeratorDialogFragment.show(
                            requireActivity() as AppCompatActivity,
                            mStatus.qqGroup,
                            mStatus.qqGroupKey,
                            tag ?: ""
                        )
                    }, {
                        Utils.toast(requireContext(), com.gh.gamecenter.feature.R.string.loading_failed_hint)
                        mViewModel?.getModeratorsApplyStatus()
                    })
                }
            }
            mBinding?.applyTv?.setOnClickListener(if (allFinished) listener else null)
        }
        if (status.status == "todo") {
            changeToAudit()
        }
    }

    private fun getCallBack(): () -> Unit {
        return {
            changeToAudit()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == ApplyModeratorDialogFragment.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            getCallBack().invoke()
        }
    }

    private fun changeToAudit() {
        mBinding?.run {
            applyTv.text = "审核中"
            applyTv.alpha = 0.4F
            applyTv.setOnClickListener(null)
            addGroupContainer.visibility = View.VISIBLE
        }
    }

    override fun onResume() {
        super.onResume()
        mViewModel?.getModeratorsApplyStatus()
    }

    override fun getLayoutId(): Int = R.layout.fragment_apply_moderator

}