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

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
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.BaseResponse
import com.pan_american.android.base.CardAdapter
import com.pan_american.android.base.CustomAlertDialog
import com.pan_american.android.data.model.common.network.DeleteRequest
import com.pan_american.android.data.model.financial_module.payment_refund.entity.PaymentRefundListItem
import com.pan_american.android.data.model.financial_module.payment_refund.network.GroupPaymentRefundListRequest
import com.pan_american.android.data.model.financial_module.payment_refund.network.GroupPaymentRefundListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentPaymentRefundListBinding
import com.pan_american.android.util.ScrollEditText
import com.scwang.smart.refresh.header.ClassicsHeader
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class PaymentRefundListFragment : BaseFragment<FragmentPaymentRefundListBinding>() {

    private var groupId = 0

    private var tourCode = ""

    private var isShow = false

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

    private lateinit var groupPaymentRefundListRequest: GroupPaymentRefundListRequest

    private val groupPaymentRefundList = ArrayList<PaymentRefundListItem>()

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

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

        requireArguments().apply {
            groupId = getInt("groupId")
            binding.groupName.text = getString("teamName")
            tourCode = getString("tourCode", "")
            binding.groupCustomer.text = getString("clientName")
            binding.visitCountry.text = getString("visitCountry")
            binding.visitDays.text = getString("visitDays")
            binding.visitMembers.text = getString("visitPNumber")
            binding.duringTime.text = getString("duringTime")
        }

        initViews()

        initEvents()

        groupPaymentRefundListRequest = GroupPaymentRefundListRequest(diId = groupId)

        getPaymentRefundList()
    }

    override fun onResume() {
        super.onResume()

        if (OASystem.needRefresh) {
            binding.paymentRefundList.adapter!!.notifyItemRangeRemoved(0, groupPaymentRefundList.size)
            groupPaymentRefundList.clear()
            getPaymentRefundList()

            OASystem.needRefresh = false
        }
    }

    override fun initViews() {
        if (OASystem.authorization(OASystem.PAYMENT_REFUND, OASystem.ADD)) {
            binding.addPaymentItem.visibility = View.VISIBLE
        }

        binding.paymentRefundListContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
    }

    override fun initEvents() {
        binding.baseInfoSwitch.setOnClickListener {
            if (isShow) {
                binding.groupBaseInfo.visibility = View.GONE
                binding.baseInfoSwitch.text = resources.getString(R.string.show)
                isShow = false
            } else {
                binding.groupBaseInfo.visibility = View.VISIBLE
                binding.baseInfoSwitch.text = resources.getString(R.string.hide)
                isShow = true
            }
        }

        binding.addPaymentItem.setOnClickListener {
            val intent = Intent(OASystem.context, AddPaymentRefundActivity::class.java)
            intent.putExtra("groupId", groupId)
            startActivity(intent)
        }
    }

    private fun getPaymentRefundList() {

        if (!isAdded) {
            return
        }

        apiService.getGroupPaymentRefundList(groupPaymentRefundListRequest)
            .enqueue(object : Callback<GroupPaymentRefundListResponse> {
                override fun onResponse(
                    call: Call<GroupPaymentRefundListResponse>,
                    response: Response<GroupPaymentRefundListResponse>
                ) {
                    val listResponse = response.body()

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

                            if (listResponse.data.data.isEmpty()) {
                                showMessage(resources.getString(R.string.no_data))
                            } else {
                                for (item in listResponse.data.data) {
                                    groupPaymentRefundList.add(item)
                                }
                            }

                            if (binding.paymentRefundListContainer.isRefreshing) {
                                binding.paymentRefundListContainer.finishRefresh()
                            }

                            initList()
                        }
                    }
                }

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

    private fun initList() {

        if (groupPaymentRefundList.size == 0) {
            return
        }

        val linearLayoutManager = LinearLayoutManager(OASystem.context)
        binding.paymentRefundList.layoutManager = linearLayoutManager

        val adapter = CardAdapter.Builder<PaymentRefundListItem>().apply {
            setData(groupPaymentRefundList)
            setLayoutId(R.layout.item_payment_refund_list)
            setCanDelete(OASystem.authorization(OASystem.PAYMENT_REFUND, OASystem.DELETE))
            addBindView { itemView, data ->
                itemView.findViewById<ImageView>(R.id.delete).apply {
                    visibility = if (data.isAuditGM != 1) {
                        View.VISIBLE
                    } else {
                        View.GONE
                    }
                }
                itemView.findViewById<TextView>(R.id.payment_name).text = data.priceName
                itemView.findViewById<TextView>(R.id.total_payment).text = String.format(
                    resources.getString(R.string.price_and_currency_format),
                    data.price,
                    data.currencyCode
                )
                itemView.findViewById<TextView>(R.id.creator).text = data.createUserName
                itemView.findViewById<TextView>(R.id.create_time).text = data.createTime
                itemView.findViewById<TextView>(R.id.is_verify).apply {
                    when(data.isAuditGM) {

                        0 -> {
                            itemView.findViewById<TextView>(R.id.is_verify).apply {
                                text = resources.getString(R.string.verify_wait)
                                setTextColor(Color.rgb(23, 171, 227))
                            }
                        }

                        1 -> {
                            itemView.findViewById<TextView>(R.id.is_verify).apply {
                                text = resources.getString(R.string.verify_passed)
                                setTextColor(Color.rgb(84, 213, 77))
                            }
                        }

                        2 -> {
                            itemView.findViewById<TextView>(R.id.is_verify).apply {
                                text = resources.getString(R.string.verify_rejected)
                                setTextColor(Color.rgb(210, 45, 34))
                            }
                        }

                        3 -> {
                            itemView.findViewById<TextView>(R.id.is_verify).text =
                                resources.getString(R.string.auto_verify)
                        }
                    }
                }
                itemView.findViewById<TextView>(R.id.verify_name).text = data.auditGMName.ifBlank { "-" }
                itemView.findViewById<TextView>(R.id.verify_time).text = data.auditGMDate.ifBlank { "-" }
                itemView.findViewById<ScrollEditText>(R.id.notes).apply {
                    isEnabled(false)
                    setText(data.remark.ifBlank { "-" })
                }
            }
        }.create()

        binding.paymentRefundList.adapter = adapter

        adapter.onRecyclerViewItemClick = object : CardAdapter.OnRecyclerViewItemClick<PaymentRefundListItem> {
            override fun onItemClick(position: Int) {
                if (groupPaymentRefundList[position].isAuditGM != 1) {
                    val intent = Intent(OASystem.context, AddPaymentRefundActivity::class.java)
                    intent.putExtra("fromList", true)
                    intent.putExtra("id", groupPaymentRefundList[position].id)
                    intent.putExtra("groupId", groupId)
                    startActivity(intent)
                } else {
                    return
                }
            }

            override fun onItemDelete(position: Int) {
                CustomAlertDialog.Builder().apply {
                    setTitle(resources.getString(R.string.alert))
                    setMessage(String.format(resources.getString(R.string.delete_alert_text), groupPaymentRefundList[position].priceName))
                    setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                        dialog.dismiss()
                    }
                    setPositiveButtonAndListener(resources.getString(R.string.confirm)) { dialog, _ ->
                        dialog.dismiss()

                        deletePaymentRefundItem(position)
                    }
                }.show()
            }
        }

        binding.paymentRefundListContainer.setOnRefreshListener {
            binding.paymentRefundList.adapter!!.notifyItemRangeRemoved(0, groupPaymentRefundList.size)
            groupPaymentRefundList.clear()
            getPaymentRefundList()
        }
    }

    private fun deletePaymentRefundItem(position: Int) {
        apiService.deletePaymentRefundItem(DeleteRequest(id = groupPaymentRefundList[position].id, pageId = OASystem.PAYMENT_REFUND)).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {
                val deleteResponse = response.body()

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

                        groupPaymentRefundList.removeAt(position)
                        binding.paymentRefundList.adapter!!.notifyItemRemoved(position)
                        binding.paymentRefundList.adapter!!.notifyItemRangeChanged(position, groupPaymentRefundList.size - position)

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

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