package com.pan_american.android.ui.group_invite_official.invite_official_payment_insert

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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.CardAdapter
import com.pan_american.android.base.CustomAlertDialog
import com.pan_american.android.data.model.common.network.DeleteRequest
import com.pan_american.android.data.model.group_invite_official.invite_official_payment_insert.entity.InviteOfficialListItem
import com.pan_american.android.data.model.group_invite_official.invite_official_payment_insert.network.InviteOfficialListRequest
import com.pan_american.android.data.model.group_invite_official.invite_official_payment_insert.network.InviteOfficialListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentGroupInvitePaymentListBinding
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 GroupInvitePaymentListFragment : BaseFragment<FragmentGroupInvitePaymentListBinding>() {

    private var isShow = false

    private var groupId = 0

    private var tourCode = ""

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

    private var inviteOfficialList = ArrayList<InviteOfficialListItem>()

    private lateinit var inviteOfficialListRequest: InviteOfficialListRequest

    private var pageIndex = 1

    private var totalPage = 0

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

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

        requireArguments().apply {
            groupId = getInt("groupId")
            binding.groupName.text = getString("teamName")
            tourCode = getString("tourCode", "")
            binding.groupCustomer.text = getString("clientName")
            binding.visitCountry.text = getString("visitCountry")
            binding.visitDays.text = getString("visitDays")
            binding.visitMembers.text = getString("visitPNumber")
            binding.duringTime.text = getString("duringTime")
        }

        initViews()
        initEvents()
    }

    override fun initViews() {

        if (OASystem.authorization(OASystem.INVITE_OFFICIAL_PAYMENT, OASystem.ADD)) {
            binding.addPaymentItem.apply {

                visibility = View.VISIBLE

                setOnClickListener {
                    val intent =
                        Intent(OASystem.context, AddInvitePaymentActivity::class.java).apply {
                            putExtra("groupId", groupId)
                            putExtra("teamName", binding.groupName.text)
                            putExtra("tourCode", tourCode)
                            putExtra("clientName", binding.groupCustomer.text)
                            putExtra("visitCountry", binding.visitCountry.text)
                        }
                    startActivity(intent)
                }
            }
        }

        inviteOfficialListRequest = InviteOfficialListRequest(groupId, "", "", "", pageIndex, 10)

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

        initInviteOfficialList(1)
    }

    override fun onStart() {
        super.onStart()

        if (OASystem.needRefresh) {
            pageIndex = 1
            inviteOfficialListRequest.pageIndex = pageIndex
            inviteOfficialList.clear()
            OASystem.needRefresh = false
            initInviteOfficialList(2)
        }
    }

    override fun initEvents() {
        binding.baseInfoSwitch.setOnClickListener {
            if (isShow) {
                binding.groupBaseInfo.visibility = View.GONE
                binding.baseInfoSwitch.text = resources.getString(R.string.show)
                isShow = false
            } else {
                binding.groupBaseInfo.visibility = View.VISIBLE
                binding.baseInfoSwitch.text = resources.getString(R.string.hide)
                isShow = true
            }
        }

        binding.paymentSiftClear.setOnClickListener {
            binding.invitee.setText("")
            binding.inviteStartTime.text = ""
            binding.inviteEndTime.text = ""
        }

        binding.inviteStartTime.setOnClickListener {
            showDatePicker(resources.getString(R.string.start_date), binding.inviteStartTime)
        }

        binding.inviteEndTime.setOnClickListener {
            showDatePicker(resources.getString(R.string.end_date), binding.inviteEndTime)
        }

        binding.commit.setOnClickListener {
            if (binding.invitee.text.trim().isNotEmpty()) {
                inviteOfficialListRequest.inviter = binding.invitee.text.toString()
            } else {
                inviteOfficialListRequest.inviter = ""
            }

            if (binding.inviteStartTime.text.isNotEmpty()) {
                inviteOfficialListRequest.startInviteTime = binding.inviteStartTime.text.toString()
            } else {
                inviteOfficialListRequest.startInviteTime = ""
            }

            if (binding.inviteEndTime.text.isNotEmpty()) {
                inviteOfficialListRequest.endInviteTime = binding.inviteEndTime.text.toString()
            } else {
                inviteOfficialListRequest.endInviteTime = ""
            }

            if (binding.inviteStartTime.text.trim()
                    .isNotEmpty() && binding.inviteEndTime.text.trim().isEmpty()
            ) {
                showMessage(resources.getString(R.string.end_date_select_hint))
                return@setOnClickListener
            }

            if (binding.inviteStartTime.text.trim().isEmpty() && binding.inviteEndTime.text.trim()
                    .isNotEmpty()
            ) {
                showMessage(resources.getString(R.string.start_date_select_hint))
                return@setOnClickListener
            }

            pageIndex = 1

            inviteOfficialListRequest.pageIndex = 1

            inviteOfficialList.clear()

            initInviteOfficialList(1)
        }
    }

    private fun initInviteOfficialList(type: Int) {

        //避免Fragment not attached to a context.
        if (!isAdded) {
            return
        }

        apiService.getInviteOfficialListItem(inviteOfficialListRequest)
            .enqueue(object : Callback<InviteOfficialListResponse> {
                override fun onResponse(
                    call: Call<InviteOfficialListResponse>,
                    response: Response<InviteOfficialListResponse>
                ) {
                    val inviteOfficialListResponse = response.body()

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

                            for (item in inviteOfficialListResponse.data.dataList) {
                                inviteOfficialList.add(item)
                            }

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

                            when (type) {
                                1 -> {
                                    totalPage = getTotalPage(
                                        inviteOfficialListResponse.data.dataCount,
                                        inviteOfficialListResponse.data.currPageSize
                                    )
                                    binding.invitePaymentContainer.setEnableLoadMore(pageIndex < totalPage)
                                    initList()
                                }

                                2 -> {
                                    binding.invitePaymentContainer.finishRefresh()
                                    totalPage = getTotalPage(
                                        inviteOfficialListResponse.data.dataCount,
                                        inviteOfficialListResponse.data.currPageSize
                                    )
                                    binding.invitePaymentContainer.setEnableLoadMore(pageIndex < totalPage)
                                    initList()
                                }

                                3 -> {
                                    binding.invitePaymentContainer.finishLoadMore()
                                    binding.invitePaymentContainer.setEnableLoadMore(pageIndex < totalPage)
                                    binding.invitePaymentList.adapter!!.notifyItemInserted(
                                        inviteOfficialList.size
                                    )
                                }
                            }
                        } else {
                            showMessage(inviteOfficialListResponse.msg)
                        }
                    }
                }

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

            })
    }

    private fun getTotalPage(dataCount: Int, pageSize: Int): Int {
        var totalPage = dataCount / pageSize
        if (dataCount % pageSize != 0) {
            totalPage++
        }

        return totalPage
    }

    private fun initList() {

        val layoutManager = LinearLayoutManager(OASystem.context)
        binding.invitePaymentList.layoutManager = layoutManager

        val adapter = CardAdapter.Builder<InviteOfficialListItem>().apply {
            setLayoutId(R.layout.item_group_invite_payment)
            setData(inviteOfficialList)
            setCanDelete(OASystem.authorization(OASystem.INVITE_OFFICIAL_PAYMENT, OASystem.DELETE))
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.invitee_name).text = data.inviter
                itemView.findViewById<TextView>(R.id.invitee_area).text = data.inviterArea
                itemView.findViewById<TextView>(R.id.invite_payment).text = String.format(
                    resources.getString(R.string.currency_name_code_format),
                    data.inviteCost.toString(),
                    data.inviteCurrency
                )
                itemView.findViewById<TextView>(R.id.express_fee).text = String.format(
                    resources.getString(R.string.currency_name_code_format),
                    data.sendCost.toString(),
                    data.sendCurrency
                )
                itemView.findViewById<TextView>(R.id.translate_payment).text = String.format(
                    resources.getString(R.string.currency_name_code_format),
                    data.translateCost.toString(),
                    data.translateCurrency
                )
                itemView.findViewById<TextView>(R.id.activity_payment).text = String.format(
                    resources.getString(R.string.price_and_currency_format),
                    data.eventsCost,
                    data.eventsCurrency
                )
                itemView.findViewById<TextView>(R.id.payment_total).text = String.format(
                    resources.getString(R.string.price_and_currency_format),
                    data.payMoney,
                    data.paymentCurrency
                )

                when (data.isGoOfficaiaBussiness) {
                    0 -> {
                        itemView.findViewById<TextView>(R.id.is_attend).text =
                            resources.getString(R.string.no)
                    }

                    1 -> {
                        itemView.findViewById<TextView>(R.id.is_attend).text =
                            resources.getString(R.string.yes)
                    }
                }

                when (data.isAudit) {
                    0 -> {
                        itemView.findViewById<TextView>(R.id.is_verify).apply {
                            text = resources.getString(R.string.verify_wait)
                            setTextColor(Color.rgb(23, 171, 227))
                        }
                    }

                    1 -> {
                        itemView.findViewById<TextView>(R.id.is_verify).apply {
                            text = resources.getString(R.string.verify_passed)
                            setTextColor(Color.rgb(84, 213, 77))
                        }
                    }

                    2 -> {
                        itemView.findViewById<TextView>(R.id.is_verify).apply {
                            text = resources.getString(R.string.verify_rejected)
                            setTextColor(Color.rgb(210, 45, 34))
                        }
                    }

                    3 -> {
                        itemView.findViewById<TextView>(R.id.is_verify).text =
                            resources.getString(R.string.auto_verify)
                    }
                }

                itemView.findViewById<TextView>(R.id.invite_time).text =
                    data.inviteTime.substring(0, 10)
            }
        }.create()

        binding.invitePaymentList.adapter = adapter

        adapter.onRecyclerViewItemClick =
            object : CardAdapter.OnRecyclerViewItemClick<InviteOfficialListItem> {
                override fun onItemClick(position: Int) {
                    val intent =
                        Intent(OASystem.context, AddInvitePaymentActivity::class.java).apply {
                            putExtra("fromList", true)
                            putExtra("groupId", groupId)
                            putExtra("paymentId", inviteOfficialList[position].id)
                            putExtra("teamName", binding.groupName.text)
                            putExtra("tourCode", tourCode)
                            putExtra("clientName", binding.groupCustomer.text)
                            putExtra("visitCountry", binding.visitCountry.text)

                            putExtra("currency", inviteOfficialList[position].currency)

                            putExtra("isAudit", inviteOfficialList[position].isAudit)
                        }
                    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),
                                inviteOfficialList[position].inviter
                            )
                        )
                        setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                            dialog.dismiss()
                        }
                        setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                            deleteOfficialPayment(position)
                        }
                    }.show()
                }
            }

        binding.invitePaymentContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                inviteOfficialListRequest.pageIndex = pageIndex
                binding.invitePaymentList.adapter!!.notifyItemRangeRemoved(0, inviteOfficialList.size)
                inviteOfficialList.clear()
                initInviteOfficialList(2)
            }

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

    private fun deleteOfficialPayment(position: Int) {
        apiService.deleteOfficialPayment(DeleteRequest(inviteOfficialList[position].id))
            .enqueue(object : Callback<BaseResponse> {
                override fun onResponse(
                    call: Call<BaseResponse>, response: Response<BaseResponse>
                ) {
                    val baseResponse = response.body()
                    if (baseResponse != null) {
                        if (baseResponse.code == 200) {
                            inviteOfficialList.removeAt(position)
                            binding.invitePaymentList.adapter!!.notifyItemRemoved(position)
                            binding.invitePaymentList.adapter!!.notifyItemRangeChanged(position, inviteOfficialList.size - position)

                            showMessage(resources.getString(R.string.delete_success))
                        } else {
                            showMessage(baseResponse.msg)
                        }
                    }
                }

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