package com.gh.gamecenter.gamedetail.fuli.kaifu

import android.app.Dialog
import android.graphics.Paint
import android.os.Bundle
import android.view.*
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.entity.SuggestType
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.databinding.DialogServersCalendearDetailBinding
import com.gh.gamecenter.databinding.LayoutServersCalendarDetailListBinding
import com.gh.gamecenter.entity.CalendarEntity
import com.gh.gamecenter.feature.entity.ServerCalendarEntity
import com.gh.gamecenter.help.HelpAndFeedbackBridge
import com.gh.gamecenter.servers.add.AddKaiFuActivity
import com.google.android.material.bottomsheet.BottomSheetDialog
import java.text.SimpleDateFormat
import java.util.*

/**
 * 游戏开服-开服表详情弹窗
 */
class ServersCalendarDetailDialog : DialogFragment() {

    private lateinit var detailViewBinding: DialogServersCalendearDetailBinding

    private lateinit var listViewBinding: LayoutServersCalendarDetailListBinding

    private val titleFormat = SimpleDateFormat("MM-dd", Locale.CHINA)

    private val parentViewModel by activityViewModels<ServersCalendarViewModel>()

    private lateinit var viewModel: ServersCalendarDetailViewModel


    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return super.onCreateDialog(savedInstanceState).apply {
            window?.setWindowAnimations(com.gh.gamecenter.common.R.style.community_publication_animation)
            window?.setGravity(Gravity.BOTTOM)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        // 必须放在super.onCreate前面，因为子Fragment的onCreate方法也是在super.onCreate回调的时候调用
        // 如果放在super.onCreate之后，那么在页面重构时，子Fragment在onCreate方法引用通过viewModels方法获取parentViewModel将触发崩溃
        viewModel = viewModelProvider(
            ServersCalendarDetailViewModel.Factory(
                source = parentViewModel.calendarLiveData,
                year = requireArguments().getInt(EntranceConsts.KEY_CALENDAR_YEAR, 0),
                month = requireArguments().getInt(EntranceConsts.KEY_CALENDAR_MONTH, 0),
                day = requireArguments().getInt(EntranceConsts.KEY_CALENDAR_DAY, 0),
                showRemind = requireArguments().getBoolean(EntranceConsts.KEY_SHOW_REMIND, false)
            )
        )
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, com.gh.gamecenter.common.R.style.DialogWindowTransparent)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return DialogServersCalendearDetailBinding.inflate(inflater, container, false)
            .also {
                detailViewBinding = it.apply {
                    content.layoutResource = R.layout.layout_servers_calendar_detail_list
                    listViewBinding = LayoutServersCalendarDetailListBinding.bind(content.inflate())
                }
            }.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 在这里加这句代码，才能保证弹窗宽度占满屏幕
        // 如果在弹窗的Theme里面加<item name="android:windowIsFloating">false</item>，那么这句代码可以去掉
        dialog?.window?.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.WRAP_CONTENT
        )

        val isPartTime = parentViewModel.meEntity?.isPartTime == true

        listViewBinding.titleInclude.add.visibility = if (isPartTime) View.VISIBLE else View.GONE

        listViewBinding.titleInclude.remindTitle.visibility = if (viewModel.showRemind) View.VISIBLE else View.GONE

        detailViewBinding.close.setOnClickListener { dismissAllowingStateLoss() }

        detailViewBinding.feedback.paint.flags = Paint.UNDERLINE_TEXT_FLAG
        detailViewBinding.feedback.paint.isAntiAlias = true
        detailViewBinding.feedback.text = if (isPartTime) "新增" else "意见反馈"
        detailViewBinding.feedback.setOnClickListener {
            val calendarEntity = viewModel.calendarEntityLiveData.value ?: return@setOnClickListener
            if (isPartTime) {
                startActivityForResult(
                    AddKaiFuActivity.getIntent(
                        it.context,
                        parentViewModel.serverCalendarLiveData.value!!.last(),
                        parentViewModel.serverCalendarLiveData.value as ArrayList<ServerCalendarEntity>,
                        parentViewModel.game.id, calendarEntity.server.first().getTime() * 1000
                    ), ServersCalendarActivity.GAME_DETAIL_ADD_KAIFU_REQUEST
                )
            } else {
                showServersDetailReportDialog(calendarEntity)
                dismissAllowingStateLoss()
            }
        }

        val adapter = ServersCalendarDetailAdapter(this@ServersCalendarDetailDialog, viewModel, parentViewModel)
        listViewBinding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
        listViewBinding.recyclerView.adapter = adapter

        viewModel.calendarEntityLiveData.observe(viewLifecycleOwner) { calendarEntity ->
            calendarEntity?.let {
                val calendar = Calendar.getInstance().apply {
                    set(it.year, it.month - 1, it.day)
                }
                detailViewBinding.calendarHint.text = "${titleFormat.format(calendar.time)}详细开服"
                adapter.submitList(calendarEntity.server)
            }
        }
    }

    private fun showServersDetailReportDialog(calendarEntity: CalendarEntity) {
        val contentView =
            LayoutInflater.from(requireContext()).inflate(R.layout.dialog_servers_calendear_detail_report, null)
        val params = ViewGroup.LayoutParams(resources.displayMetrics.widthPixels, ViewGroup.LayoutParams.WRAP_CONTENT)
        val dialog = BottomSheetDialog(requireContext(), com.gh.gamecenter.common.R.style.DialogWindowTransparent)
        val window = dialog.window
        window?.setGravity(Gravity.BOTTOM)
        window?.setWindowAnimations(com.gh.gamecenter.common.R.style.community_publication_animation)
        dialog.setContentView(contentView, params)
        dialog.show()

        val recyclerView = contentView.findViewById<RecyclerView>(R.id.recycler_view)
        val adapter = ServersCalendarDetailReportAdapter(requireContext(), calendarEntity.server)
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        recyclerView.adapter = adapter

        contentView.findViewById<TextView>(R.id.submit).setOnClickListener {
            val builder = StringBuilder()
            val serverCalendarList = adapter.selectedServerCalendarList
            serverCalendarList.forEachIndexed { index, entity ->
                if (index != 0) builder.append("；")
                builder.append("${entity.getFormatTime("yyyy年MM月dd日")}开服信息有误：${entity.getNote()}")
            }
            HelpAndFeedbackBridge.startSuggestionActivity(
                it.context,
                SuggestType.GAME,
                "service",
                builder.toString()
            )
            dialog.dismiss()
        }

        contentView.findViewById<View>(R.id.close).setOnClickListener {
            dialog.dismiss()
        }
    }
}