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

import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupWindow
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.BaseFragment
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.personnel_module.materials_operate.entity.MaterialHistoryListItem
import com.pan_american.android.data.model.personnel_module.materials_operate.network.MaterialHistoryListRequest
import com.pan_american.android.data.model.personnel_module.materials_operate.network.MaterialHistoryListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentMaterialHistoryListBinding
import com.pan_american.android.util.CommitButton
import com.pan_american.android.util.ScrollEditText
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 MaterialHistoryListFragment : BaseFragment<FragmentMaterialHistoryListBinding>() {

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

    private val materialHistoryListRequest = MaterialHistoryListRequest()

    private val materialHistoryList = ArrayList<MaterialHistoryListItem>()

    private var pageIndex = 1

    private var totalPage = 0

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        bundle: Bundle?
    ) = FragmentMaterialHistoryListBinding.inflate(inflater, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        requireArguments().apply {
            materialHistoryListRequest.also {
                it.goodsName = getString("material_name").toString()
                it.beginDt = getString("start_time").toString()
                it.endDt = getString("end_time").toString()
                it.groupLabel = getString("group_id").toString()
                it.typeLabel = getString("detail_type").toString()
                it.auditLabel = getString("verify_status").toString()

                it.pageIndex = pageIndex
                it.pageSize = 10
            }
        }

        initViews()
    }

    override fun initViews() {
        binding.materialListContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
        binding.materialListContainer.setRefreshFooter(ClassicsFooter(OASystem.context))
        initMaterialHistoryList(1)
    }

    private fun initMaterialHistoryList(type: Int) {
        apiService.getMaterialHistoryList(materialHistoryListRequest).enqueue(object : Callback<MaterialHistoryListResponse> {
            override fun onResponse(
                call: Call<MaterialHistoryListResponse>,
                response: Response<MaterialHistoryListResponse>
            ) {
                val listResponse = response.body()

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

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

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

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

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

                            3 -> {
                                binding.materialListContainer.finishLoadMore()
                                binding.materialListContainer.setEnableLoadMore(pageIndex < totalPage)
                                binding.materialHistoryList.adapter!!.notifyItemInserted(materialHistoryList.size)
                            }
                        }

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

            override fun onFailure(call: Call<MaterialHistoryListResponse>, t: Throwable) {
                showErrorInfo(R.string.material_application_history_get_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.materialHistoryList.layoutManager = layoutManager

        val adapter = ListAdapter.Builder<MaterialHistoryListItem>().apply {
            setData(materialHistoryList)
            setLayoutId(R.layout.item_material_history)
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.material_name).text = data.goodsName
                itemView.findViewById<TextView>(R.id.material_type).text = data.goodsType
                itemView.findViewById<TextView>(R.id.material_counts).text = data.quantity.toString()
                itemView.findViewById<TextView>(R.id.create_time).text = data.createTime.substring(0, 10)
                itemView.findViewById<TextView>(R.id.verify_status).apply {
                    text = data.auditStatusText

                    when(data.auditStatus) {
                        0 -> {
                            setTextColor(Color.rgb(23, 171, 227))
                            itemView.findViewById<ImageView>(R.id.verify_status_icon).setImageResource(R.mipmap.icon_wait)
                        }

                        1 -> {
                            setTextColor(Color.rgb(84, 213, 77))
                            itemView.findViewById<ImageView>(R.id.verify_status_icon).setImageResource(R.mipmap.icon_passed)
                        }

                        2 -> {
                            setTextColor(Color.rgb(210, 45, 34))
                            itemView.findViewById<ImageView>(R.id.verify_status_icon).setImageResource(R.mipmap.icon_reject)
                        }
                    }
                }
                itemView.findViewById<TextView>(R.id.verify_name).text = data.auditUserName.ifBlank { resources.getString(R.string.no_info) }
                itemView.findViewById<TextView>(R.id.verify_date).text = data.auditTime.substring(0, 10)
            }
        }.create()

        binding.materialHistoryList.adapter = adapter

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

                val detailPopView = View.inflate(OASystem.context, R.layout.popup_material_history, null)
                popupWindow = PopupWindow(detailPopView, ViewGroup.LayoutParams.MATCH_PARENT, binding.root.height * 3 / 4)

                showPopupWindow {
                    val materialName = detailPopView.findViewById<TextView>(R.id.material_name)
                    val materialType = detailPopView.findViewById<TextView>(R.id.material_type)
                    val associationGroup = detailPopView.findViewById<TextView>(R.id.association_group)
                    val materialCount = detailPopView.findViewById<TextView>(R.id.material_application_count)
                    val applicationReason = detailPopView.findViewById<ScrollEditText>(R.id.application_reason)
                    val notes = detailPopView.findViewById<ScrollEditText>(R.id.remark)
                    val commit = detailPopView.findViewById<CommitButton>(R.id.commit)

                    materialHistoryList[position].apply {
                        materialName.text = goodsName
                        materialType.text = goodsType
                        associationGroup.text = groupName
                        materialCount.text = quantity.toString()
                        applicationReason.setText(reason)
                        notes.setText(remark)

                        applicationReason.isEnabled(false)
                        notes.isEnabled(false)
                    }

                    commit.setText(resources.getString(R.string.confirm))

                    commit.setOnClickListener {
                        popupWindow.dismiss()
                    }

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

        binding.materialListContainer.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                materialHistoryListRequest.pageIndex = pageIndex
                binding.materialHistoryList.adapter!!.notifyItemRangeRemoved(0, materialHistoryList.size)
                materialHistoryList.clear()
                initMaterialHistoryList(2)
            }

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