package com.pan_american.android.ui.group_hotel.hotel_predetermine

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseFragment
import com.pan_american.android.base.CardAdapter
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.group_hotel.hotel_predetermine.entity.HotelReservationsContentDetailsView
import com.pan_american.android.databinding.FragmentHotelPredetermineBaseBinding
import org.greenrobot.eventbus.EventBus
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

class HotelPredetermineBaseFragment : BaseFragment<FragmentHotelPredetermineBaseBinding>() {

    private var fromList = false

    private var teamName = ""

    private var tourCode = ""

    private var clientName = ""

    private var visitCountry = ""

    private var canBeEdit = false

    private var groupId = 0

    private var countryId = 0

    private var countrySelected = false

    private var customerTypeId = 0

    private var customerTypeSelect = false

    private var websiteId = 0

    private var websiteSelect = false

    private var customerSelectList = ArrayList<Selector>()

    private var checkInTypeId = 0

    private var checkInTypeSelect = false

    private var days = 0

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        bundle: Bundle?
    ) = FragmentHotelPredetermineBaseBinding.inflate(layoutInflater, container, false)

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

        requireArguments().apply {
            fromList = getBoolean("fromList")
            teamName = getString("teamName").toString()
            tourCode = getString("tourCode").toString()
            clientName = getString("clientName").toString()
            visitCountry = getString("visitCountry").toString()
            canBeEdit = getBoolean("canBeEdit")

            groupId = getInt("groupId")
        }

        initViews()
        initEvents()
    }

    override fun initViews() {
        binding.groupName.text = teamName
        binding.groupNumber.text = tourCode
        binding.groupCustomer.text = clientName
        binding.visitCountry.text = visitCountry

        if (fromList) {
            OASystem.hotelPredetermineRequest.apply {
                run {
                    for (item in OASystem.hotelPredetermineCustomerType) {
                        if (item.id == gtId) {
                            binding.customerType.text = item.name

                            customerTypeId = item.id
                            customerTypeSelect = true

                            return@run
                        }
                    }
                }

                binding.checkInCode.text = checkNumber

                run {
                    for (item in OASystem.hotelPredetermineHotelWebSite) {
                        if (item.id == reservationsWebsite) {
                            binding.predetermineWebsite.text = item.name

                            websiteId = item.id
                            websiteSelect = true

                            return@run
                        }
                    }
                }

                binding.hotelConfirmCode.setText(determineNo)

                run {
                    for (item in OASystem.hotelPredetermineCountries) {
                        if (item.id == areaId) {
                            binding.area.text = String.format(resources.getString(R.string.during_format), item.country, item.city)

                            countryId = item.id
                            countrySelected

                            return@run
                        }
                    }
                }

                binding.locatedCity.setText(city)

                binding.hotelName.setText(hotelName)

                binding.hotelTel.setText(hotelTel)

                binding.hotelLocation.setText(hotelAddress)

                val customerSelectedId = ArrayList<String>()

                if (guestName.isNotBlank()) {
                    guestName.split(",").onEach {
                        customerSelectedId.add(it)
                    }
                }

                customerSelectList.clear()

                if (customerSelectedId.isNotEmpty() && OASystem.hotelPredetermineCustomerList.size != 0) {
                    for (id in customerSelectedId) {
                        for (item in OASystem.hotelPredetermineCustomerList) {
                            if (id.matches(Regex("[0-9]*\$"))) {
                                if (item.id == id.toInt()) {
                                    customerSelectList.add(item)
                                }
                            }
                        }
                    }
                }

                initCustomerList()

                binding.checkInStartTime.text = checkInDate

                binding.checkInEndTime.text = checkOutDate

                days = if (binding.checkInStartTime.text.isNotBlank() && binding.checkInEndTime.text.isNotBlank()) {

                    val startTime = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).parse(binding.checkInStartTime.text.toString())
                    val endTime = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).parse(binding.checkInEndTime.text.toString())

                    getGapCount(startTime!!, endTime!!)

                } else {
                    0
                }

                run {
                    for (item in OASystem.hotelPredetermineCheckInType) {
                        if (item.id == checkType) {
                            binding.checkInType.text = item.name

                            checkInTypeId = item.id
                            checkInTypeSelect = true

                            return@run
                        }
                    }
                }

                binding.roomIntroduction.setText(roomExplanation)

                binding.hotelNotes.setText(hotelRemark)
            }

            if (!canBeEdit) {
                binding.apply {
                    customerType.isEnabled = false
                    predetermineWebsite.isEnabled = false
                    hotelConfirmCode.isEnabled(false)
                    locatedCity.isEnabled = false
                    hotelName.isEnabled = false
                    hotelTel.isEnabled = false
                    hotelLocation.isEnabled(false)
                    addCustomer.visibility = View.GONE
                    checkInStartTime.isEnabled = false
                    checkInEndTime.isEnabled = false
                    checkInType.isEnabled = false
                    roomIntroduction.isEnabled(false)
                    hotelNotes.isEnabled(false)

                    save.visibility = View.GONE
                }
            }
        }
    }

    override fun initEvents() {
        binding.customerType.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setLayoutId(R.layout.item_selector)
                    setData(OASystem.hotelPredetermineCustomerType)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.name

                            if (customerTypeId == data.id) {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.title_background_color,
                                        null
                                    )
                                )
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            binding.customerType.text = OASystem.hotelPredetermineCustomerType[position].name

                            customerTypeId = OASystem.hotelPredetermineCustomerType[position].id
                            customerTypeSelect = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.predetermineWebsite.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setLayoutId(R.layout.item_selector)
                    setData(OASystem.hotelPredetermineHotelWebSite)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.name

                            if (websiteId == data.id) {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.title_background_color,
                                        null
                                    )
                                )
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            binding.predetermineWebsite.text = OASystem.hotelPredetermineHotelWebSite[position].name

                            websiteId = OASystem.hotelPredetermineHotelWebSite[position].id
                            websiteSelect = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.area.setOnClickListener {
            val selectorList = ArrayList<Selector>()

            for (item in OASystem.hotelPredetermineCountries) {
                selectorList.add(item)
            }

            val popView = View.inflate(OASystem.context, R.layout.popup_smart_refresh_selector, null)
            popupWindow = PopupWindow(popView, RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)

            showPopupWindow {

                val searchView: LinearLayout = popView.findViewById(R.id.search_view)
                searchView.visibility = View.VISIBLE

                val searchText: EditText = popView.findViewById(R.id.search_text)

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

                selectorContainer = popView.findViewById(R.id.selector_refresh_container)
                selectorContainer.setEnableRefresh(false)
                selectorContainer.setEnableLoadMore(false)

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

                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(selectorList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = String.format(resources.getString(R.string.during_format), data.country, data.city)

                            if (countryId == data.id) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            selectorList[position].apply {
                                binding.area.text = String.format(resources.getString(R.string.during_format), country, city)
                                binding.locatedCity.setText(city)

                                countryId = id
                                countrySelected = true

                                popupWindow.dismiss()
                            }
                        }
                    }

                searchText.addTextChangedListener(object : TextWatcher {
                    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                    }

                    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                    }

                    override fun afterTextChanged(editable: Editable?) {

                        adapter.notifyItemRangeRemoved(0, selectorList.size)

                        selectorList.clear()

                        if (editable.isNullOrBlank()) {

                            for (item in OASystem.hotelPredetermineCountries) {
                                selectorList.add(item)
                            }

                        } else {
                            for (i in 0 until OASystem.hotelPredetermineCountries.size) {
                                OASystem.hotelPredetermineCountries[i].apply {
                                    if (country.contains(editable) || city.contains(editable)) {
                                        selectorList.add(this)
                                    }
                                }
                            }
                        }

                        if (selectorList.size == 0) {
                            showMessage(resources.getString(R.string.no_data))
                        } else {
                            for (i in 0 until selectorList.size) {
                                adapter.notifyItemInserted(i)
                            }
                        }
                    }
                })

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

        binding.addCustomer.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setLayoutId(R.layout.item_selector)
                    setData(OASystem.hotelPredetermineCustomerList)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = String.format(
                                resources.getString(R.string.currency_name_code_format),
                                String.format(
                                    resources.getString(R.string.with_space_format),
                                    data.lastName,
                                    data.firstName
                                ),
                                data.pinyin
                            )

                            for (item in customerSelectList) {
                                if (data.id == item.id) {
                                    setTextColor(
                                        ResourcesCompat.getColor(
                                            resources, R.color.title_background_color, null
                                        )
                                    )
                                }
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {

                            for (item in customerSelectList) {
                                if (OASystem.hotelPredetermineCustomerList[position].id == item.id) {
                                    showMessage(resources.getString(R.string.customer_selected))
                                    popupWindow.dismiss()
                                    return
                                }
                            }

                            customerSelectList.add(OASystem.hotelPredetermineCustomerList[position])
                            initCustomerList()

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.checkInStartTime.setOnClickListener {
            showDatePicker(resources.getString(R.string.check_in_start_select_hint), binding.checkInStartTime)
        }

        binding.checkInEndTime.setOnClickListener {
            showDatePicker(resources.getString(R.string.check_in_end_select_hint), binding.checkInEndTime)
        }

        binding.checkInType.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(OASystem.hotelPredetermineCheckInType)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.name

                            if (checkInTypeId == data.id) {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.title_background_color,
                                        null
                                    )
                                )
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            binding.checkInType.text = OASystem.hotelPredetermineCheckInType[position].name

                            checkInTypeId = OASystem.hotelPredetermineCheckInType[position].id
                            checkInTypeSelect = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.save.setOnClickListener {

            if (hotelBaseDataVerify()) {
                if (!fromList) {
                    for (i in 1 .. 4) {
                        val hotelContent = HotelReservationsContentDetailsView()

                        hotelContent.priceType = i

                        OASystem.hotelPredetermineRequest.contents.add(hotelContent)
                    }
                }

                EventBus.getDefault().post(OASystem.hotelPredetermineRequest)
            }

        }

        binding.nextPage.setOnClickListener {

            if (canBeEdit) {
                if (hotelBaseDataVerify()) {
                    days = if (binding.checkInStartTime.text.isNotBlank() && binding.checkInEndTime.text.isNotBlank()) {

                        val startTime = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).parse(binding.checkInStartTime.text.toString())
                        val endTime = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).parse(binding.checkInEndTime.text.toString())

                        getGapCount(startTime!!, endTime!!)

                    } else {
                        0
                    }
                }
            }

            val hotelPredeterminePaymentFragment = HotelPredeterminePaymentFragment()

            val bundle = Bundle().apply {
                putBoolean("fromList", fromList)
                putBoolean("canBeEdit", canBeEdit)
                putInt("days", days)
            }

            hotelPredeterminePaymentFragment.arguments = bundle

            parentFragmentManager.beginTransaction().setCustomAnimations(
                R.anim.slide_right_in,
                R.anim.slide_left_out,
                R.anim.slide_left_in,
                R.anim.slide_right_out
            ).addToBackStack(null)
                .add(R.id.hotel_predetermine_container, hotelPredeterminePaymentFragment).commit()
        }
    }

    private fun initCustomerList() {
        val layoutManager = LinearLayoutManager(OASystem.context)
        binding.customerList.layoutManager = layoutManager

        val adapter = CardAdapter.Builder<Selector>().apply {
            setData(customerSelectList)
            setLayoutId(R.layout.item_delete_button_selector)
            setCanDelete(canBeEdit)
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.left_text).text = data.pinyin
                itemView.findViewById<TextView>(R.id.right_text).text = String.format(
                    resources.getString(R.string.with_space_format), data.lastName, data.firstName
                )
            }
        }.create()

        binding.customerList.adapter = adapter

        adapter.onRecyclerViewItemClick = object : CardAdapter.OnRecyclerViewItemClick<Selector> {
            override fun onItemClick(position: Int) {

            }

            override fun onItemDelete(position: Int) {
                customerSelectList.removeAt(position)
                binding.customerList.adapter!!.notifyItemRemoved(position)
                binding.customerList.adapter!!.notifyItemRangeChanged(position, customerSelectList.size - position)
            }
        }
    }

    private fun getGapCount(startData: Date, endDate: Date): Int {
        //开始时间
        val startTime = Calendar.getInstance()
        startTime.time = startData
        startTime.set(Calendar.HOUR_OF_DAY, 0)
        startTime.set(Calendar.MINUTE, 0)
        startTime.set(Calendar.SECOND, 0)
        startTime.set(Calendar.MILLISECOND, 0)

        //结束时间
        val endTime = Calendar.getInstance()
        endTime.time = endDate
        endTime.set(Calendar.HOUR_OF_DAY, 0)
        endTime.set(Calendar.MINUTE, 0)
        endTime.set(Calendar.SECOND, 0)
        endTime.set(Calendar.MILLISECOND, 0)

        return (((endTime.time.time - startTime.time.time) / (1000 * 60 * 60 * 24)).toInt())
    }

    private fun hotelBaseDataVerify(): Boolean {

        if (canBeEdit) {
            when {
                !customerTypeSelect -> {
                    showMessage(resources.getString(R.string.customer_type_select_hint))
                    return false
                }

                !websiteSelect -> {
                    showMessage(resources.getString(R.string.website_select_hint))
                    return false
                }

                binding.hotelConfirmCode.getText().isBlank() -> {
                    showMessage(resources.getString(R.string.hotel_confirm_code_hint))
                    return false
                }

                !countrySelected -> {
                    showMessage(resources.getString(R.string.area_select_hint))
                    return false
                }

                binding.locatedCity.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.hotel_located_input_hint))
                    return false
                }

                binding.hotelName.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.hotel_name_input_hint))
                    return false
                }

                binding.hotelTel.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.hotel_tel_input_hint))
                    return false
                }

                binding.hotelLocation.getText().isBlank() -> {
                    showMessage(resources.getString(R.string.hotel_located_input_hint))
                    return false
                }

                customerSelectList.size == 0 -> {
                    showMessage(resources.getString(R.string.customer_select_hint))
                    return false
                }

                binding.checkInStartTime.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.check_in_start_select_hint))
                    return false
                }

                binding.checkInEndTime.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.check_in_end_select_hint))
                    return false
                }

                !checkInTypeSelect -> {
                    showMessage(resources.getString(R.string.check_in_type_select_hint))
                    return false
                }

                binding.roomIntroduction.getText().isBlank() -> {
                    showMessage(resources.getString(R.string.room_introduction_hint))
                    return false
                }

                else -> {

                    OASystem.hotelPredetermineRequest.apply {
                        diId = groupId
                        gtId = customerTypeId
                        reservationsWebsite = websiteId
                        determineNo = binding.hotelConfirmCode.getText()
                        areaId = countryId
                        city = binding.locatedCity.text.toString()
                        hotelName = binding.hotelName.text.toString()
                        hotelTel = binding.hotelTel.text.toString()
                        hotelAddress = binding.hotelLocation.getText()

                        var i = 0
                        var idList = ""
                        while (i < customerSelectList.size) {

                            idList += customerSelectList[i].id
                            i += 1

                            if (i < customerSelectList.size) {
                                idList += ","
                            }
                        }

                        guestName = idList

                        checkInDate = binding.checkInStartTime.text.toString()

                        checkOutDate = binding.checkInEndTime.text.toString()

                        checkType = checkInTypeId

                        roomExplanation = binding.roomIntroduction.getText()

                        hotelRemark = binding.hotelNotes.getText()
                    }

                    return true
                }
            }
        } else {
            return true
        }
    }
}