package com.pan_american.android.ui.personnel_module.materials_operate

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
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.ListAdapter
import com.pan_american.android.data.model.common.entity.SimpleGroupInfo
import com.pan_american.android.data.model.common.network.SimpleGroupInfoRequest
import com.pan_american.android.data.model.common.network.SimpleGroupInfoResponse
import com.pan_american.android.data.model.personnel_module.materials_operate.network.MaterialApplicationRequest
import com.pan_american.android.data.model.personnel_module.materials_operate.network.MaterialApplicationResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityMaterialApplicationBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import com.pan_american.android.util.CommitButton
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 MaterialApplicationActivity : BaseActivity<ActivityMaterialApplicationBinding>() {

    private var materialId = 0

    private var materialTypeId = 0

    private var associateGroupId = 0

    private lateinit var titleBinding: LayoutTitleBinding

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

    private val simpleGroupInfoRequest = SimpleGroupInfoRequest()

    private val simpleGroupInfoList = ArrayList<SimpleGroupInfo>()

    private val materialApplicationRequest = MaterialApplicationRequest()

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

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

        intent.apply {
            binding.materialName.text = getStringExtra("material_name")
            materialId = getIntExtra("material_id", 0)
            binding.materialType.text = getStringExtra("material_type_name")
            materialTypeId = getIntExtra("material_type_id", 0)
            binding.materialCount.text = getDoubleExtra("material_count", 0.0).toString()
        }

        initTitle()
        initViews()
        initEvents()
    }

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

            backButton.setOnClickListener {
                back()
            }
        }
    }

    override fun initViews() {
        binding.commit.setText(resources.getString(R.string.confirm))
    }

    override fun initEvents() {
        binding.associationGroup.setOnClickListener {
            simpleGroupInfoRequest.apply {
                pageIndex = 1
                pageSize = 10
                search = ""
            }

            simpleGroupInfoList.clear()

            getSimpleGroupInfoResource(1)
        }

        binding.commit.setOnClickListener {

            if (binding.associationGroup.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.group_select_hint))
                return@setOnClickListener
            }

            if (binding.materialApplicationCount.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.application_count_input_hint))
                return@setOnClickListener
            }

            if (binding.materialCount.text.toString().toDouble() < binding.materialApplicationCount.text.toString().toDouble()) {
                showMessage(resources.getString(R.string.material_count_error))
                return@setOnClickListener
            }

            if (binding.applicationReason.getText().isBlank()) {
                showMessage(resources.getString(R.string.application_reason_input_hint))
                return@setOnClickListener
            }

            if (binding.remark.getText().isBlank()) {
                showMessage(resources.getString(R.string.remark_input_hint))
                return@setOnClickListener
            }

            binding.commit.setButtonStatus(CommitButton.STATUS_IN_COMMITING)

            materialApplicationRequest.apply {
                groupId = associateGroupId
                goodsId = materialId
                quantity = binding.materialApplicationCount.text.toString().toDouble()
                reason = binding.applicationReason.getText()
                remark = binding.remark.getText()
            }

            materialApplicationOperate()
        }
    }

    private fun getSimpleGroupInfoResource(type: Int) {
        apiService.getGroupNameWithSearch(simpleGroupInfoRequest).enqueue(object :
            Callback<SimpleGroupInfoResponse> {
            override fun onResponse(p0: Call<SimpleGroupInfoResponse>, response: Response<SimpleGroupInfoResponse>) {
                val resourceResponse = response.body()

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

                        for (item in resourceResponse.data) {
                            simpleGroupInfoList.add(item)
                        }

                        when(type) {
                            1 -> {
                                val popView = View.inflate(OASystem.context, R.layout.popup_smart_refresh_selector, null)
                                popupWindow = PopupWindow(popView, RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.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)

                                    selectorContainer = popView.findViewById(R.id.selector_refresh_container)
                                    selectorContainer.setEnableRefresh(true)
                                    selectorContainer.setEnableLoadMore(true)

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

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

                                                if (binding.associationGroup.text == data.name) {
                                                    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<SimpleGroupInfo> {
                                            override fun onItemClick(position: Int) {
                                                simpleGroupInfoList[position].apply {
                                                    binding.associationGroup.text = name

                                                    associateGroupId = id

                                                    popupWindow.dismiss()
                                                }
                                            }
                                        }

                                    selectorContainer.setOnRefreshLoadMoreListener(object :
                                        OnRefreshLoadMoreListener {
                                        override fun onRefresh(p0: RefreshLayout) {
                                            simpleGroupInfoRequest.pageIndex = 1

                                            selector.adapter!!.notifyItemRangeRemoved(0, simpleGroupInfoList.size)

                                            simpleGroupInfoList.clear()

                                            getSimpleGroupInfoResource(2)
                                        }

                                        override fun onLoadMore(p0: RefreshLayout) {
                                            simpleGroupInfoRequest.pageIndex += 1

                                            getSimpleGroupInfoResource(3)
                                        }
                                    })

                                    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, simpleGroupInfoList.size)

                                            simpleGroupInfoList.clear()

                                            simpleGroupInfoRequest.apply {
                                                pageIndex = 1
                                                search = editable.toString()
                                            }

                                            getSimpleGroupInfoResource(2)
                                        }
                                    })

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

                                selectorContainer.setEnableLoadMore(simpleGroupInfoRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(0)
                            }

                            2 -> {
                                selectorContainer.finishRefresh()
                                selectorContainer.setEnableLoadMore(simpleGroupInfoRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(0)
                            }

                            3 -> {
                                selectorContainer.finishLoadMore()
                                selectorContainer.setEnableLoadMore(simpleGroupInfoRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(simpleGroupInfoList.size)
                            }
                        }

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

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

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

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

        return pageCount
    }

    private fun materialApplicationOperate() {
        apiService.materialApplicationOperate(materialApplicationRequest).enqueue(object : Callback<MaterialApplicationResponse> {
            override fun onResponse(
                call: Call<MaterialApplicationResponse>,
                response: Response<MaterialApplicationResponse>
            ) {

                val applicationResponse = response.body()

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

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

                        OASystem.needRefresh = true

                        back()

                    } else {
                        showMessage(applicationResponse.msg)

                        binding.commit.setButtonStatus(CommitButton.STATUS_COMMITTED)
                    }
                }
            }

            override fun onFailure(call: Call<MaterialApplicationResponse>, t: Throwable) {
                showErrorInfo(R.string.material_application_error)

                binding.commit.setButtonStatus(CommitButton.STATUS_COMMITTED)
            }
        })
    }
}