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

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
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.ListAdapter
import com.pan_american.android.data.model.personnel_module.materials_operate.adapter.MaterialListAdapter
import com.pan_american.android.data.model.personnel_module.materials_operate.entity.MaterialListItem
import com.pan_american.android.data.model.personnel_module.materials_operate.entity.MaterialTypeData
import com.pan_american.android.data.model.personnel_module.materials_operate.network.MaterialBaseDataResponse
import com.pan_american.android.data.model.personnel_module.materials_operate.network.MaterialSearchRequest
import com.pan_american.android.data.model.personnel_module.materials_operate.network.MaterialSearchResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityMaterialOperateBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import com.pan_american.android.util.CommitButton
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 MaterialOperateActivity : BaseActivity<ActivityMaterialOperateBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private var isHidden = false

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

    private val materialSearchRequest = MaterialSearchRequest()

    private var materialTypeId = 0

    private var materialTypeSelected = false

    private val materialTypeDetail = ArrayList<MaterialTypeData.SubTypeItem>()

    private val materialList = ArrayList<MaterialListItem>()

    private var pageIndex = 1

    private var totalPage = 0

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

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

        initTitle()

        initViews()

        getMaterialBaseDataSource()
    }

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

//            if (OASystem.authorization(OASystem.MATERIAL_OPERATION, OASystem.ADD)) {
//                rightTextField.visibility = View.VISIBLE
//            }
//
//            rightTextField.text = resources.getString(R.string.add_material)

            rightTextField.visibility = View.VISIBLE

            rightTextField.text = resources.getString(R.string.material_application_history)

            rightTextField.setOnClickListener {
                val intent = Intent(OASystem.context, MaterialApplicationHistoryActivity::class.java)
                startActivity(intent)
            }

            backButton.setOnClickListener {
                back()
            }
        }
    }

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

        binding.materialContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
        binding.materialContainer.setRefreshFooter(ClassicsFooter(OASystem.context))
    }

    override fun onStart() {
        super.onStart()

        if (OASystem.needRefresh) {
            pageIndex = 1
            materialSearchRequest.pageIndex = pageIndex
            binding.materialList.adapter!!.notifyItemRangeRemoved(0, materialList.size)
            materialList.clear()
            OASystem.needRefresh = false
            materialSearch(2)
        }
    }

    private fun getMaterialBaseDataSource() {
        apiService.getMaterialTypeDataResource().enqueue(object : Callback<MaterialBaseDataResponse> {
            override fun onResponse(
                call: Call<MaterialBaseDataResponse>,
                response: Response<MaterialBaseDataResponse>
            ) {

                val dataSourceResponse = response.body()

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

                        OASystem.materialBaseData = dataSourceResponse.data.goodsTypeData

                        materialSearchRequest.apply {
                            pageIndex = 1
                            pageSize = 10
                        }

                        materialSearch(1)

                        initEvents()

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

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

    override fun initEvents() {
        binding.filterSwitch.setOnClickListener {
            if (isHidden) {

                binding.materialFilter.visibility = View.VISIBLE

                binding.filterSwitch.text = resources.getString(R.string.hide)

                isHidden = false

            } else {
                binding.materialFilter.visibility = View.GONE

                binding.filterSwitch.text = resources.getString(R.string.show)

                isHidden = true
            }
        }

        binding.materialType.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<MaterialTypeData>().apply {
                    setData(OASystem.materialBaseData)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            if (data.id == materialTypeId) {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color_blue,
                                        null
                                    )
                                )
                            } else {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color,
                                        null
                                    )
                                )
                            }

                            text = data.name
                        }
                    }
                }.create()

                selector.adapter = adapter

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

                        OASystem.materialBaseData[position].apply {

                            if (materialTypeId != id) {
                                materialTypeId = id

                                binding.materialType.text = name

                                materialTypeDetail.clear()

                                binding.detailType.text = ""
                            }

                            materialTypeSelected = true

                            popupWindow.dismiss()
                        }
                    }
                }
            }
        }

        binding.detailType.setOnClickListener {

            if (materialTypeSelected) {
                val subTypeItem = ArrayList<MaterialTypeData.SubTypeItem>()

                showSelector {
                    val adapter = ListAdapter.Builder<MaterialTypeData.SubTypeItem>().apply {
                        for (item in OASystem.materialBaseData) {
                            if (materialTypeId == item.id) {
                                subTypeItem.clear()

                                subTypeItem.addAll(item.subTypeItems)

                                setData(subTypeItem)
                            }
                        }

                        setLayoutId(R.layout.item_selector)

                        addBindView { itemView, data ->
                            itemView.findViewById<TextView>(R.id.selector_item_name).apply {

                                if (materialTypeDetail.contains(data)) {
                                    setTextColor(
                                        ResourcesCompat.getColor(
                                            resources,
                                            R.color.text_color_blue,
                                            null
                                        )
                                    )
                                } else {
                                    setTextColor(
                                        ResourcesCompat.getColor(
                                            resources,
                                            R.color.text_color,
                                            null
                                        )
                                    )
                                }

                                text = data.name
                            }
                        }
                    }.create()

                    selector.adapter = adapter

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

                            subTypeItem[position].apply {

                                if (materialTypeDetail.contains(this)) {
                                    materialTypeDetail.remove(this)
                                } else {
                                    materialTypeDetail.add(this)
                                }

                                var detailTypeText = ""

                                for (item in materialTypeDetail) {
                                    detailTypeText += item.name
                                    detailTypeText += "\t\t"
                                }

                                binding.detailType.text = detailTypeText.trim()

                                popupWindow.dismiss()
                            }

                        }
                    }
                }
            } else {
                showMessage(resources.getString(R.string.material_type_select_hint))
            }
        }

        binding.commit.setOnClickListener {

            binding.commit.setButtonStatus(CommitButton.STATUS_IN_COMMITING)

            materialList.clear()
            binding.materialList.adapter!!.notifyItemRangeRemoved(0, materialList.size)

            materialSearchRequest.apply {
                pageIndex = 1
                pageSize = 10

                typeIds = ""

                var i = 0

                while (i < materialTypeDetail.size) {

                    typeIds += materialTypeDetail[i].id

                    i += 1

                    if (i < materialTypeDetail.size) {
                        typeIds += ","
                    }
                }

                goodsName = binding.materialName.text.toString()
            }

            materialSearch(1)
        }
    }

    private fun materialSearch(type: Int) {
        apiService.getMaterialList(materialSearchRequest).enqueue(object : Callback<MaterialSearchResponse> {
            override fun onResponse(
                call: Call<MaterialSearchResponse>,
                response: Response<MaterialSearchResponse>
            ) {
                val listResponse = response.body()

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

                        for (item in listResponse.data) {
                            materialList.add(item)
                        }

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

                        when(type) {

                            1 -> {
                                totalPage = getTotalPage(listResponse.count)
                                binding.materialContainer.setEnableLoadMore(pageIndex < totalPage)
                                initList()
                            }

                            2 -> {
                                binding.materialContainer.finishRefresh()
                                totalPage = getTotalPage(listResponse.count)
                                binding.materialContainer.setEnableLoadMore(pageIndex < totalPage)
                                initList()
                            }

                            3 -> {
                                binding.materialContainer.finishLoadMore()
                                binding.materialContainer.setEnableLoadMore(pageIndex < totalPage)
                                binding.materialList.adapter!!.notifyItemInserted(materialList.size)
                            }
                        }
                    } else {
                        showMessage(listResponse.msg)
                    }

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

            override fun onFailure(call: Call<MaterialSearchResponse>, t: Throwable) {
                binding.commit.setButtonStatus(CommitButton.STATUS_COMMITTED)

                showErrorInfo(R.string.material_search_error)
            }
        })
    }

    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.materialList.layoutManager = layoutManager

        val adapter = MaterialListAdapter(materialList)

        binding.materialList.adapter = adapter

        adapter.onItemClickListener = object : MaterialListAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {

            }

            override fun onPutInClick(position: Int) {

            }

            override fun onUseClick(position: Int) {
                val intent = Intent(OASystem.context, MaterialApplicationActivity::class.java).apply {
                    putExtra("material_name", materialList[position].name)
                    putExtra("material_id", materialList[position].id)
                    putExtra("material_type_name", materialList[position].typeName)
                    putExtra("material_type_id", materialList[position].type)
                    putExtra("material_count", materialList[position].stockQuantity)
                }
                startActivity(intent)
            }

            override fun onItemDelete(position: Int) {
//                CustomAlertDialog.Builder().apply {
//                    setTitle(resources.getString(R.string.alert))
//                    setMessage(String.format(resources.getString(R.string.delete_alert_text), materialList[position].name))
//                    setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
//                        dialog.dismiss()
//                    }
//                    setPositiveButtonAndListener(resources.getString(R.string.confirm)) { dialog, _ ->
//
//                    }
//                }.show()
            }
        }

        binding.materialContainer.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                materialSearchRequest.pageIndex = pageIndex
                binding.materialList.adapter!!.notifyItemRangeRemoved(0, materialList.size)
                materialList.clear()
                materialSearch(2)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (pageIndex < totalPage) {
                    pageIndex += 1
                    materialSearchRequest.pageIndex = pageIndex
                    materialSearch(3)
                }
            }
        })
    }
}