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

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.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.group_hotel.hotel_payment_insert.entity.HotelPredetermineListItem
import com.pan_american.android.data.model.group_hotel.hotel_payment_insert.network.HotelPredetermineListRequest
import com.pan_american.android.data.model.group_hotel.hotel_payment_insert.network.HotelPredetermineListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentHotelPredetermineListBinding
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class HotelPredetermineListFragment : BaseFragment<FragmentHotelPredetermineListBinding>() {

    private var isShow = false

    private var groupId = 0

    private var tourCode = ""

    private lateinit var hotelPredetermineListRequest: HotelPredetermineListRequest

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

    private var listInit = false

    private var hotelPredetermineList = ArrayList<HotelPredetermineListItem>()

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

    override fun onStart() {
        super.onStart()

        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()
    }


    override fun initViews() {

        if (OASystem.authorization(OASystem.HOTEL_PREDETERMINE, OASystem.ADD)) {
            binding.addPaymentItem.apply {

                visibility = View.VISIBLE

                setOnClickListener {
                    val intent =
                        Intent(OASystem.context, AddHotelPredetermineActivity::class.java).apply {
                            putExtra("groupId", groupId)
                            putExtra("teamName", binding.groupName.text)
                            putExtra("tourCode", tourCode)
                            putExtra("clientName", binding.groupCustomer.text)
                            putExtra("visitCountry", binding.visitCountry.text)
                        }
                    startActivity(intent)
                }
            }
        }

        binding.hotelPredetermineContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
        binding.hotelPredetermineContainer.setRefreshFooter(ClassicsFooter(OASystem.context))

        hotelPredetermineListRequest =
            HotelPredetermineListRequest(groupId, OASystem.HOTEL_PREDETERMINE)

        getHotelPredetermineList(1)
    }

    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
            }
        }
    }

    private fun getHotelPredetermineList(type: Int) {

        //避免Fragment not attached to a context.
        if (!isAdded) {
            return
        }

        if (!listInit) {
            apiService.getHotelPredetermineList(hotelPredetermineListRequest)
                .enqueue(object : Callback<HotelPredetermineListResponse> {
                    override fun onResponse(
                        call: Call<HotelPredetermineListResponse>,
                        response: Response<HotelPredetermineListResponse>
                    ) {
                        val hotelPredetermineResponse = response.body()

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

                                for (item in hotelPredetermineResponse.data) {
                                    hotelPredetermineList.add(item)
                                }

                                if (hotelPredetermineList.size == 0) {
                                    showMessage(resources.getString(R.string.no_data))
                                }

                                when (type) {
                                    1 -> {
                                        binding.hotelPredetermineContainer.setEnableLoadMore(false)
                                        initList()
                                        listInit = true
                                    }

                                    2 -> {
                                        binding.hotelPredetermineContainer.finishRefresh()
                                        binding.hotelPredetermineContainer.setEnableLoadMore(false)
                                        initList()
                                        listInit = true
                                    }
                                }

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

                    override fun onFailure(
                        call: Call<HotelPredetermineListResponse>, t: Throwable
                    ) {
                        showErrorInfo(R.string.hotel_predetermine_list_get_failed)
                    }
                })
        } else {
            if (OASystem.needRefresh) {
                hotelPredetermineList.clear()
                listInit = false
                getHotelPredetermineList(2)
            }
        }
    }

    private fun initList() {

        val layoutManager = LinearLayoutManager(OASystem.context)
        binding.hotelPredetermineList.layoutManager = layoutManager

        val adapter = CardAdapter.Builder<HotelPredetermineListItem>().apply {
            setLayoutId(R.layout.item_hotel_predetermine_list)
            setData(hotelPredetermineList)
            setCanDelete(OASystem.authorization(OASystem.HOTEL_PREDETERMINE, OASystem.DELETE))
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.hotel_name).text = data.hotelName
                itemView.findViewById<TextView>(R.id.predetermine_code).text = data.reservationsNo
                itemView.findViewById<TextView>(R.id.check_in_start_time).text = data.checkInDate
                itemView.findViewById<TextView>(R.id.check_in_end_time).text = data.checkOutDate
                itemView.findViewById<TextView>(R.id.payment_sum).text = String.format(
                    resources.getString(R.string.price_and_currency_format),
                    data.payMoney,
                    data.payCurrency
                )

                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_reject)
                            setTextColor(Color.rgb(210, 45, 34))
                        }
                    }

                    3 -> {
                        itemView.findViewById<TextView>(R.id.is_verify).text =
                            resources.getString(R.string.auto_verify)
                    }
                }
            }
        }.create()

        binding.hotelPredetermineList.adapter = adapter

        adapter.onRecyclerViewItemClick =
            object : CardAdapter.OnRecyclerViewItemClick<HotelPredetermineListItem> {
                override fun onItemClick(position: Int) {
                    val intent =
                        Intent(OASystem.context, AddHotelPredetermineActivity::class.java).apply {
                            putExtra("fromList", true)
                            putExtra("groupId", groupId)
                            putExtra("paymentId", hotelPredetermineList[position].id)
                            putExtra("teamName", binding.groupName.text)
                            putExtra("tourCode", tourCode)
                            putExtra("clientName", binding.groupCustomer.text)
                            putExtra("visitCountry", binding.visitCountry.text)

                            putExtra("isAuditGM", hotelPredetermineList[position].isAuditGM)
                        }
                    startActivity(intent)
                }

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

        binding.hotelPredetermineContainer.setOnRefreshListener {
            hotelPredetermineList.clear()
            listInit = false
            getHotelPredetermineList(2)
        }
    }

    private fun deleteHotelPredetermineItem(position: Int) {
        apiService.deleteHotelPredetermine(DeleteRequest(hotelPredetermineList[position].id))
            .enqueue(object : Callback<BaseResponse> {
                override fun onResponse(
                    call: Call<BaseResponse>, response: Response<BaseResponse>
                ) {
                    val baseResponse = response.body()
                    if (baseResponse != null) {
                        if (baseResponse.code == 200) {
                            hotelPredetermineList.removeAt(position)
                            binding.hotelPredetermineList.adapter!!.notifyItemRemoved(position)
                            binding.hotelPredetermineList.adapter!!.notifyItemRangeRemoved(
                                position, hotelPredetermineList.size - position
                            )

                            showMessage(resources.getString(R.string.delete_success))
                        } else {
                            showMessage(baseResponse.msg)
                        }
                    }
                }

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