package com.pan_american.android.ui.document

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
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.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.network.SelectorResponse
import com.pan_american.android.data.model.document.network.DocumentGroupListRequest
import com.pan_american.android.data.model.document.network.group_airplane_ticket.AirplaneReportFormGenerateRequest
import com.pan_american.android.data.model.document.network.group_airplane_ticket.AirplaneTicketDocumentGenerateResponse
import com.pan_american.android.data.model.document.network.group_airplane_ticket.AirplaneTravelItineraryGenerateRequest
import com.pan_american.android.data.model.document.network.group_hotel.HotelDocumentGenerateRequest
import com.pan_american.android.data.model.document.network.group_hotel.HotelDocumentGenerateResponse
import com.pan_american.android.data.model.document.network.group_management.GroupCustomerListGenerateRequest
import com.pan_american.android.data.model.document.network.group_management.GroupEnterExitCostGenerateRequest
import com.pan_american.android.data.model.document.network.group_management.GroupManagerDocumentGenerateResponse
import com.pan_american.android.data.model.document.network.group_management.GroupReverseTableGenerateRequest
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityDocumentGroupListBinding
import com.pan_american.android.databinding.LayoutTitleBinding
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 DocumentGroupListActivity : BaseActivity<ActivityDocumentGroupListBinding>() {

    lateinit var titleBinding: LayoutTitleBinding

    private var tag = ""

    private var groupNameListRequest = DocumentGroupListRequest()

    private var pageIndex = 1

    private var totalPage = 0

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

    private var listInit = false

    private var groupNameList = ArrayList<Selector>()

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

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

        intent.apply {
            tag = this.getStringExtra("tag").toString()
        }

        initTitle()
        initViews()
    }

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

            searchView.visibility = View.VISIBLE
            searchText.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                }

                override fun afterTextChanged(p0: Editable?) {

                }
            })

            backButton.setOnClickListener {
                back()
            }
        }
    }

    override fun initViews() {

        groupNameListRequest.pageIndex = pageIndex
        groupNameListRequest.pageSize = 10

        binding.groupListContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
        binding.groupListContainer.setRefreshFooter(ClassicsFooter(OASystem.context))

        getGroupList(1)
    }

    private fun getGroupList(type: Int) {

        if (!listInit) {
            apiService.documentGroupList(groupNameListRequest).enqueue(object : Callback<SelectorResponse> {
                override fun onResponse(
                    call: Call<SelectorResponse>,
                    response: Response<SelectorResponse>
                ) {
                    val groupNameListResponse = response.body()
                    if (groupNameListResponse != null) {
                        if (groupNameListResponse.code == 200) {

                            for (item in groupNameListResponse.data) {
                                groupNameList.add(item)
                            }

                            if (groupNameList.size == 0) {
                                showMessage(resources.getString(R.string.no_data))
                            }

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

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

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

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

                override fun onFailure(call: Call<SelectorResponse>, t: Throwable) {
                    showErrorInfo(R.string.group_list_get_failed)
                }
            })
        }
    }

    private fun getTotalPage(dataCount: Int): Int {
        var totalPage = dataCount / 10
        if (dataCount % 10 != 0) {
            totalPage++
        }

        return totalPage
    }

    private fun initList() {

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

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

        binding.groupList.adapter = adapter

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

                    var docTypeName: String
                    var downloadUrl: String

                    when (tag) {
                        //voucher
                        "voucher" -> {
                            apiService.hotelVoucherGenerate(HotelDocumentGenerateRequest(OASystem.HOTEL_PREDETERMINE, groupNameList[position].id)).enqueue(object : Callback<HotelDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<HotelDocumentGenerateResponse>,
                                    response: Response<HotelDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.voucher)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<HotelDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        //确认单
                        "confirmList" -> {
                            apiService.hotelConfirmListGenerate(HotelDocumentGenerateRequest(OASystem.HOTEL_PREDETERMINE, groupNameList[position].id)).enqueue(object : Callback<HotelDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<HotelDocumentGenerateResponse>,
                                    response: Response<HotelDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.hotel_confirm_list)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<HotelDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        //预订成本
                        "predetermineCost" -> {
                            apiService.hotelPredetermineCostGenerate(HotelDocumentGenerateRequest(OASystem.HOTEL_PREDETERMINE, groupNameList[position].id)).enqueue(object : Callback<HotelDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<HotelDocumentGenerateResponse>,
                                    response: Response<HotelDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.hotel_predetermine_cost)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<HotelDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        //机票报表
                        "airplaneReportForm" -> {
                            apiService.airplaneTicketReportFormGenerate(AirplaneReportFormGenerateRequest(groupNameList[position].id)).enqueue(object : Callback<AirplaneTicketDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<AirplaneTicketDocumentGenerateResponse>,
                                    response: Response<AirplaneTicketDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.airplane_report_forms)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<AirplaneTicketDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        //中文行程单
                        "chTravelItinerary" -> {
                            apiService.airplaneTravelItineraryGenerate(AirplaneTravelItineraryGenerateRequest(groupNameList[position].id, "CN")).enqueue(object : Callback<AirplaneTicketDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<AirplaneTicketDocumentGenerateResponse>,
                                    response: Response<AirplaneTicketDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.ch_travel_itinerary)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<AirplaneTicketDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        //英文行程单
                        "enTravelItinerary" -> {
                            apiService.airplaneTravelItineraryGenerate(AirplaneTravelItineraryGenerateRequest(groupNameList[position].id, "EN")).enqueue(object : Callback<AirplaneTicketDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<AirplaneTicketDocumentGenerateResponse>,
                                    response: Response<AirplaneTicketDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.ch_travel_itinerary)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<AirplaneTicketDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        //OP行程单word
                        "opTravelItineraryWord" -> {

                        }

                        //OP行程单pdf
                        "opTravelItineraryPdf" -> {

                        }

                        //接团客户名单（中文版）
                        "groupCustomerListCh" -> {
                            apiService.groupCustomerListGenerate(GroupCustomerListGenerateRequest(groupNameList[position].id, 0)).enqueue(object : Callback<GroupManagerDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    response: Response<GroupManagerDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.group_customer_list_ch)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        //接团客户名单（英文版）
                        "groupCustomerListEn" -> {
                            apiService.groupCustomerListGenerate(GroupCustomerListGenerateRequest(groupNameList[position].id, 1)).enqueue(object : Callback<GroupManagerDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    response: Response<GroupManagerDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.group_customer_list_en)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        //倒推表
                        "reverseTable" -> {
                            apiService.groupReverseTableGenerate(GroupReverseTableGenerateRequest(groupNameList[position].id)).enqueue(object : Callback<GroupManagerDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    response: Response<GroupManagerDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.reverse_table)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        "foundsExamineForm" -> {
                            apiService.groupEnterExitCostGenerate(GroupEnterExitCostGenerateRequest(groupNameList[position].id, 1, 1005)).enqueue(object : Callback<GroupManagerDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    response: Response<GroupManagerDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.founds_examine_form)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        "foundsCalculateForm" -> {
                            apiService.groupEnterExitCostGenerate(GroupEnterExitCostGenerateRequest(groupNameList[position].id, 1, 1006)).enqueue(object : Callback<GroupManagerDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    response: Response<GroupManagerDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.founds_calculate_form)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        "provinceExamineForm" -> {
                            apiService.groupEnterExitCostGenerate(GroupEnterExitCostGenerateRequest(groupNameList[position].id, 1, 1007)).enqueue(object : Callback<GroupManagerDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    response: Response<GroupManagerDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.province_examine_form)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        "cityExamineForm" -> {
                            apiService.groupEnterExitCostGenerate(GroupEnterExitCostGenerateRequest(groupNameList[position].id, 1, 1066)).enqueue(object : Callback<GroupManagerDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    response: Response<GroupManagerDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.city_examine_form)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        "leaveExamineForm" -> {
                            apiService.groupEnterExitCostGenerate(GroupEnterExitCostGenerateRequest(groupNameList[position].id, 2, 1008)).enqueue(object : Callback<GroupManagerDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    response: Response<GroupManagerDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.leave_examine_form)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }

                        "reimbursementForm" -> {
                            apiService.groupEnterExitCostGenerate(GroupEnterExitCostGenerateRequest(groupNameList[position].id, 2, 1009)).enqueue(object : Callback<GroupManagerDocumentGenerateResponse> {
                                override fun onResponse(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    response: Response<GroupManagerDocumentGenerateResponse>
                                ) {
                                    val downloadResponse = response.body()

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

                                            docTypeName = resources.getString(R.string.reimbursement_form)

                                            downloadUrl = downloadResponse.data

                                            showDownloadHintDialog(groupNameList[position].groupName, docTypeName, downloadUrl)

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

                                override fun onFailure(
                                    call: Call<GroupManagerDocumentGenerateResponse>,
                                    t: Throwable
                                ) {
                                    showErrorInfo(R.string.interface_request_error)
                                }
                            })
                        }
                    }
                }
            }

        binding.groupListContainer.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                groupNameListRequest.pageIndex = pageIndex
                groupNameList.clear()
                listInit = false
                getGroupList(2)
            }

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

    private fun showDownloadHintDialog(groupName: String, docType: String, url: String) {
        CustomAlertDialog.Builder(OASystem.context).apply {
            setTitle(resources.getString(R.string.hint))
            setMessage(String.format(resources.getString(R.string.document_generated), groupName, docType))
            setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                dialog.dismiss()
            }
            setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                val uri = Uri.parse(url)
                startActivity(Intent(Intent.ACTION_VIEW, uri))
            }
            setCancelable(false)
        }.show()
    }
}