package com.pan_american.android.ui.group_op.ground_convey_payment_insert

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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.CustomAlertDialog
import com.pan_american.android.data.model.common.network.DeleteRequest
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.adapter.GroundConveyListAdapter
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.entity.GroundConveyListItem
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.network.GroundConveyListRequest
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.network.GroundConveyListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentGroupOpPaymentListBinding
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 GroundConveyPaymentListFragment : BaseFragment<FragmentGroupOpPaymentListBinding>() {

    private var isShow = false

    private var groupId = 0

    private var tourCode = ""

    private lateinit var groundConveyListRequest: GroundConveyListRequest

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

    private var pageIndex = 1

    private var totalPage = 0

    private var groundConveyPaymentList = ArrayList<GroundConveyListItem>()

    override fun getViewBinding(
        inflater: LayoutInflater, container: ViewGroup?, bundle: Bundle?
    ) = FragmentGroupOpPaymentListBinding.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.GROUND_CONVEY_PAYMENT_INSERT, OASystem.ADD)) {
            binding.addPaymentItem.apply {

                visibility = View.VISIBLE

                setOnClickListener {
                    val intent =
                        Intent(OASystem.context, AddGroundConveyInfoActivity::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)
                }
            }
        }

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

        groundConveyListRequest = GroundConveyListRequest(groupId)

        groundConveyListRequest.pageIndex = pageIndex

        groundConveyListRequest.pageSize = 10

        getGroundConveyPaymentList(1)

    }

    override fun onStart() {
        super.onStart()

        if (OASystem.needRefresh) {
            pageIndex = 1
            groundConveyListRequest.pageIndex = pageIndex
            groundConveyPaymentList.clear()
            OASystem.needRefresh = false
            getGroundConveyPaymentList(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
            }
        }
    }

    private fun getGroundConveyPaymentList(type: Int) {

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

        apiService.getGroundConveyPaymentList(groundConveyListRequest)
            .enqueue(object : Callback<GroundConveyListResponse> {
                override fun onResponse(
                    call: Call<GroundConveyListResponse>,
                    response: Response<GroundConveyListResponse>
                ) {
                    val groundConveyResponse = response.body()

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

                            for (item in groundConveyResponse.data.dataList) {
                                groundConveyPaymentList.add(item)
                            }

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

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

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

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

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

                override fun onFailure(call: Call<GroundConveyListResponse>, t: Throwable) {
                    showErrorInfo(R.string.ground_convey_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() {

        binding.groundConveyPaymentList.layoutManager = LinearLayoutManager(OASystem.context)

        val adapter = GroundConveyListAdapter(groundConveyPaymentList)

        binding.groundConveyPaymentList.adapter = adapter

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

                            putExtra("isAuditGM", groundConveyPaymentList[position].isAuditGM)
                        }
                    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),
                                groundConveyPaymentList[position].area
                            )
                        )
                        setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                            dialog.dismiss()
                        }
                        setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                            deleteGroundConveyPayment(position)
                        }
                    }.show()
                }

                override fun viewPaymentDetail(position: Int) {
                    val intent = Intent(
                        OASystem.context, GroundConveyPaymentDetailActivity::class.java
                    ).apply {
                        putExtra("groupId", groupId)
                        putExtra("paymentId", groundConveyPaymentList[position].id)
                        putExtra("teamName", binding.groupName.text)

                        putExtra("isAuditGM", groundConveyPaymentList[position].isAuditGM)
                    }

                    startActivity(intent)
                }
            }

        binding.groundConveyPaymentContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                groundConveyListRequest.pageIndex = pageIndex
                binding.groundConveyPaymentList.adapter!!.notifyItemRangeRemoved(0, groundConveyPaymentList.size)
                groundConveyPaymentList.clear()
                getGroundConveyPaymentList(2)
            }

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

    private fun deleteGroundConveyPayment(position: Int) {
        apiService.deleteGroundConveyPayment(DeleteRequest(groundConveyPaymentList[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) {
                            groundConveyPaymentList.removeAt(position)
                            binding.groundConveyPaymentList.adapter!!.notifyItemRemoved(position)
                            binding.groundConveyPaymentList.adapter!!.notifyItemRangeChanged(position, groundConveyPaymentList.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)
                }
            })
    }
}