package com.pan_american.android.ui.customer_resource.market_sales_revenue

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import com.bin.david.form.data.style.FontStyle
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.ListAdapter
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.entity.SellerRank
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.entity.YearQuarterlyData
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.network.MarketSalesOrderRankResponse
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.network.MarketSalesStatisticsRequest
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentSalesRevenueRankBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.Calendar

class SalesRevenueRankFragment : BaseFragment<FragmentSalesRevenueRankBinding>() {

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

    private var isInit = true

    private var year = 0

    private var companyId = 0

    private var sellerRank = ArrayList<SellerRank>()

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

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

        if (isInit) {
            val calendar = Calendar.getInstance()

            year = calendar.get(Calendar.YEAR)

            binding.year.text = year.toString()

            for (item in OASystem.marketSalesRevenueCompanyList) {
                if (OASystem.userInfo.companyName == item.name) {
                    companyId = item.id
                }
            }

            getSellerRankData()

            isInit = false
        }

        initEvents()
    }

    override fun initEvents() {
        binding.year.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<YearQuarterlyData>().apply {
                    setData(OASystem.marketSalesRevenueDateList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.year.toString()

                            if (year == data.year) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))

                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<YearQuarterlyData> {
                    override fun onItemClick(position: Int) {
                        OASystem.marketSalesRevenueDateList[position].apply {
                            binding.year.text = year.toString()
                            this@SalesRevenueRankFragment.year = year
                        }

                        sellerRank.clear()

                        getSellerRankData()

                        popupWindow.dismiss()
                    }
                }
            }
        }
    }

    private fun getSellerRankData() {

        if (!isAdded) {
            return
        }

        val marketSalesStatisticsRequest = MarketSalesStatisticsRequest().apply {
            beginDt = "$year-01-01"
            endDt = "$year-12-31"
            companyId = this@SalesRevenueRankFragment.companyId
            groupPickupUserId = -1
            pageIndex = 1
            pageSize = 100
        }

        apiService.getMarketSalesOrderRanking(marketSalesStatisticsRequest).enqueue(object :
            Callback<MarketSalesOrderRankResponse> {
            override fun onResponse(
                call: Call<MarketSalesOrderRankResponse>,
                response: Response<MarketSalesOrderRankResponse>
            ) {
                val rankResponse = response.body()

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

                        for (item in rankResponse.data) {
                            sellerRank.add(item)
                        }

                        if (sellerRank.size == 0) {
                            showMessage(resources.getString(R.string.no_data))
                            sellerRank.add(SellerRank().apply {
                                rowNumber = 1
                                userName = "-"
                                count = 0
                            })
                        }

                        binding.rankTable.config.apply {
                            isShowTableTitle = false
                            isShowXSequence = false
                            isShowYSequence = false
                            minTableWidth = binding.rankTable.width
                            verticalPadding = resources.getDimensionPixelSize(R.dimen.common_padding)
                            columnTitleStyle = FontStyle(resources.getDimensionPixelSize(R.dimen.text_size_large), ResourcesCompat.getColor(resources, R.color.text_color, null))
                            contentStyle = FontStyle(resources.getDimensionPixelSize(R.dimen.text_size_medium), ResourcesCompat.getColor(resources, R.color.text_color, null))
                        }

                        binding.rankTable.apply {
                            setZoom(false)
                            setData(sellerRank)
                        }

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

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