package com.pan_american.android.ui.group_op.ground_convey_payment_insert

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView.LayoutParams
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.ListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.common.network.QuerySetDataRequest
import com.pan_american.android.data.model.common.network.SelectorResponse
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.network.GroundConveyDetailRequest
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.network.GroundConveyDetailResponse
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.network.UpdateGroundConveyRequest
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAddGroupOpPaymentBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class AddGroundConveyInfoActivity : BaseActivity<ActivityAddGroupOpPaymentBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private var fromList = false

    private var groupId = 0

    private var paymentId = 0

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

    private var areaList = ArrayList<Selector>()

    private var areaId = -1

    private var regex = Regex("^[\\u4e00-\\u9fa5]*\$")

    private var paymentMarkId = -1

    private var updateGroundConveyRequest = UpdateGroundConveyRequest()

    private var isAuditGM = -1

    private var priceTypeList = ArrayList<Selector>()

    private var priceTypeId = -1

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

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

        intent.apply {
            fromList = getBooleanExtra("fromList", false)
            groupId = getIntExtra("groupId", 0)
            paymentId = getIntExtra("paymentId", 0)
            binding.groupName.text = getStringExtra("teamName")
            binding.groupNumber.text = getStringExtra("tourCode")
            binding.groupCustomer.text = getStringExtra("clientName")
            binding.visitCountry.text = getStringExtra("visitCountry")

            isAuditGM = if (fromList) {
                getIntExtra("isAuditGM", -1)
            } else {
                0
            }
        }

        initTitle()

        initCityResource()
    }

    override fun initTitle() {
        titleBinding = LayoutTitleBinding.bind(binding.root).apply {

            if (fromList) {
                titleText.text = resources.getString(R.string.update_ground_entry_payment)

                rightTextField.visibility = View.VISIBLE
                rightTextField.text = resources.getString(R.string.payment_detail)

                rightTextField.setOnClickListener {
                    val intent = Intent(
                        OASystem.context, GroundConveyPaymentDetailActivity::class.java
                    ).apply {
                        putExtra("groupId", groupId)
                        putExtra("paymentId", paymentId)
                        putExtra("teamName", binding.groupName.text)
                    }

                    startActivity(intent)
                }
            } else {
                titleBinding = LayoutTitleBinding.bind(binding.root).apply {
                    titleText.text = resources.getString(R.string.add_ground_entry_payment)
                }
            }

            backButton.setOnClickListener {
                back()
            }

        }
    }

    override fun initViews() {
        if (fromList) {
            getGroundConveyDetail()

            binding.commit.setText(resources.getString(R.string.update))

            if (!canBeEdit()) {
                binding.apply {
                    paymentName.isEnabled = false
                    area.isEnabled = false
                    serviceStartTime.isEnabled = false
                    serviceEndTime.isEnabled = false
                    serviceCompany.isEnabled = false
                    serviceGuideName.isEnabled = false
                    guidePhone.isEnabled = false
                    serviceCarName.isEnabled = false
                    serviceCarTel.isEnabled = false
                    paymentMark.isEnabled = false
                    carDescription.isEnabled(false)
                    serviceDescription.isEnabled(false)
                    notes.isEnabled(false)

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

    override fun initEvents() {

        binding.area.setOnClickListener {

            val selectorList = ArrayList<Selector>()

            for (item in areaList) {
                selectorList.add(item)
            }

            val popView = View.inflate(OASystem.context, R.layout.popup_selector, null)
            popupWindow = PopupWindow(popView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)

            showPopupWindow {

                val searchView: LinearLayout = popView.findViewById(R.id.search_view)
                searchView.visibility = View.VISIBLE

                val searchText: EditText = popView.findViewById(R.id.search_text)

                selector = popView.findViewById(R.id.selector_list)

                val layoutManager = LinearLayoutManager(OASystem.context)
                selector.layoutManager = layoutManager

                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(selectorList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text =
                                String.format(
                                    resources.getString(R.string.with_space_format),
                                    data.country,
                                    data.city
                                )

                            if (areaId == data.id) {
                                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<Selector> {
                        override fun onItemClick(position: Int) {
                            selectorList[position].apply {
                                binding.area.text = String.format(
                                    resources.getString(R.string.with_space_format),
                                    country,
                                    city
                                )

                                areaId = id

                                popupWindow.dismiss()
                            }
                        }
                    }

                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(editable: Editable?) {

                        adapter.notifyItemRangeRemoved(0, selectorList.size)

                        selectorList.clear()

                        if (editable.isNullOrBlank()) {

                            for (item in areaList) {
                                selectorList.add(item)
                            }

                        } else {
                            for (i in 0 until areaList.size) {
                                areaList[i].apply {
                                    if (country.contains(editable) || city.contains(
                                            editable
                                        )
                                    ) {
                                        selectorList.add(this)
                                    }
                                }
                            }
                        }

                        if (selectorList.size == 0) {
                            showMessage(resources.getString(R.string.no_data))
                        } else {
                            for (i in 0 until selectorList.size) {
                                adapter.notifyItemInserted(i)
                            }
                        }
                    }
                })

                popupWindow.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
            }
        }

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

                            if (priceTypeId == data.id) {
                                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<Selector> {
                    override fun onItemClick(position: Int) {
                        priceTypeList[position].apply {
                            priceTypeId = id
                            binding.priceType.text = name
                        }

                        popupWindow.dismiss()
                    }
                }
            }
        }

        binding.serviceStartTime.setOnClickListener {
            showDatePicker(
                resources.getString(R.string.consume_date_select_hint), binding.serviceStartTime
            ) {}
        }

        binding.serviceEndTime.setOnClickListener {
            showDatePicker(
                resources.getString(R.string.consume_date_select_hint), binding.serviceEndTime
            ) {}
        }

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

                            if (paymentMarkId == data.id) {
                                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<Selector> {
                        override fun onItemClick(position: Int) {
                            paymentMarkId = OASystem.paymentMark[position].id
                            binding.paymentMark.text = OASystem.paymentMark[position].name

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.commit.setOnClickListener {

            if (!canBeEdit()) {
                back()
                return@setOnClickListener
            }

            updateGroundConveyRequest.id = paymentId
            updateGroundConveyRequest.diId = groupId

            if (binding.paymentName.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.payment_name_input_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyRequest.priceName = binding.paymentName.text.toString()
            }

            if (areaId == -1) {
                showMessage(resources.getString(R.string.area_select_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyRequest.area = areaId.toString()
            }

            if (priceTypeId == -1) {
                showMessage(resources.getString(R.string.price_type_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyRequest.priceType = priceTypeId
            }

            if (binding.serviceStartTime.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.start_time_select_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyRequest.serviceStartTime =
                    binding.serviceStartTime.text.toString()
            }

            if (binding.serviceEndTime.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.end_time_select_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyRequest.serviceEndTime = binding.serviceEndTime.text.toString()
            }

            if (binding.serviceCompany.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.service_company_input_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyRequest.serviceCompany = binding.serviceCompany.text.toString()
            }

            if (binding.serviceGuideName.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.service_guide_name_input_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyRequest.serviceGuide = binding.serviceGuideName.text.toString()
            }

            if (binding.guidePhone.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.service_guide_tel_input_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyRequest.serviceTel = binding.guidePhone.text.toString()
            }

            if (binding.serviceCarName.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.service_car_name_input_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyRequest.busName = binding.serviceCarName.text.toString()
            }

            if (binding.serviceCarTel.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.service_car_tel_input_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyRequest.busTel = binding.serviceCarTel.text.toString()
            }

            if (paymentMarkId == -1) {
                showMessage(resources.getString(R.string.payment_mark_hint))
                return@setOnClickListener
            } else {
                updateGroundConveyRequest.orbitalPrivateTransfer = paymentMarkId
            }

            if (binding.carDescription.getText().isNotBlank()) {
                updateGroundConveyRequest.busDescription = binding.carDescription.getText()
            }

            if (binding.serviceDescription.getText().isNotBlank()) {
                updateGroundConveyRequest.serviceDescription = binding.serviceDescription.getText()
            }

            if (binding.notes.getText().isNotBlank()) {
                updateGroundConveyRequest.remark = binding.notes.getText()
            }

            if (fromList) {
                updateGroundConveyRequest.status = 2
            } else {
                updateGroundConveyRequest.status = 1
            }

            updateGroundConvey()
        }
    }

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

                if (listResponse != null) {
                    if (listResponse.code == 200) {
                        for (item in listResponse.data) {
                            areaList.add(item)
                        }

                        getPriceType()

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

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

    private fun getGroundConveyDetail() {

        apiService.getGroundConveyDetail(GroundConveyDetailRequest(paymentId))
            .enqueue(object : Callback<GroundConveyDetailResponse> {
                override fun onResponse(
                    call: Call<GroundConveyDetailResponse>,
                    response: Response<GroundConveyDetailResponse>
                ) {
                    val detailResponse = response.body()

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

                            updateGroundConveyRequest = detailResponse.data.carTouristGuideGround

                            updateGroundConveyRequest.apply {

                                binding.paymentName.setText(priceName)

                                //匹配旧数据
                                if (area.matches(regex)) {
                                    binding.area.text = area
                                } else {
                                    val selectedAreaId = area.toInt()

                                    for (item in areaList) {
                                        if (selectedAreaId == item.id) {
                                            binding.area.text = String.format(
                                                resources.getString(R.string.with_space_format),
                                                item.country,
                                                item.city
                                            )

                                            areaId = selectedAreaId
                                        }
                                    }
                                }

                                for (item in priceTypeList) {
                                    if (priceType == item.id) {
                                        priceTypeId = item.id
                                        binding.priceType.text = item.name
                                    }
                                }

                                binding.serviceStartTime.text = serviceStartTime
                                binding.serviceEndTime.text = serviceEndTime
                                binding.serviceCompany.setText(serviceCompany)
                                binding.serviceGuideName.setText(serviceGuide)
                                binding.guidePhone.setText(serviceTel)
                                binding.serviceCarName.setText(busName)
                                binding.serviceCarTel.setText(busTel)
                                binding.paymentMark.text =
                                    OASystem.paymentMark[orbitalPrivateTransfer].name

                                paymentMarkId = orbitalPrivateTransfer

                                if (busDescription.isNotBlank()) {
                                    binding.carDescription.setText(busDescription)
                                }

                                if (serviceDescription.isNotBlank()) {
                                    binding.serviceDescription.setText(serviceDescription)
                                }

                                if (remark.isNotBlank()) {
                                    binding.notes.setText(remark)
                                }
                            }
                        } else {
                            showMessage(detailResponse.msg)
                        }
                    }
                }

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

    private fun updateGroundConvey() {

        binding.commit.setButtonStatus(1)

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

                    val baseResponse = response.body()

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

                            OASystem.needRefresh = true

                            back()

                        } else {

                            binding.commit.setButtonStatus(0)

                            showMessage(baseResponse.msg)
                        }
                    }
                }

                override fun onFailure(call: Call<BaseResponse>, t: Throwable) {

                    binding.commit.setButtonStatus(0)

                    showErrorInfo(R.string.update_error)
                }
            })
    }

    private fun canBeEdit(): Boolean {
        return OASystem.authorization(OASystem.GROUND_CONVEY_PAYMENT_INSERT, OASystem.EDIT) and (isAuditGM == 0)
    }

    private fun getPriceType() {
        apiService.querySetData(QuerySetDataRequest(83)).enqueue(object : Callback<SelectorResponse> {
            override fun onResponse(
                call: Call<SelectorResponse>,
                response: Response<SelectorResponse>
            ) {
                val dataSetResponse = response.body()

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

                        for (item in dataSetResponse.data) {
                            priceTypeList.add(item)
                        }

                        initViews()

                        initEvents()

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

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