package com.pan_american.android.ui.financial_module.payment_refund

import android.os.Bundle
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.BaseActivity
import com.pan_american.android.base.BaseRequest
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.financial_module.payment_refund.network.PaymentRefundDataSourceResponse
import com.pan_american.android.data.model.financial_module.payment_refund.network.PaymentRefundDetailRequest
import com.pan_american.android.data.model.financial_module.payment_refund.network.PaymentRefundDetailResponse
import com.pan_american.android.data.model.financial_module.payment_refund.network.UpdatePaymentRefundRequest
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAddPaymentRefundBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import com.pan_american.android.util.MoneyInputFilter
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class AddPaymentRefundActivity : BaseActivity<ActivityAddPaymentRefundBinding>() {

    private var fromList = false

    private var paymentId = 0

    private var groupId = 0

    private val paymentWayList = ArrayList<Selector>()

    private val paymentMarkList = ArrayList<Selector>()

    private val paymentTypeList = ArrayList<Selector>()

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

    private var paymentWayId = -1

    private var paymentMarkId = -1

    private var paymentTypeId = -1

    private val updatePaymentRefundRequest = UpdatePaymentRefundRequest()

    private lateinit var titleBinding: LayoutTitleBinding

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

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

        intent.apply {
            fromList = getBooleanExtra("fromList", false)
            paymentId = getIntExtra("id", 0)
            groupId = getIntExtra("groupId", 0)
        }

        initTitle()

        //获取基础数据源
        getBaseDataSource()
    }

    private fun getBaseDataSource() {
        apiService.getPaymentRefundBaseDataSource(BaseRequest()).enqueue(object : Callback<PaymentRefundDataSourceResponse> {
            override fun onResponse(
                call: Call<PaymentRefundDataSourceResponse>,
                response: Response<PaymentRefundDataSourceResponse>
            ) {
                val dataResponse = response.body()

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

                        dataResponse.data.apply {

                            for (item in orbitalPrivateTransferDatas) {
                                paymentMarkList.add(item)
                            }

                            for (item in payTypeDatas) {
                                paymentWayList.add(item)
                            }

                            for (item in priceTypeDatas) {
                                paymentTypeList.add(item)
                            }
                        }

                        initViews()

                        initEvents()

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

            override fun onFailure(p0: Call<PaymentRefundDataSourceResponse>, p1: Throwable) {
                showErrorInfo(R.string.payment_refund_base_data_get_error)
            }
        })
    }

    override fun initTitle() {
        titleBinding = LayoutTitleBinding.bind(binding.root).apply {
            titleText.text = if (fromList) {
                resources.getString(R.string.update_payment_refund)
            } else {
                resources.getString(R.string.add_payment_refund)
            }

            backButton.setOnClickListener {
                back()
            }
        }
    }

    override fun initViews() {
        if (fromList) {
            getPaymentDetailById()

            binding.commit.setText(resources.getString(R.string.update))

        } else {
            binding.commit.setText(resources.getString(R.string.add))
        }

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

    override fun initEvents() {
        binding.paymentWay.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(paymentWayList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            if (paymentWayId == data.id) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }

                            text = data.name
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                    override fun onItemClick(position: Int) {
                        paymentWayList[position].apply {
                            paymentWayId = id

                            binding.paymentWay.text = name

                            popupWindow.dismiss()
                        }
                    }
                }
            }
        }

        binding.paymentMark.setOnClickListener {
            showSelector {
                showSelector {
                    val adapter = ListAdapter.Builder<Selector>().apply {
                        setData(paymentMarkList)
                        setLayoutId(R.layout.item_selector)
                        addBindView { itemView, data ->
                            itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                                if (paymentMarkId == data.id) {
                                    setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                                } else {
                                    setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                                }

                                text = data.name
                            }
                        }
                    }.create()

                    selector.adapter = adapter

                    adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            paymentMarkList[position].apply {
                                paymentMarkId = id

                                binding.paymentMark.text = name

                                popupWindow.dismiss()
                            }
                        }
                    }
                }
            }
        }

        binding.paymentType.setOnClickListener {
            showSelector {
                showSelector {
                    val adapter = ListAdapter.Builder<Selector>().apply {
                        setData(paymentTypeList)
                        setLayoutId(R.layout.item_selector)
                        addBindView { itemView, data ->
                            itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                                if (paymentTypeId == data.id) {
                                    setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                                } else {
                                    setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                                }

                                text = data.name
                            }
                        }
                    }.create()

                    selector.adapter = adapter

                    adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            paymentTypeList[position].apply {
                                paymentTypeId = id

                                binding.paymentType.text = name

                                popupWindow.dismiss()
                            }
                        }
                    }
                }
            }
        }

        binding.commit.setOnClickListener {
            if (binding.paymentName.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.payment_name_input_hint))
                return@setOnClickListener
            } else {
                updatePaymentRefundRequest.priceName = binding.paymentName.text.toString()
            }

            if (binding.price.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.payment_price_hint))
                return@setOnClickListener
            } else {
                updatePaymentRefundRequest.price = binding.price.text.toString().toDouble()
            }

            if (binding.payee.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.payee_hint))
                return@setOnClickListener
            } else {
                updatePaymentRefundRequest.payee = binding.payee.text.toString()
            }

            if (binding.otherBankName.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.other_bank_name_input_hint))
                return@setOnClickListener
            } else {
                updatePaymentRefundRequest.otherBankName = binding.otherBankName.text.toString()
            }

            if (binding.otherSideNo.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.other_side_number_input_hint))
                return@setOnClickListener
            } else {
                updatePaymentRefundRequest.otherSideNo = binding.otherSideNo.text.toString()
            }

            if (paymentWayId == -1) {
                showMessage(resources.getString(R.string.payment_way_hint))
                return@setOnClickListener
            } else {
                updatePaymentRefundRequest.payDId = paymentWayId
            }

            if (paymentMarkId == -1) {
                showMessage(resources.getString(R.string.payment_mark_hint))
                return@setOnClickListener
            } else {
                updatePaymentRefundRequest.orbitalPrivateTransfer = paymentMarkId
            }

            if (binding.consumeWay.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.consume_way_hint))
                return@setOnClickListener
            } else {
                updatePaymentRefundRequest.consumptionPatterns = binding.consumeWay.text.toString()
            }

            if (paymentTypeId == -1) {
                showMessage(resources.getString(R.string.payment_type_select_hint))
                return@setOnClickListener
            } else {
                updatePaymentRefundRequest.payType = paymentTypeId
            }

            if (binding.notes.getText().isNotBlank()) {
                updatePaymentRefundRequest.remark = binding.notes.getText()
            }

            if (fromList) {
                updatePaymentRefundRequest.status = 2
            } else {
                updatePaymentRefundRequest.status = 1
            }

            updatePaymentRefundRequest.diId = groupId

            updatePaymentRefund()
        }
    }

    private fun getPaymentDetailById() {
        apiService.getPaymentRefundDetailById(PaymentRefundDetailRequest(paymentId)).enqueue(object : Callback<PaymentRefundDetailResponse> {
            override fun onResponse(
                call: Call<PaymentRefundDetailResponse>,
                response: Response<PaymentRefundDetailResponse>
            ) {
                val detailResponse = response.body()

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

                        detailResponse.data.apply {
                            updatePaymentRefundRequest.id = id
                            updatePaymentRefundRequest.diId = diId
                            updatePaymentRefundRequest.ccpId = ccpId
                            paymentWayId = payDId
                            paymentMarkId = orbitalPrivateTransfer
                            paymentTypeId = payType

                            binding.paymentName.setText(priceName)
                            binding.price.setText(price.toString())
                            binding.payee.setText(payee)
                            binding.otherBankName.setText(otherBankName)
                            binding.otherSideNo.setText(otherSideNo)

                            for (item in paymentWayList) {
                                if (item.id == paymentWayId) {
                                    binding.paymentWay.text = item.name
                                }
                            }

                            for (item in paymentMarkList) {
                                if (item.id == paymentMarkId) {
                                    binding.paymentMark.text = item.name
                                }
                            }

                            binding.consumeWay.setText(consumptionPatterns)

                            for (item in paymentTypeList) {
                                if (item.id == paymentTypeId) {
                                    binding.paymentType.text = item.name
                                }
                            }

                            binding.notes.setText(remark)
                        }
                    } else {
                        showMessage(detailResponse.msg)
                    }
                }
            }

            override fun onFailure(p0: Call<PaymentRefundDetailResponse>, p1: Throwable) {
                showErrorInfo(R.string.payment_refund_detail_get_error)
            }
        })
    }

    private fun updatePaymentRefund() {
        apiService.updatePaymentRefundDetail(updatePaymentRefundRequest).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {
                val updateResponse = response.body()

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

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

            override fun onFailure(p0: Call<BaseResponse>, p1: Throwable) {
                showErrorInfo(R.string.update_error)
            }
        })
    }
}