package com.pan_american.android.ui.group_management.group_info

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
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.CustomAlertDialog
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.databinding.FragmentGroupInfoBaseBinding
import com.pan_american.android.util.MoneyInputFilter

class GroupInfoBaseFragment : BaseFragment<FragmentGroupInfoBaseBinding>() {

    private var opPercentageSelected = false

    private var opPercentageSubLevel = listOf<String>()

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

    override fun onStart() {
        super.onStart()

        initViews()
        initEvents()
    }

    override fun initViews() {

        binding.apply {

            salesQuotation.text = OASystem.groupOperationRequest.salesQuoteNo

            for (item in OASystem.tradeDirector) {
                if (OASystem.groupOperationRequest.jietuanOperator == item.id) {
                    groupTradeDirector.text = item.cnName
                }
            }

            for (item in OASystem.groupInfoCustomerLevel) {
                if (OASystem.groupOperationRequest.teamLevSId == item.id) {
                    customerLevel.text = item.name
                }
            }

            for (item in OASystem.groupType) {
                if (OASystem.groupOperationRequest.teamDid == item.id) {
                    groupType.text = item.name
                }
            }

            groupName.setText(OASystem.groupOperationRequest.teamName)
            clientName.setText(OASystem.groupOperationRequest.clientName)
            customerDepartment.setText(OASystem.groupOperationRequest.clientUnit)
            visitCountry.setText(OASystem.groupOperationRequest.visitCountry)
            visitDate.text = OASystem.groupOperationRequest.visitDate
            visitDays.setText(OASystem.groupOperationRequest.visitDays.toString())
            visitMembers.setText(OASystem.groupOperationRequest.visitPNumber.toString())
            contractDate.text = OASystem.groupOperationRequest.tontractTime
            visitDaysBefore.setText(OASystem.groupOperationRequest.payDay.toString())
            prePayment.setText(OASystem.groupOperationRequest.paymentMoney.toString())

            for (item in OASystem.opPercentageLevel) {
                if (OASystem.groupOperationRequest.opRoyaltyLv == item.id) {
                    opPercentageLevel.text = item.name

                    opPercentageSelected = true
                }
            }

            levelIllustrate.text = OASystem.groupOperationRequest.opRoyaltyRemark
        }

        if (!OASystem.authorization(OASystem.GROUP_INFORMATION, OASystem.EDIT)) {
            binding.apply {

                salesQuotation.isEnabled = false

                groupTradeDirector.isEnabled = false

                customerLevel.isEnabled = false

                groupType.isEnabled = false

                groupName.isEnabled = false
                clientName.isEnabled = false
                customerDepartment.isEnabled = false
                visitCountry.isEnabled = false
                visitDate.isEnabled = false
                visitDays.isEnabled = false
                visitMembers.isEnabled = false
                contractDate.isEnabled = false
                visitDaysBefore.isEnabled = false
                prePayment.isEnabled = false

                opPercentageLevel.isEnabled = false

                levelIllustrate.isEnabled = false

                reset.visibility = View.GONE
            }
        }

        if (OASystem.groupOperationRequest.status == 2) {
            for (item in OASystem.opPercentageLevel) {
                if (item.id == OASystem.groupOperationRequest.opRoyaltyLv) {
                    opPercentageSubLevel = item.remark.split("&")
                }
            }
        }

        binding.prePayment.filters = arrayOf(MoneyInputFilter())
    }

