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

import android.content.Intent
import android.os.Bundle
import android.view.View
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.BaseActivity
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.customer_resource.market_sales_revenue.entity.VisitHistoryListItem
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.network.MarketSalesVisitHistoryRequest
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.network.MarketSalesVisitHistoryResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivitySalesCustomerVisitListBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import com.pan_american.android.util.ScrollEditText
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 SalesCustomerVisitListActivity : BaseActivity<ActivitySalesCustomerVisitListBinding>() {

    private var groupId = 0

    private lateinit var titleBinding: LayoutTitleBinding

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

    private val marketSalesVisitHistoryRequest = MarketSalesVisitHistoryRequest()

    private var pageIndex = 1

    private var totalPage = 0

    private val historyList = ArrayList<VisitHistoryListItem>()

    override fun getViewBinding() = ActivitySalesCustomerVisitListBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        intent.apply {
            binding.groupName.text = getStringExtra("group_name")
            groupId = getIntExtra("id", 0)
        }

        marketSalesVisitHistoryRequest.apply {
            diId = groupId
            pageIndex = this@SalesCustomerVisitListActivity.pageIndex
            pageSize = 10
        }

        initTitle()
        initViews()
    }

    override fun initTitle() {
        titleBinding = LayoutTitleBinding.bind(binding.root).apply {
            titleText.text = resources.getString(R.string.visit_history)

            addButton.visibility = View.VISIBLE

            addButton.setOnClickListener {
                val intent = Intent(OASystem.context, AddCustomerVisitHistoryActivity::class.java).apply {
                    putExtra("fromList", false)
                    putExtra("diId", groupId)
                }
                startActivity(intent)
            }

            backButton.setOnClickListener {
                back()
            }
        }
    }

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

        getVisitHistoryData(1)
    }

    override fun onStart() {
        super.onStart()

        if (OASystem.needRefresh) {
            pageIndex = 1
            marketSalesVisitHistoryRequest.pageIndex = pageIndex
            binding.visitHistoryList.adapter!!.notifyItemRangeRemoved(0, historyList.size)
            historyList.clear()
            OASystem.needRefresh = false
            getVisitHistoryData(2)
        }
    }

    private fun getVisitHistoryData(type: Int) {

        apiService.getMarketSalesVisitHistory(marketSalesVisitHistoryRequest).enqueue(object : Callback<MarketSalesVisitHistoryResponse> {
            override fun onResponse(
                p0: Call<MarketSalesVisitHistoryResponse>,
                response: Response<MarketSalesVisitHistoryResponse>
            ) {
                val listResponse = response.body()

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

                        for (item in listResponse.data) {
                            item.beginDt = item.beginDt.substring(0, 16)
                            item.endDt = item.endDt.substring(0, 16)
                            historyList.add(item)
                        }

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

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

                            3 -> {
                                binding.visitHistoryContainer.finishLoadMore()
                                binding.visitHistoryContainer.setEnableLoadMore(pageIndex < totalPage)
                                binding.visitHistoryList.adapter!!.notifyItemInserted(historyList.size)
                            }
                        }

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

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

    private fun initList() {
        if (historyList.size == 0) {
            showMessage(resources.getString(R.string.no_data))
            return
        }

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

        val adapter = CardAdapter.Builder<VisitHistoryListItem>().apply {
            setData(historyList)
            setLayoutId(R.layout.item_visit_history_list)
            setCanDelete(OASystem.authorization(OASystem.MARKET_SALES_REVENUE, OASystem.DELETE))
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.client_name).text = data.customerName
                itemView.findViewById<TextView>(R.id.customer_company).text = data.customerUnit
                itemView.findViewById<TextView>(R.id.customer_job_name).text = data.customerJob
                itemView.findViewById<TextView>(R.id.customer_contact_way).text = data.customerContact
                itemView.findViewById<TextView>(R.id.visit_start_time).text = data.beginDt
                itemView.findViewById<TextView>(R.id.visit_end_time).text = data.endDt
                itemView.findViewById<ScrollEditText>(R.id.visit_matter).apply {
                    setText(data.remark)
                    isEnabled(false)
                }
            }
        }.create()

        binding.visitHistoryList.adapter = adapter

        adapter.onRecyclerViewItemClick = object : CardAdapter.OnRecyclerViewItemClick<VisitHistoryListItem> {
            override fun onItemClick(position: Int) {
                val intent = Intent(OASystem.context, AddCustomerVisitHistoryActivity::class.java).apply {
                    putExtra("fromList", true)
                    putExtra("id", historyList[position].id)
                    putExtra("diId", historyList[position].diId)
                    putExtra("customer_name", historyList[position].customerName)
                    putExtra("customer_company", historyList[position].customerUnit)
                    putExtra("customer_job", historyList[position].customerJob)
                    putExtra("customer_contact_way", historyList[position].customerContact)
                    putExtra("start_time", historyList[position].beginDt)
                    putExtra("end_time",historyList[position].endDt)
                    putExtra("remark", historyList[position].remark)
                }

                startActivity(intent)
            }

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

        binding.visitHistoryContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                marketSalesVisitHistoryRequest.pageIndex = pageIndex
                binding.visitHistoryList.adapter!!.notifyItemRangeRemoved(0, historyList.size)
                historyList.clear()
                getVisitHistoryData(2)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (pageIndex < totalPage) {
                    pageIndex += 1
                    marketSalesVisitHistoryRequest.pageIndex = pageIndex
                    getVisitHistoryData(3)
                }
            }
        })
    }

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

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

        return totalPage
    }

    private fun deleteVisitHistoryById(position: Int) {
        apiService.deleteMarketSalesVisitHistory(DeleteRequest(historyList[position].id)).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {

                val deleteResponse = response.body()

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

                        historyList.removeAt(position)
                        binding.visitHistoryList.adapter!!.notifyItemRemoved(position)
                        binding.visitHistoryList.adapter!!.notifyItemRangeChanged(position, historyList.size - position)

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

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

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