package com.pan_american.android.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.DatePicker
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.pan_american.android.OASystem
import com.pan_american.android.R
import java.util.Calendar

abstract class BaseFragment<T: ViewBinding>: Fragment() {

    private lateinit var _binding: T

    protected val binding get() = _binding

    lateinit var popupWindow: PopupWindow

    private lateinit var selectorPopView: View

    //筛选列表组件
    lateinit var selector: RecyclerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        OASystem.needRefresh = false
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = getViewBinding(inflater, container, savedInstanceState)
        return binding.root
    }

    protected abstract fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?, bundle: Bundle?): T

    override fun onStart() {
        super.onStart()

        if (!OASystem.isUserInfoInit()) {
            requireActivity().packageManager.getLaunchIntentForPackage(requireActivity().packageName)?.let {
                return@let Intent.makeRestartActivityTask(it.component)
            }?.let {
                startActivity(it)
            }

            android.os.Process.killProcess(android.os.Process.myPid())
        }
    }

    open fun initViews() {}

    open fun initEvents() {}

    fun showMessage(str: String) {
        Toast.makeText(OASystem.context, str, Toast.LENGTH_SHORT).show()
    }

    /**
     * 弹出popWindow
     */
    fun showPopupWindow(block : () -> Unit) {

        //避免出现弹出PopupWindow时界面透明的问题
        requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)

        //点击隐藏软键盘
        val inputMethodManager = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (inputMethodManager.isActive) {
            inputMethodManager.hideSoftInputFromWindow(requireActivity().window.decorView.windowToken, 0)
        }

        popupWindow.apply {
            //设置背景黑暗度
            val layoutParams: WindowManager.LayoutParams = requireActivity().window.attributes
            layoutParams.alpha = 0.4f
            requireActivity().window.attributes = layoutParams

            //手势提示条适配
            isClippingEnabled = false
            //设置动画效果
            animationStyle = R.style.AnimationBottomPopup
            //设置聚焦，点击外部可以取消
            isOutsideTouchable = true
            isFocusable = true
            setOnDismissListener {
                val layoutParamsDismiss = requireActivity().window.attributes
                layoutParamsDismiss.alpha = 1f
                requireActivity().window.attributes = layoutParamsDismiss
            }
        }

        block()
    }

    /**
     * 弹出底部selector
     */
    fun showSelector(block: () -> Unit) {
        selectorPopView = View.inflate(OASystem.context, R.layout.popup_selector, null)
        popupWindow = PopupWindow(selectorPopView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        showPopupWindow {

            selector = selectorPopView.findViewById(R.id.selector_list)

            val layoutManager = LinearLayoutManager(OASystem.context)
            selector.layoutManager = layoutManager

            block()

            popupWindow.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
        }
    }

    /**
     * 弹出日期选择组件
     */

    fun showDatePicker(text: String, textView: TextView, block: () -> Unit) {
        val calendar = Calendar.getInstance()
        val popView = View.inflate(OASystem.context, R.layout.popup_date_selector, null)
        popupWindow = PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        showPopupWindow {

            val title = popView.findViewById<TextView>(R.id.date_selector_name)
            val datePicker = popView.findViewById<DatePicker>(R.id.date_selector)
            val commit = popView.findViewById<TextView>(R.id.commit)

            var date = String.format(resources.getString(R.string.date_format), calendar.get(
                Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH))

            title.text = text

            datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(
                Calendar.DAY_OF_MONTH)
            ) { _, year, month, day ->
                date = String.format(resources.getString(R.string.date_format), year, month + 1, day)
            }

            commit.setOnClickListener {
                textView.text = date
                popupWindow.dismiss()
            }

            popupWindow.showAtLocation(binding.root, Gravity.CENTER, 0, 0)
        }

        block()
    }

    /**
     * 错误信息提示
     */
    fun showErrorInfo(stringId: Int) {
        showMessage(String.format(resources.getString(R.string.network_error), resources.getString(stringId)))
    }
}