package com.pan_american.android.ui.group_airplane_ticket.airplane_payment_insert

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.common.network.GroupCurrencyRequest
import com.pan_american.android.data.model.common.network.GroupCurrencyResponse
import com.pan_american.android.data.model.group_airplane_ticket.airplane_payment_insert.entity.GroupAirplaneTicketListItem
import com.pan_american.android.data.model.group_airplane_ticket.airplane_payment_insert.network.AirplaneTicketListRequest
import com.pan_american.android.data.model.group_airplane_ticket.airplane_payment_insert.network.AirplaneTicketListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentAirplaneTicketListBinding
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class AirplaneTicketListFragment : BaseFragment<FragmentAirplaneTicketListBinding>() {

    private var isShow = false

    private var groupId = 0

    private var tourCode = ""

    private lateinit var airplaneTicketListRequest: AirplaneTicketListRequest

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

    private var currencyInit = false

    private var listInit = false

    private var pageIndex = 1

    private var totalPage = 0

    private var airplaneTicketList = ArrayList<GroupAirplaneTicketListItem>()

    override fun getViewBinding(
        inflater: LayoutInflater, container: ViewGroup?, bundle: Bundle?
    ) = FragmentAirplaneTicketListBinding.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")
        }

        getGroupCurrency()
    }

    override fun initViews() {

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

                visibility = View.VISIBLE

                setOnClickListener {
                    val intent =
                        Intent(OASystem.context, AddAirplaneTicketActivity::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.airplaneTicketPaymentContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
        binding.airplaneTicketPaymentContainer.setRefreshFooter(ClassicsFooter(OASystem.context))

        airplaneTicketListRequest = AirplaneTicketListRequest(groupId)

        airplaneTicketListRequest.pageIndex = pageIndex

        airplaneTicketListRequest.pageSize = 10

        getAirplaneTicketPaymentList(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 getGroupCurrency() {

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

        if (!currencyInit) {

            apiService.getGroupCurrency(GroupCurrencyRequest(groupId, 85))
                .enqueue(object : Callback<GroupCurrencyResponse> {
                    override fun onResponse(
                        call: Call<GroupCurrencyResponse>, response: Response<GroupCurrencyResponse>
                    ) {

                        val currencyResponse = response.body()

                        if (currencyResponse != null) {
                            if (currencyResponse.code == 200) {
                                OASystem.currency.clear()

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

                                currencyInit = true

                                initViews()
                                initEvents()

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

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

        } else {
            initViews()
            initEvents()
        }
    }

    private fun getAirplaneTicketPaymentList(type: Int) {

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

        if (!listInit) {
            apiService.getGroupAirplaneTicketListItem(airplaneTicketListRequest)
                .enqueue(object : Callback<AirplaneTicketListResponse> {
                    override fun onResponse(
                        call: Call<AirplaneTicketListResponse>,
                        response: Response<AirplaneTicketListResponse>
                    ) {

                        val airplaneTicketListResponse = response.body()

                        if (airplaneTicketListResponse != null) {
                            if (airplaneTicketListResponse.code == 200) {
                                for (item in airplaneTicketListResponse.data.airData.dataList) {
                                    airplaneTicketList.add(item)
                                }

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

                                when (type) {
                                    1 -> {
                                        totalPage = getTotalPage(
                                            airplaneTicketListResponse.data.airData.dataCount,
                                            airplaneTicketListResponse.data.airData.currPageSize
                                        )
                                        binding.airplaneTicketPaymentContainer.setEnableLoadMore(
                                            pageIndex < totalPage
                                        )
                                        initList()
                                        listInit = true
                                    }

                                    2 -> {
                                        binding.airplaneTicketPaymentContainer.finishRefresh()
                                        totalPage = getTotalPage(
                                            airplaneTicketListResponse.data.airData.dataCount,
                                            airplaneTicketListResponse.data.airData.currPageSize
                                        )
                                        binding.airplaneTicketPaymentContainer.setEnableLoadMore(
                                            pageIndex < totalPage
                                        )
                                        initList()
                                        listInit = true
                                    }

                                    3 -> {
                                        binding.airplaneTicketPaymentContainer.finishLoadMore()
                                        binding.airplaneTicketPaymentContainer.setEnableLoadMore(
                                            pageIndex < totalPage
                                        )
                                        binding.airplaneTicketPaymentList.adapter!!.notifyItemInserted(
                                            airplaneTicketList.size
                                        )
                                        listInit = true
                                    }
                                }
                            } else {
                                showMessage(airplaneTicketListResponse.msg)
                            }
                        }
                    }

                    override fun onFailure(call: Call<AirplaneTicketListResponse>, t: Throwable) {
                        showErrorInfo(R.string.airplane_ticket_list_get_failed)
                    }
                })
        } else {
            if (OASystem.needRefresh) {
                pageIndex = 1
                airplaneTicketListRequest.pageIndex = pageIndex
                airplaneTicketList.clear()
                listInit = false
                getAirplaneTicketPaymentList(2)
            }
        }
    }

    private fun getTotalPage(dataCount: Int, pageSize: Int): Int {
        var totalPage = dataCount / pageSize
        if (dataCount % pageSize != 0) {
            totalPage++
        }

        return totalPage
    }

    private fun initList() {

        binding.airplaneTicketPaymentList.layoutManager = LinearLayoutManager(OASystem.context)

        val adapter = CardAdapter.Builder<GroupAirplaneTicketListItem>().apply {
            setLayoutId(R.layout.item_group_airplane_ticket)
            setData(airplaneTicketList)
            setCanDelete(OASystem.authorization(OASystem.AIRPLANE_PAYMENT_INSERT, OASystem.DELETE))
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.flight_code).text = data.flightsCode
                itemView.findViewById<TextView>(R.id.service_car_tel).text = data.cTypeName
                itemView.findViewById<TextView>(R.id.members).text = data.clientNum.toString()
                itemView.findViewById<TextView>(R.id.flight_city).text = data.flightsCity
                itemView.findViewById<TextView>(R.id.take_off_time).text = String.format(
                    resources.getString(R.string.with_space_format),
                    data.flightsDate,
                    data.flightsTime
                )

                for (item in OASystem.currency) {
                    if (item.currencyId == data.preCurrency) {
                        itemView.findViewById<TextView>(R.id.ticket_unit_price).text =
                            String.format(
                                resources.getString(R.string.currency_name_code_format),
                                data.prePrice.toString(),
                                item.currencyCode
                            )
                    }

                    if (item.currencyId == data.currency) {
                        itemView.findViewById<TextView>(R.id.total_price).text = String.format(
                            resources.getString(R.string.currency_name_code_format),
                            data.price.toString(),
                            item.currencyCode
                        )
                    }
                }

                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.airplaneTicketPaymentList.adapter = adapter

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

                            putExtra("isAuditGM", airplaneTicketList[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),
                                airplaneTicketList[position].flightsCode
                            )
                        )
                        setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                            dialog.dismiss()
                        }
                        setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                            deleteAirplaneTicket(position)
                        }
                    }.show()
                }
            }

        binding.airplaneTicketPaymentContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                airplaneTicketListRequest.pageIndex = pageIndex
                airplaneTicketList.clear()
                listInit = false
                getAirplaneTicketPaymentList(2)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (pageIndex < totalPage) {
                    pageIndex += 1
                    airplaneTicketListRequest.pageIndex = pageIndex
                    listInit = false
                    getAirplaneTicketPaymentList(3)
                }
            }
        })
    }

    private fun deleteAirplaneTicket(position: Int) {
        apiService.deleteAirplaneTicket(DeleteRequest(airplaneTicketList[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) {

                            airplaneTicketList.removeAt(position)
                            binding.airplaneTicketPaymentList.adapter!!.notifyItemRemoved(position)
                            binding.airplaneTicketPaymentList.adapter!!.notifyItemRangeRemoved(
                                position, airplaneTicketList.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)
                }
            })
    }
}