package com.pan_american.android.ui.financial_module.collection_bill

import android.content.Intent
import android.net.Uri
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.base.ListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.common.entity.SimpleGroupInfo
import com.pan_american.android.data.model.common.network.DeleteRequest
import com.pan_american.android.data.model.common.network.SelectorResponse
import com.pan_american.android.data.model.financial_module.collection_bill.entity.CollectionBillItem
import com.pan_american.android.data.model.financial_module.collection_bill.network.CollectionBillFileDownloadRequest
import com.pan_american.android.data.model.financial_module.collection_bill.network.CollectionBillFileDownloadResponse
import com.pan_american.android.data.model.financial_module.collection_bill.network.CollectionBillGroupDetailPaymentListRequest
import com.pan_american.android.data.model.financial_module.collection_bill.network.CollectionBillGroupDetailPaymentListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityCollectionBillPaymentListBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import com.pan_american.android.util.ScrollEditText
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class CollectionBillPaymentListActivity : BaseActivity<ActivityCollectionBillPaymentListBinding>() {
    private val apiService = ServiceCreator.create<APIService>()

    private var groupId = 0

    private val collectionBillGroupDetailPaymentListRequest =
        CollectionBillGroupDetailPaymentListRequest()

    private val groupInfoSimple = SimpleGroupInfo()

    private var groupSimpleInfoShown = false

    private lateinit var titleBinding: LayoutTitleBinding

    private val collectionBillPaymentList = ArrayList<CollectionBillItem>()

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

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

        intent.apply {
            groupId = getIntExtra("groupId", 0)

            collectionBillGroupDetailPaymentListRequest.diId = groupId
        }

        initTitle()

        getGroupDetailAndPaymentList()
    }

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

            rightTextField.apply {
                visibility = View.VISIBLE
                text = resources.getString(R.string.download)

                setOnClickListener {
                    exportList()
                }
            }

            backButton.setOnClickListener {
                back()
            }
        }
    }

    override fun onResume() {
        super.onResume()

        if (OASystem.needRefresh) {
            binding.groupPaymentList.adapter!!.notifyItemRangeRemoved(0, collectionBillPaymentList.size)

            collectionBillPaymentList.clear()

            getGroupDetailAndPaymentList()

            OASystem.needRefresh = false
        }
    }

    private fun getGroupDetailAndPaymentList() {
        apiService.getGroupDetailAndPaymentList(collectionBillGroupDetailPaymentListRequest)
            .enqueue(object : Callback<CollectionBillGroupDetailPaymentListResponse> {
                override fun onResponse(
                    call: Call<CollectionBillGroupDetailPaymentListResponse>,
                    response: Response<CollectionBillGroupDetailPaymentListResponse>
                ) {
                    val detailResponse = response.body()

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

                            detailResponse.data.apply {
                                groupInfoSimple.also {
                                    groupInfo.apply {
                                        it.id = id
                                        it.name = name
                                        it.clientName = clientName
                                        it.visitPNumber = visitPNumber
                                        it.visitCountry = visitCountry
                                        it.visitDays = visitDays
                                        it.visitStartDate = visitStartDate
                                        it.visitEndDate = visitEndDate
                                        it.tourCode = tourCode

                                        it.teamName = teamName
                                    }
                                }

                                if (groupCollectionStatementData.size > 0) {
                                    for (item in groupCollectionStatementData) {
                                        collectionBillPaymentList.add(item)
                                    }
                                } else {
                                    showMessage(resources.getString(R.string.no_data))
                                }
                            }

                            initViews()

                            initEvents()

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

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

    override fun initViews() {
        groupInfoSimple.apply {
            binding.groupName.text = teamName
            binding.groupCustomer.text = clientName
            binding.visitCountry.text = visitCountry
            binding.visitDays.text = visitDays.toString()
            binding.visitMembers.text = visitPNumber.toString()
            binding.duringTime.text = String.format(
                resources.getString(R.string.during_format),
                visitStartDate.substring(0, 10),
                visitEndDate.substring(0, 10)
            )
        }

        if (OASystem.authorization(OASystem.COLLECTION_BILL, OASystem.ADD)) {
            binding.addPaymentItem.visibility = View.VISIBLE
        }

        initList()
    }

    override fun initEvents() {
        binding.baseInfoSwitch.setOnClickListener {
            if (groupSimpleInfoShown) {
                binding.groupBaseInfo.visibility = View.GONE
                binding.baseInfoSwitch.text = resources.getString(R.string.show)

                groupSimpleInfoShown = false
            } else {
                binding.groupBaseInfo.visibility = View.VISIBLE
                binding.baseInfoSwitch.text = resources.getString(R.string.hide)

                groupSimpleInfoShown = true
            }
        }

        binding.importThreePublicExpense.setOnClickListener {
            importThreePublicExpense()
        }

        binding.addPaymentItem.setOnClickListener {
            val intent = Intent(OASystem.context, AddCollectionBillPaymentActivity::class.java).apply {
                putExtra("fromList", false)
                putExtra("groupId", groupId)
            }
            startActivity(intent)
        }
    }

    private fun initList() {

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

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

        val adapter = CardAdapter.Builder<CollectionBillItem>().apply {
            setData(collectionBillPaymentList)
            setLayoutId(R.layout.item_collcetion_bill_payment)
            setCanDelete(true)
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.price_name).text = data.priceName
                itemView.findViewById<TextView>(R.id.add_mode).text = data.addingModeName
                itemView.findViewById<TextView>(R.id.per_price).text = data.price.toString()
                itemView.findViewById<TextView>(R.id.unit).text = data.unit
                itemView.findViewById<TextView>(R.id.currency).text = data.currencyStr
                itemView.findViewById<TextView>(R.id.rate).text = data.rate.toString()
                itemView.findViewById<TextView>(R.id.count).text = data.count.toString()
                itemView.findViewById<TextView>(R.id.receivables).text = data.itemSumPrice.toString()
                itemView.findViewById<TextView>(R.id.create_time).text = data.createTime
                itemView.findViewById<ScrollEditText>(R.id.notes).apply {
                    isEnabled(false)
                    setText(data.remark)
                }
            }
        }.create()

        binding.groupPaymentList.adapter = adapter

        adapter.onRecyclerViewItemClick = object : CardAdapter.OnRecyclerViewItemClick<CollectionBillItem> {
            override fun onItemClick(position: Int) {
                collectionBillPaymentList[position].apply {
                    val intent = Intent(OASystem.context, AddCollectionBillPaymentActivity::class.java).apply {
                        putExtra("fromList", true)
                        putExtra("groupId", groupId)
                        putExtra("paymentId", id)
                        putExtra("paymentName", priceName)
                        putExtra("paymentMode", addingWay)
                        putExtra("perPrice", price)
                        putExtra("currencyId", currency)
                        putExtra("currencyStr", currencyStr)
                        putExtra("count", count)
                        putExtra("unit", unit)
                        putExtra("exchangeRate", rate)
                        putExtra("remark", remark)
                        putExtra("sumPrice", itemSumPrice)
                    }
                    startActivity(intent)
                }
            }

            override fun onItemDelete(position: Int) {

                collectionBillPaymentList[position].apply {
                    CustomAlertDialog.Builder(OASystem.context).apply {
                        setTitle(resources.getString(R.string.alert))
                        setMessage(String.format(resources.getString(R.string.delete_alert_text), priceName))
                        setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog , _ ->
                            dialog.dismiss()
                        }
                        setPositiveButtonAndListener(resources.getString(R.string.confirm)) { dialog, _ ->

                            deleteCollectionBillItem(id, position)

                            dialog.dismiss()
                        }
                    }.show()
                }
            }
        }
    }

    private fun exportList() {
        apiService.getCollectionBillExportFileList().enqueue(object : Callback<SelectorResponse> {
            override fun onResponse(p0: Call<SelectorResponse>, response: Response<SelectorResponse>) {
                val listResponse = response.body()

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

                        val selectorList = listResponse.data

                        showSelector {
                            val adapter = ListAdapter.Builder<Selector>().apply {
                                setData(selectorList)
                                setLayoutId(R.layout.item_selector)
                                addBindView { itemView, data ->
                                    itemView.findViewById<TextView>(R.id.selector_item_name).text = data.name
                                }
                            }.create()

                            selector.adapter = adapter

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

                                    selectorList[position].apply {
                                        fileDownLoad(groupId, id, name)
                                    }

                                    popupWindow.dismiss()
                                }
                            }
                        }

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

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

    private fun fileDownLoad(groupId: Int, type: Int, typeName: String) {
        apiService.collectionBillFileDownload(CollectionBillFileDownloadRequest(groupId, type)).enqueue(object : Callback<CollectionBillFileDownloadResponse> {
            override fun onResponse(
                call: Call<CollectionBillFileDownloadResponse>,
                response: Response<CollectionBillFileDownloadResponse>
            ) {
                val urlResponse = response.body()

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

                        CustomAlertDialog.Builder(OASystem.context).apply {
                            setTitle(resources.getString(R.string.hint))
                            setMessage(String.format(resources.getString(R.string.document_generated), groupInfoSimple.teamName, typeName))
                            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<CollectionBillFileDownloadResponse>, p1: Throwable) {
                showErrorInfo(R.string.interface_request_error)
            }
        })
    }

    private fun importThreePublicExpense() {
        apiService.importThreePublicExpense(groupId).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(
                call: Call<BaseResponse>,
                response: Response<BaseResponse>
            ) {

                val listResponse = response.body()

                if (listResponse != null) {
                    if (listResponse.code == 200) {
                        showMessage(resources.getString(R.string.three_public_expense_import_success))

                        binding.groupPaymentList.adapter!!.notifyItemRangeRemoved(0, collectionBillPaymentList.size)

                        collectionBillPaymentList.clear()

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

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

    private fun deleteCollectionBillItem(id: Int, position: Int) {
        apiService.deleteCollectionBillItem(DeleteRequest(id = id)).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(p0: Call<BaseResponse>, response: Response<BaseResponse>) {
                val deleteResponse = response.body()

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

                        collectionBillPaymentList.removeAt(position)
                        binding.groupPaymentList.adapter!!.notifyItemRemoved(position)
                        binding.groupPaymentList.adapter!!.notifyItemRangeChanged(position, collectionBillPaymentList.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)
            }
        })
    }
}