package com.pan_american.android.ui.group_op.ground_convey_payment_insert

import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.CheckedTextView
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseActivity
import com.pan_american.android.base.BaseResponse
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.common.entity.SiftListItem
import com.pan_american.android.data.model.common.network.GroupCurrencyRequest
import com.pan_american.android.data.model.common.network.GroupCurrencyResponse
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.adapter.GroundConveyFooterAdapter
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.adapter.GroundConveyHeaderAdapter
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.adapter.GroundConveyTableAdapter
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.entity.GroundConveyTableItem
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.network.GroundConveyPaymentResourceRequest
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.network.GroundConveyPaymentResponse
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.network.UpdateGroundConveyDetailRequest
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityGroundConveyPaymentDetailBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class GroundConveyPaymentDetailActivity : BaseActivity<ActivityGroundConveyPaymentDetailBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private var groupId = 0

    private var paymentId = 0

    private val apiService = ServiceCreator.create<APIService>()

    private var paymentWayList = ArrayList<Selector>()

    private var currencyList = ArrayList<Selector>()

    private var tableInitialization = ArrayList<SiftListItem>()

    private var carTouristGuides = ArrayList<GroundConveyTableItem>()

    private var checkedItemId = ArrayList<Int>()

    private lateinit var adapter: GroundConveyTableAdapter

    private var headerAdapter = GroundConveyHeaderAdapter()

    private var footerAdapter = GroundConveyFooterAdapter()

    private var currencyId = 0

    private var currencySelect = false

    private var paymentMarkId = 0

    private var paymentMarkSelect = false

    private var paymentWayId = 0

    private var paymentWaySelect = false

    private var totalPrice = 0.0

    private val regex = Regex("^-?\\d+(\\.\\d{1,2})?\$")

    private val updateGroundConveyDetailRequest = UpdateGroundConveyDetailRequest()

    override fun getViewBinding() = ActivityGroundConveyPaymentDetailBinding.inflate(layoutInflater)

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

        intent.apply {
            groupId = getIntExtra("groupId", 0)
            paymentId = getIntExtra("paymentId", 0)
            headerAdapter.setGroupName(getStringExtra("teamName").toString())
        }

        initTitle()

        getGroundConveyDetailResource()
    }

    override fun initTitle() {
        titleBinding = LayoutTitleBinding.bind(binding.root).apply {
            titleText.text = resources.getString(R.string.cost_entry_detail)

            backButton.setOnClickListener {
                back()
            }
        }
    }

    override fun initViews() {

        binding.paymentList.itemAnimator!!.changeDuration = 0

        initList()
    }

    override fun initEvents() {

        binding.commit.setOnClickListener {

            updateGroundConveyDetailRequest.diId = groupId
            updateGroundConveyDetailRequest.ctggrId = paymentId

            if (!currencySelect) {
                showMessage(resources.getString(R.string.payment_currency_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyDetailRequest.currency = currencyId
            }

            if (footerAdapter.getPaymentPercentage().isBlank() || !footerAdapter.getPaymentPercentage().matches(regex)
            ) {
                showMessage(resources.getString(R.string.payment_percentage_input_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyDetailRequest.payPercentage =
                    footerAdapter.getPaymentPercentage().toDouble()
            }

            if (footerAdapter.getPayee().isBlank()) {
                showMessage(resources.getString(R.string.payee_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyDetailRequest.payee = footerAdapter.getPayee()
            }

            if (!paymentMarkSelect) {
                showMessage(resources.getString(R.string.payment_mark_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyDetailRequest.orbitalPrivateTransfer = paymentMarkId
            }

            if (!paymentWaySelect) {
                showMessage(resources.getString(R.string.payment_way_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyDetailRequest.payDId = paymentWayId
            }

            updateGroundConveyDetailRequest.opContentList = carTouristGuides

            val selectCheck = ArrayList<String>()

            for (item in checkedItemId) {
                selectCheck.add(item.toString())
            }

            updateGroundConveyDetailRequest.selectCheck = selectCheck

            updateGroundConveyDetail()

        }
    }

    private fun getGroundConveyDetailResource() {

        apiService.initGroundConveyDetailResource(GroundConveyPaymentResourceRequest(paymentId))
            .enqueue(object : Callback<GroundConveyPaymentResponse> {
                override fun onResponse(
                    call: Call<GroundConveyPaymentResponse>,
                    response: Response<GroundConveyPaymentResponse>
                ) {
                    val resourceResponse = response.body()

                    if (resourceResponse != null) {
                        if (resourceResponse.code == 200) {
                            for (item in resourceResponse.data.payment) {
                                paymentWayList.add(item)
                            }

                            for (item in resourceResponse.data.tableInitialization) {
                                tableInitialization.add(item)
                            }

                            for (item in resourceResponse.data.carTouristGuides) {
                                carTouristGuides.add(item)
                            }

                            OASystem.unitList = resourceResponse.data.ssdv

                            for (item in resourceResponse.data.checkedItemId) {
                                if (!checkedItemId.contains(item)) {
                                    checkedItemId.add(item)
                                }
                            }

                            for (item in tableInitialization) {
                                for (checkedItem in checkedItemId) {
                                    if (item.id == checkedItem) {
                                        item.isChecked = true
                                    }
                                }
                            }

                            for (item in carTouristGuides) {
                                for (checkedItem in checkedItemId) {
                                    if (item.sId == checkedItem) {
                                        totalPrice += item.price * item.count
                                    }
                                }

                                if (!checkedItemId.contains(item.sId)) {
                                    item.isVisible = false
                                }
                            }

                            headerAdapter.setCurrencyCode(resourceResponse.data.creditCardPayment.paymentCurrencyName)
                            currencyId = resourceResponse.data.creditCardPayment.paymentCurrency

                            if (resourceResponse.data.creditCardPayment.paymentCurrency != 0 && resourceResponse.data.creditCardPayment.paymentCurrencyName.isNotBlank()) {
                                for (item in carTouristGuides) {
                                    item.currencyStr = resourceResponse.data.creditCardPayment.paymentCurrencyName
                                }
                                currencySelect = true
                            }

                            binding.paymentTotal.text = String.format(
                                resources.getString(R.string.price_and_currency_format),
                                totalPrice,
                                headerAdapter.getCurrencyCode()
                            )

                            footerAdapter.setPayee(resourceResponse.data.creditCardPayment.payee)

                            footerAdapter.setPaymentPercentage(resourceResponse.data.creditCardPayment.payPercentage.toString())

                            footerAdapter.setPaymentMark(OASystem.paymentMark[resourceResponse.data.creditCardPayment.orbitalPrivateTransfer].name)

                            paymentMarkId =
                                resourceResponse.data.creditCardPayment.orbitalPrivateTransfer

                            paymentMarkSelect = true

                            run {
                                for (item in paymentWayList) {
                                    if (item.id == resourceResponse.data.creditCardPayment.payDId) {
                                        footerAdapter.setPaymentWay(item.name)

                                        paymentWayId = item.id
                                        paymentWaySelect = true

                                        return@run
                                    }
                                }
                            }

                            getGroupCurrency()

                        } else {
                            showMessage(resourceResponse.msg)
                        }
                    }
                }

                override fun onFailure(
                    call: Call<GroundConveyPaymentResponse>, t: Throwable
                ) {
                    showMessage(resources.getString(R.string.network_error))
                }
            })
    }

    private fun getGroupCurrency() {
        apiService.getGroupCurrency(GroupCurrencyRequest(groupId, OASystem.C_TABLE_GROUND_CONVEY))
            .enqueue(object : Callback<GroupCurrencyResponse> {
                override fun onResponse(
                    call: Call<GroupCurrencyResponse>, response: Response<GroupCurrencyResponse>
                ) {
                    val currencyResponse = response.body()

                    if (currencyResponse != null) {
                        if (currencyResponse.code == 200) {

                            for (item in currencyResponse.data.teamRates) {
                                currencyList.add(item)
                            }

                            initViews()

                            initEvents()

                        } else {
                            showMessage(currencyResponse.msg)
                        }
                    }
                }

                override fun onFailure(call: Call<GroupCurrencyResponse>, t: Throwable) {
                    showMessage(resources.getString(R.string.network_error))
                }
            })
    }

    private fun initList() {
        val layoutManager = LinearLayoutManager(OASystem.context)
        binding.paymentList.layoutManager = layoutManager

        headerAdapter.onItemClick = object : GroundConveyHeaderAdapter.OnItemClick {
            override fun onCurrencyCodeClick() {
                showSelector {
                    val selectorAdapter = ListAdapter.Builder<Selector>().apply {
                        setData(currencyList)
                        setLayoutId(R.layout.item_selector)
                        addBindView { itemView, data ->
                            itemView.findViewById<TextView>(R.id.selector_item_name).text =
                                String.format(
                                    resources.getString(R.string.currency_name_code_format),
                                    data.currencyName,
                                    data.currencyCode
                                )
                        }
                    }.create()

                    selector.adapter = selectorAdapter

                    selectorAdapter.onRecyclerViewItemClick =
                        object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                            override fun onItemClick(position: Int) {
                                headerAdapter.setCurrencyCode(currencyList[position].currencyCode)
                                binding.paymentTotal.text = String.format(
                                    resources.getString(R.string.price_and_currency_format),
                                    totalPrice,
                                    currencyList[position].currencyCode
                                )

                                currencyId = currencyList[position].currencyId
                                currencySelect = true

                                popupWindow.dismiss()

                                for ((i, item) in carTouristGuides.withIndex()) {
                                    item.currencyStr = headerAdapter.getCurrencyCode()
                                    binding.paymentList.adapter!!.notifyItemChanged(i)
                                }
                            }
                        }
                }
            }

            override fun onPaymentTypeClick() {
                val popView = View.inflate(OASystem.context, R.layout.popup_sift_list, null)
                popupWindow = PopupWindow(
                    popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
                )

                showPopupWindow {

                    //初始化RecyclerView
                    selector = popView.findViewById(R.id.selector_list)

                    val paymentTypeAdapter = ListAdapter.Builder<SiftListItem>().setData(tableInitialization)
                        .setLayoutId(R.layout.item_customer_sift_long).addBindView { itemView, data ->

                            itemView.findViewById<CheckedTextView>(R.id.customer_sift).apply {
                                isChecked = data.isChecked
                                text = data.name
                            }

                        }.create()

                    val staggeredGridLayoutManager = StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)

                    selector.layoutManager = staggeredGridLayoutManager
                    selector.adapter = paymentTypeAdapter

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

                                tableInitialization[position].apply {

                                    if (isChecked) {
                                        isChecked = false

                                        checkedItemId.remove(id)

                                        for ((i, item) in carTouristGuides.withIndex()) {
                                            if (item.sId == id) {
                                                carTouristGuides[i].isVisible = false
                                                totalPrice -= carTouristGuides[i].price * carTouristGuides[i].count
                                                adapter.notifyItemChanged(i)
                                            }
                                        }

                                    } else {
                                        isChecked = true
                                        checkedItemId.add(id)

                                        for ((i, item) in carTouristGuides.withIndex()) {
                                            if (item.sId == id) {
                                                carTouristGuides[i].isVisible = true
                                                totalPrice += carTouristGuides[i].price * carTouristGuides[i].count
                                                adapter.notifyItemChanged(i)
                                            }
                                        }
                                    }

                                    binding.paymentTotal.text = String.format(
                                        resources.getString(R.string.price_and_currency_format),
                                        totalPrice,
                                        headerAdapter.getCurrencyCode()
                                    )

                                    paymentTypeAdapter.notifyItemChanged(position)
                                }
                            }
                        }

                    popView.findViewById<TextView>(R.id.commit).setOnClickListener {
                        popupWindow.dismiss()
                    }

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

        adapter = GroundConveyTableAdapter(carTouristGuides)

        adapter.onItemTextChanged =
            object : GroundConveyTableAdapter.OnItemTextChanged {
                override fun onPriceTextChanged(position: Int) {

                    carTouristGuides[position].apply {
                        prePrice = price * count
                        price = adapter.price
                    }

                    totalPrice =
                        totalPrice - carTouristGuides[position].prePrice + carTouristGuides[position].price * carTouristGuides[position].count

                    binding.paymentTotal.text = String.format(
                        resources.getString(R.string.price_and_currency_format),
                        totalPrice,
                        headerAdapter.getCurrencyCode()
                    )
                }

                override fun onPriceContentChanged(position: Int) {
                    carTouristGuides[position].priceContent = adapter.priceContentText
                }

                override fun onCountChanged(position: Int) {
                    carTouristGuides[position].apply {
                        prePrice = price * count
                        count = adapter.count.toInt()
                    }

                    totalPrice =
                        totalPrice - carTouristGuides[position].prePrice + carTouristGuides[position].price * carTouristGuides[position].count

                    binding.paymentTotal.text = String.format(
                        resources.getString(R.string.price_and_currency_format),
                        totalPrice,
                        headerAdapter.getCurrencyCode()
                    )
                }
            }

        adapter.onItemClick =
            object : GroundConveyTableAdapter.OnItemClick {
                override fun onUnitClick(itemPosition: Int) {
                    showSelector {
                        val unitAdapter = ListAdapter.Builder<Selector>().apply {
                            setData(OASystem.unitList)
                            setLayoutId(R.layout.item_selector)
                            addBindView { itemView, data ->
                                itemView.findViewById<TextView>(R.id.selector_item_name).text = data.name
                            }
                        }.create()

                        selector.adapter = unitAdapter

                        unitAdapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                            override fun onItemClick(position: Int) {
                                OASystem.unitList[position].apply {

                                    carTouristGuides[itemPosition].units = id
                                    adapter.notifyItemChanged(itemPosition)

                                    popupWindow.dismiss()
                                }
                            }
                        }
                    }
                }
            }

        footerAdapter.onItemClick = object : GroundConveyFooterAdapter.OnItemClick {
            override fun paymentMarkClick() {
                showSelector {
                    val selectorAdapter = ListAdapter.Builder<Selector>().apply {
                        setData(OASystem.paymentMark)
                        setLayoutId(R.layout.item_selector)
                        addBindView { itemView, data ->
                            itemView.findViewById<TextView>(R.id.selector_item_name).text = data.name
                        }
                    }.create()

                    selector.adapter = selectorAdapter

                    selectorAdapter.onRecyclerViewItemClick =
                        object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                            override fun onItemClick(position: Int) {
                                footerAdapter.setPaymentMark(OASystem.paymentMark[position].name)

                                paymentMarkId = OASystem.paymentMark[position].id
                                paymentMarkSelect = true

                                popupWindow.dismiss()
                            }
                        }
                }
            }

            override fun paymentWayClick() {
                showSelector {
                    val selectorAdapter = ListAdapter.Builder<Selector>().apply {
                        setData(paymentWayList)
                        setLayoutId(R.layout.item_selector)
                        addBindView { itemView, data ->
                            itemView.findViewById<TextView>(R.id.selector_item_name).text = data.name
                        }
                    }.create()

                    selector.adapter = selectorAdapter

                    selectorAdapter.onRecyclerViewItemClick =
                        object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                            override fun onItemClick(position: Int) {
                                footerAdapter.setPaymentWay(paymentWayList[position].name)

                                paymentWayId = paymentWayList[position].id
                                paymentWaySelect = true

                                popupWindow.dismiss()
                            }
                        }
                }
            }
        }

        val concatAdapter = ConcatAdapter(headerAdapter, adapter, footerAdapter)

        binding.paymentList.adapter = concatAdapter
    }

    private fun updateGroundConveyDetail() {

        binding.commit.isEnabled = false

        binding.commit.visibility = View.GONE

        binding.updateLoading.visibility = View.VISIBLE

//        val file = File(filesDir, "data.txt")
//        if (file.exists()) {
//            file.delete()
//        }
//        file.createNewFile()
//        val writer = FileWriter(file)
//        writer.append(Gson().toJson(updateGroundConveyDetailRequest))
//        writer.flush()
//        writer.close()

        apiService.updateGroundConveyDetail(updateGroundConveyDetailRequest)
            .enqueue(object : Callback<BaseResponse> {
                override fun onResponse(
                    call: Call<BaseResponse>, response: Response<BaseResponse>
                ) {

                    val updateResponse = response.body()

                    if (updateResponse != null) {
                        if (updateResponse.code == 200) {
                            showMessage(resources.getString(R.string.update_success))

                            OASystem.needRefresh = true

                            back()
                        } else {
                            showMessage(updateResponse.msg)

                            binding.commit.isEnabled = true

                            binding.commit.visibility = View.VISIBLE

                            binding.updateLoading.visibility = View.GONE
                        }
                    }
                }

                override fun onFailure(call: Call<BaseResponse>, t: Throwable) {

                    binding.commit.isEnabled = true

                    binding.commit.visibility = View.VISIBLE

                    binding.updateLoading.visibility = View.GONE

                    showMessage(resources.getString(R.string.network_error))
                }
            })
    }
}