    override fun initEvents() {

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

                            if (OASystem.groupOperationRequest.jietuanOperator == 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) {
                            OASystem.tradeDirector[position].apply {
                                binding.groupTradeDirector.text = cnName
                                OASystem.groupOperationRequest.jietuanOperator = id
                            }

                            popupWindow.dismiss()
                        }
                    }
            }
        }

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

                            if (OASystem.groupOperationRequest.teamLevSId == 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) {
                            OASystem.groupInfoCustomerLevel[position].apply {
                                binding.customerLevel.text = name
                                OASystem.groupOperationRequest.teamLevSId = id
                            }

                            popupWindow.dismiss()
                        }
                    }
            }
        }

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

                            if (OASystem.groupOperationRequest.teamDid == 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) {
                            OASystem.groupType[position].apply {
                                binding.groupType.text = name
                                OASystem.groupOperationRequest.teamDid = id
                            }

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.customerDepartment.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(p0: Editable?) {
                initGroupName()
            }
        })

        binding.visitCountry.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(p0: Editable?) {
                initGroupName()
            }
        })

        binding.visitDays.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(p0: Editable?) {
                initGroupName()
            }
        })

        binding.visitDate.setOnClickListener {
            showDatePicker(resources.getString(R.string.visit_date), binding.visitDate) {}
        }

        binding.contractDate.setOnClickListener {
            showDatePicker(resources.getString(R.string.contract_date), binding.contractDate) {}
        }

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

                            if (OASystem.groupOperationRequest.opRoyaltyLv == 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) {
                            OASystem.opPercentageLevel[position].apply {
                                binding.opPercentageLevel.text = name

                                opPercentageSubLevel = remark.split("&")

                                if (id != OASystem.groupOperationRequest.opRoyaltyLv) {

                                    binding.levelIllustrate.text = ""

                                    OASystem.groupOperationRequest.opRoyaltyLv = id
                                }
                            }

                            opPercentageSelected = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.levelIllustrate.setOnClickListener {
            if (!opPercentageSelected) {
                showMessage(resources.getString(R.string.op_percentage_hint))
                return@setOnClickListener
            }

            showSelector {
                val adapter = ListAdapter.Builder<String>().apply {
                    setData(opPercentageSubLevel)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data
                            isSelected = true

                            if (OASystem.groupOperationRequest.opRoyaltyRemark == data) {
                                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<String> {
                        override fun onItemClick(position: Int) {
                            opPercentageSubLevel[position].apply {
                                binding.levelIllustrate.text = this

                                OASystem.groupOperationRequest.opRoyaltyRemark = this
                            }

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.reset.setOnClickListener {

            CustomAlertDialog.Builder(OASystem.context).apply {
                setTitle(resources.getString(R.string.alert))
                setMessage(resources.getString(R.string.group_base_reset_alert))
                setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                    dialog.dismiss()
                }
                setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                    binding.apply {
                        groupTradeDirector.text = ""
                        customerLevel.text = ""
                        groupType.text = ""
                        groupName.setText("")
                        clientName.setText("")
                        customerDepartment.setText("")
                        visitCountry.setText("")
                        visitDate.text = ""
                        visitDays.setText("")
                        visitMembers.setText("")
                        contractDate.text = ""
                        visitDaysBefore.setText("")
                        prePayment.setText("")
                        opPercentageLevel.text = ""
                        levelIllustrate.text = ""
                    }
                }
            }
        }

        binding.nextPage.setOnClickListener {

            if (binding.groupTradeDirector.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.group_trade_director_hint))
                return@setOnClickListener
            }

            if (binding.customerLevel.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.customer_level_select_hint))
                return@setOnClickListener
            }

            if (binding.groupType.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.group_type_hint))
                return@setOnClickListener
            }

            binding.groupName.text.apply {
                if (isNullOrBlank()) {
                    showMessage(resources.getString(R.string.group_name_hint))
                    return@setOnClickListener
                } else {
                    OASystem.groupOperationRequest.teamName = this.toString()
                }
            }

            binding.clientName.text.apply {
                if (isNullOrBlank()) {
                    showMessage(resources.getString(R.string.client_name_hint))
                    return@setOnClickListener
                } else {
                    OASystem.groupOperationRequest.clientName = this.toString()
                }
            }

            binding.customerDepartment.text.apply {
                if (isNullOrBlank()) {
                    showMessage(resources.getString(R.string.customer_department_hint))
                    return@setOnClickListener
                } else {
                    OASystem.groupOperationRequest.clientUnit = this.toString()
                }
            }

            binding.visitCountry.text.apply {
                if (isNullOrBlank()) {
                    showMessage(resources.getString(R.string.visit_country_hint))
                    return@setOnClickListener
                } else {
                    OASystem.groupOperationRequest.visitCountry = this.toString()
                }
            }

            binding.visitDate.text.apply {
                if (isNullOrBlank()) {
                    showMessage(resources.getString(R.string.visit_date_hint))
                    return@setOnClickListener
                } else {
                    OASystem.groupOperationRequest.visitDate = this.toString()
                }
            }

            binding.visitDays.text.apply {
                if (isNullOrBlank()) {
                    showMessage(resources.getString(R.string.visit_days_hint))
                    return@setOnClickListener
                } else {
                    OASystem.groupOperationRequest.visitDays = this.toString().toInt()
                }
            }

            binding.visitMembers.text.apply {
                if (isNullOrBlank()) {
                    showMessage(resources.getString(R.string.visit_members_hint))
                    return@setOnClickListener
                } else {
                    OASystem.groupOperationRequest.visitPNumber = this.toString().toInt()
                }
            }

            binding.contractDate.text.apply {
                if (isNullOrBlank()) {
                    showMessage(resources.getString(R.string.contract_date_hint))
                    return@setOnClickListener
                } else {
                    OASystem.groupOperationRequest.tontractTime = this.toString()
                }
            }

            binding.visitDaysBefore.text.apply {
                if (isNullOrBlank()) {
                    showMessage(resources.getString(R.string.day_before_hint))
                    return@setOnClickListener
                } else {
                    OASystem.groupOperationRequest.payDay = this.toString().toInt()
                }
            }

            binding.prePayment.text.apply {
                if (isNullOrBlank()) {
                    showMessage(resources.getString(R.string.pre_payment_hint))
                    return@setOnClickListener
                } else {
                    OASystem.groupOperationRequest.paymentMoney = this.toString().toDouble()
                }
            }

            binding.opPercentageLevel.text.apply {
                if (isNullOrBlank()) {
                    showMessage(resources.getString(R.string.op_percentage_hint))
                    return@setOnClickListener
                }
            }

            binding.levelIllustrate.text.apply {
                if (isNullOrBlank()) {
                    showMessage(resources.getString(R.string.level_illustrate_hint))
                    return@setOnClickListener
                }
            }

            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)
                .replace(R.id.add_group_info_container, GroupCustomerListFragment()).commit()
        }
    }

    private fun initGroupName() {
        if (binding.customerDepartment.text.isNotBlank() && binding.visitCountry.text.isNotBlank() && binding.visitDays.text.isNotBlank()) {
            binding.groupName.setText(String.format(resources.getString(R.string.group_name_format), binding.customerDepartment.text, binding.visitCountry.text, binding.visitDays.text))
        }
    }
}