package com.pan_american.android.ui.announcement

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.BaseResponse
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.entity.RequestCodeBean
import com.pan_american.android.data.model.message.entity.MessageDetail
import com.pan_american.android.data.model.message.network.MessageChangeStateRequest
import com.pan_american.android.data.model.message.network.MessageListRequest
import com.pan_american.android.data.model.message.network.MessageListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentAnnouncementBinding
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 org.greenrobot.eventbus.EventBus
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class AnnouncementFragment : BaseFragment<FragmentAnnouncementBinding>() {

    companion object {
        const val ANNOUNCEMENT_NOTIFICATION = 1022
    }

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

    private lateinit var messageListRequest: MessageListRequest

    private var haveUnread = 0

    private var pageIndex = 1

    private var totalPage = 0

    private var messageList = ArrayList<MessageDetail>()

    private var listInit = false

    private var isUnRead = true

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

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

        if (listInit) {
            if (isUnRead) {
                messageListRequest.readStatus = 2
            } else {
                messageListRequest.readStatus = 3
            }
        } else {
            haveUnread = if (OASystem.announcementUnReadCount > 0) {
                2
            } else {
                3
            }

            messageListRequest = MessageListRequest(ANNOUNCEMENT_NOTIFICATION, haveUnread)
        }

        initViews()
        initEvents()
    }

    override fun initViews() {

        messageListRequest.pageIndex = pageIndex
        messageListRequest.pageSize = 10

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

        if (OASystem.announcementUnReadCount == 0) {
            binding.read.isChecked = true
        }

        getMessage(1)

    }

    override fun initEvents() {
        binding.messageSwitch.setOnCheckedChangeListener { radioGroup, i ->

            if (radioGroup.id == binding.messageSwitch.id) {
                when (i) {
                    binding.unread.id -> {
                        binding.unread.isChecked = true
                        messageListRequest.readStatus = 2
                        isUnRead = true
                        refreshMessageList()
                    }

                    binding.read.id -> {
                        binding.read.isChecked = true
                        messageListRequest.readStatus = 3
                        isUnRead = false
                        refreshMessageList()
                    }
                }
            }
        }
    }

    private fun getMessage(type: Int) {

        if (!listInit) {
            apiService.getMessageList(messageListRequest)
                .enqueue(object : Callback<MessageListResponse> {
                    override fun onResponse(
                        call: Call<MessageListResponse>, response: Response<MessageListResponse>
                    ) {
                        val messageListResponse = response.body()

                        if (messageListResponse != null) {
                            if (messageListResponse.code == 200) {
                                for (item in messageListResponse.data) {
                                    var operatedStr = ""
                                    item.content.split("\n").apply {
                                        for (str in this) {
                                            str.trim()
                                            operatedStr += str.replace("<br/>", "")
                                        }
                                    }
                                    item.content = operatedStr
                                    messageList.add(item)
                                }

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

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

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

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

                    override fun onFailure(call: Call<MessageListResponse>, t: Throwable) {
                        showMessage(resources.getString(R.string.network_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.messageList.layoutManager = layoutManager

        val adapter = ListAdapter.Builder<MessageDetail>().apply {
            setData(messageList)
            setLayoutId(R.layout.item_message_list)
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.title).text = data.title
                itemView.findViewById<TextView>(R.id.branch_name).text = data.issuerDep
                itemView.findViewById<TextView>(R.id.publisher).text = data.issuerUser
                itemView.findViewById<TextView>(R.id.publish_time).text = data.releaseTime

                when (data.isRead) {
                    0 -> {
                        itemView.findViewById<ImageView>(R.id.unread_hint).visibility = View.VISIBLE
                    }

                    1 -> {
                        itemView.findViewById<ImageView>(R.id.unread_hint).visibility = View.GONE
                    }
                }
            }
        }.create()

        binding.messageList.adapter = adapter

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

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

                    showPopupWindow {
                        val title: TextView = popView.findViewById(R.id.title)
                        val branchName: TextView = popView.findViewById(R.id.branch_name)
                        val publisher: TextView = popView.findViewById(R.id.publisher)
                        val content: TextView = popView.findViewById(R.id.message_content)
                        val publishTime: TextView = popView.findViewById(R.id.publish_time)
                        val commitRead: TextView = popView.findViewById(R.id.commit_read)

                        messageList[position].apply {
                            title.text = this.title
                            branchName.text = issuerDep
                            publisher.text = issuerUser
                            content.text = this.content
                            publishTime.text = releaseTime

                            if (isRead == 1) {
                                commitRead.text = resources.getText(R.string.back)
                            }
                        }

                        commitRead.setOnClickListener {
                            when (messageList[position].isRead) {
                                1 -> {
                                    popupWindow.dismiss()
                                }

                                0 -> {
                                    changeReadState(position)
                                }
                            }
                        }

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

        binding.messageListContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                refreshMessageList()
            }

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

    private fun changeReadState(position: Int) {
        apiService.changeMessageState(MessageChangeStateRequest(messageList[position].id))
            .enqueue(object : Callback<BaseResponse> {
                override fun onResponse(
                    call: Call<BaseResponse>, response: Response<BaseResponse>
                ) {

                    val stateChangeResponse = response.body()

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

                            OASystem.announcementUnReadCount -= 1

                            refreshMessageList()

                            EventBus.getDefault().post(RequestCodeBean(OASystem.REFRESH_NAVIGATION))

                            popupWindow.dismiss()

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

                override fun onFailure(call: Call<BaseResponse>, t: Throwable) {
                    showMessage(resources.getString(R.string.network_error))
                }
            })
    }

    private fun refreshMessageList() {
        pageIndex = 1
        messageListRequest.pageIndex = pageIndex
        messageList.clear()
        listInit = false
        getMessage(2)
    }

}