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

import android.content.Intent
import android.net.Uri
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 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.CustomAlertDialog
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.entity.GroupListItem
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.GenerateMarketSalesDocumentRequest
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.network.GenerateMarketSalesDocumentResponse
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.network.MarketSalesGroupListResponse
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.FragmentSalesRevenueListBinding
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
import java.util.Calendar

class SalesRevenueListFragment : BaseFragment<FragmentSalesRevenueListBinding>() {

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

    private var isInit = true

    private var listInit = false

    private var year = 0

    private var pageIndex = 1

    private var totalPage = 0

    private val marketSalesStatisticsRequest = MarketSalesStatisticsRequest()

    private val generateMarketSalesDocumentRequest = GenerateMarketSalesDocumentRequest()

    private val groupList = ArrayList<GroupListItem>()

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        bundle: Bundle?
    ) = FragmentSalesRevenueListBinding.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) {
                    marketSalesStatisticsRequest.companyId = id
                }
            }

            marketSalesStatisticsRequest.pageIndex = 1

            marketSalesStatisticsRequest.pageSize = 10

            isInit = false
        }

        initViews()

        initEvents()
    }

    override fun initViews() {
        binding.groupCustomerContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
        binding.groupCustomerContainer.setRefreshFooter(ClassicsFooter(OASystem.context))

        getGroupCustomerList(1)
    }

    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@SalesRevenueListFragment.year = year

                            pageIndex = 1
                            listInit = false
                            marketSalesStatisticsRequest.pageIndex = pageIndex
                            binding.groupCustomerList.adapter!!.notifyItemRangeRemoved(0, groupList.size)
                            groupList.clear()
                            getGroupCustomerList(2)

                            popupWindow.dismiss()
                        }
                    }
                }
            }
        }

        binding.generateDocument.setOnClickListener {

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

                beginDt = "$year-01-01"
                endDt = "$year-12-31"
            }

            apiService.generateMarketSalesGroupListDocument(generateMarketSalesDocumentRequest).enqueue(object : Callback<GenerateMarketSalesDocumentResponse> {
                override fun onResponse(
                    call: Call<GenerateMarketSalesDocumentResponse>,
                    response: Response<GenerateMarketSalesDocumentResponse>
                ) {
                    val urlResponse = response.body()

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

                            CustomAlertDialog.Builder().apply {
                                setTitle(resources.getString(R.string.hint))
                                setMessage(
                                    String.format(
                                        resources.getString(R.string.market_sales_revenue_group_excel_generated),
                                        generateMarketSalesDocumentRequest.beginDt,
                                        generateMarketSalesDocumentRequest.endDt
                                    )
                                )
                                setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                                    dialog.dismiss()
                                }
                                setPositiveButtonAndListener(resources.getString(R.string.confirm)) { dialog, _ ->
                                    val uri = Uri.parse(urlResponse.data.url)
                                    startActivity(Intent(Intent.ACTION_VIEW, uri))

                                    dialog.dismiss()
                                }
                            }.show()

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

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

    private fun getGroupCustomerList(type: Int) {
        if (!isAdded) {
            return
        }

        if (!listInit) {
            marketSalesStatisticsRequest.beginDt = "$year-01-01"
            marketSalesStatisticsRequest.endDt = "$year-12-31"

            apiService.getMarketSalesGroupList(marketSalesStatisticsRequest).enqueue(object : Callback<MarketSalesGroupListResponse> {
                override fun onResponse(
                    request: Call<MarketSalesGroupListResponse>,
                    response: Response<MarketSalesGroupListResponse>
                ) {
                    val listResponse = response.body()

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

                            for (item in listResponse.data) {
                                item.collectionDays = item.collectionDays.substring(0, 10)
                                groupList.add(item)
                            }

                            if (groupList.size == 0) {
                                showMessage(resources.getString(R.string.no_data))
                            } else {
                                binding.generateDocument.visibility = View.VISIBLE
                            }

                            when(type) {
                                1 -> {
                                    totalPage = getTotalPage(listResponse.count)
                                    binding.groupCustomerContainer.setEnableLoadMore(totalPage > pageIndex)
                                    initList()
                                    listInit = true
                                }

                                2 -> {
                                    binding.groupCustomerContainer.finishRefresh()
                                    totalPage = getTotalPage(listResponse.count)
                                    binding.groupCustomerContainer.setEnableLoadMore(pageIndex < totalPage)
                                    initList()
                                    listInit = true
                                }

                                3 -> {
                                    binding.groupCustomerContainer.finishLoadMore()
                                    binding.groupCustomerContainer.setEnableLoadMore(pageIndex < totalPage)
                                    binding.groupCustomerList.adapter!!.notifyItemInserted(
                                        groupList.size
                                    )
                                    listInit = true
                                }
                            }

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

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

    private fun getTotalPage(count: Int): Int {
        var totalPage = count / 10

        if (count % 10 > 0) {
            totalPage += 1
        }

        return totalPage
    }

    private fun initList() {

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

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

        val adapter = ListAdapter.Builder<GroupListItem>().apply {
            setData(groupList)
            setLayoutId(R.layout.item_sales_group_list)
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.group_name).text = data.teamName
                itemView.findViewById<TextView>(R.id.turnover).text = data.groupSales.toString()
                itemView.findViewById<TextView>(R.id.visit_date).text = String.format(resources.getString(R.string.during_format), data.visitDate.substring(0, 10), data.visitEndDate.substring(0, 10))
                itemView.findViewById<TextView>(R.id.group_members).text = data.visitPNumber.toString()
                itemView.findViewById<TextView>(R.id.payment_date).text = data.collectionDays
            }
        }.create()

        binding.groupCustomerList.adapter = adapter

        adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<GroupListItem> {
            override fun onItemClick(position: Int) {

                val intent = Intent(OASystem.context, SalesCustomerVisitListActivity::class.java).apply {
                    putExtra("group_name", groupList[position].teamName)
                    putExtra("id", groupList[position].id)
                }

                startActivity(intent)
            }
        }

        binding.groupCustomerContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                listInit = false
                marketSalesStatisticsRequest.pageIndex = pageIndex
                binding.groupCustomerList.adapter!!.notifyItemRangeRemoved(0, groupList.size)
                groupList.clear()
                getGroupCustomerList(2)
            }

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