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

import android.os.Bundle
import androidx.core.view.isNotEmpty
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.data.model.customer_resource.market_sales_revenue.network.MarketSalesAddVisitHistoryRequest
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAddCustomerVisitHistoryBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class AddCustomerVisitHistoryActivity : BaseActivity<ActivityAddCustomerVisitHistoryBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private var fromList = false

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

    private val marketSalesAddVisitHistoryRequest = MarketSalesAddVisitHistoryRequest()

    private var startDateSelect = false

    private var startTimeSelect = false

    private var endDateSelect = false

    private var endTimeSelect = false

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

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

        intent.apply {
            fromList = getBooleanExtra("fromList", false)
            marketSalesAddVisitHistoryRequest.diId = getIntExtra("diId", 0)

            if (fromList) {

                marketSalesAddVisitHistoryRequest.id = getIntExtra("id", 0)

                binding.clientName.setText(getStringExtra("customer_name"))
                binding.customerCompany.setText(getStringExtra("customer_company"))
                binding.clientJob.setText(getStringExtra("customer_job"))
                binding.contractWay.setText(getStringExtra("customer_contact_way"))
                binding.visitStartTime.text = getStringExtra("start_time")
                binding.visitEndTime.text = getStringExtra("end_time")
                binding.notes.setText(getStringExtra("remark").toString())

                startDateSelect = true
                startTimeSelect = true
                endDateSelect = true
                endTimeSelect = true
            }
        }

        initTitle()
        initViews()
        initEvents()
    }

    override fun initTitle() {
        titleBinding = LayoutTitleBinding.bind(binding.root).apply {
            titleText.text = if (fromList) {
                resources.getString(R.string.add_visit_history)
            } else {
                resources.getString(R.string.visit_history_detail)
            }

            backButton.setOnClickListener {
                back()
            }
        }
    }

    override fun initViews() {
        if (fromList) {
            if (canBeEdit()) {
                binding.commit.setText(resources.getString(R.string.update))
            } else {

                binding.clientName.isEnabled = false
                binding.customerCompany.isEnabled = false
                binding.clientJob.isEnabled = false
                binding.contractWay.isEnabled = false
                binding.visitStartTime.isEnabled = false
                binding.visitEndTime.isEnabled = false
                binding.notes.isEnabled(false)

                binding.commit.setText(resources.getString(R.string.back))
            }

        } else {
            binding.commit.setText(resources.getString(R.string.add))
        }
    }

    override fun initEvents() {
        binding.visitStartTime.setOnClickListener {
            showDateAndTimePicker(resources.getString(R.string.start_time), binding.visitStartTime)
        }

        binding.visitEndTime.setOnClickListener {
            showDateAndTimePicker(resources.getString(R.string.end_time), binding.visitEndTime)
        }

        binding.commit.setOnClickListener {
            if (!canBeEdit()) {
                back()
                return@setOnClickListener
            }

            if (binding.clientName.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.client_name_hint))
                return@setOnClickListener
            } else {
                marketSalesAddVisitHistoryRequest.customerName = binding.clientName.text.toString()
            }

            if (binding.customerCompany.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.customer_company_hint))
                return@setOnClickListener
            } else {
                marketSalesAddVisitHistoryRequest.customerUnit = binding.customerCompany.text.toString()
            }

            if (binding.clientJob.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.customer_job_hint))
                return@setOnClickListener
            } else {
                marketSalesAddVisitHistoryRequest.customerJob = binding.clientJob.text.toString()
            }

            if (binding.contractWay.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.customer_contact_way_hint))
                return@setOnClickListener
            } else {
                marketSalesAddVisitHistoryRequest.customerContact = binding.contractWay.text.toString()
            }

            if (!startDateSelect || !startTimeSelect) {
                showMessage(resources.getString(R.string.start_time_select_error))
                return@setOnClickListener
            } else {
                marketSalesAddVisitHistoryRequest.beginDt = binding.visitStartTime.text.toString()
            }

            if (!endDateSelect || !endTimeSelect) {
                showMessage(resources.getString(R.string.end_time_select_error))
                return@setOnClickListener
            } else {
                marketSalesAddVisitHistoryRequest.endDt = binding.visitEndTime.text.toString()
            }

            if (binding.notes.isNotEmpty()) {
                marketSalesAddVisitHistoryRequest.remark = binding.notes.getText()
            }

            updateVisitHistory()
        }
    }

    private fun canBeEdit(): Boolean {
        return OASystem.authorization(OASystem.MARKET_SALES_REVENUE, OASystem.EDIT)
    }

    private fun updateVisitHistory() {

        apiService.updateMarketSalesVisitHistory(marketSalesAddVisitHistoryRequest).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(p0: Call<BaseResponse>, response: Response<BaseResponse>) {

                val updateResponse = response.body()

                if (updateResponse != null) {
                    if (updateResponse.code == 200) {
                        if (fromList) {
                            showMessage(resources.getString(R.string.update_success))
                        } else {
                            showMessage(resources.getString(R.string.insert_success))
                        }

                        OASystem.needRefresh = true

                        back()
                    } else {
                        showMessage(updateResponse.msg)
                    }
                }
            }

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