package com.pan_american.android.ui.group_visa.insurance_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.ImageView
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_visa.insurance_payment_insert.entity.InsurancePaymentListItem
import com.pan_american.android.data.model.group_visa.insurance_payment_insert.network.InsurancePaymentListRequest
import com.pan_american.android.data.model.group_visa.insurance_payment_insert.network.InsurancePaymentListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentInsuranceListBinding
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 InsuranceListFragment : BaseFragment<FragmentInsuranceListBinding>() {

    private var isShow = false

    private var groupId = 0

    private var tourCode = ""

    private lateinit var insurancePaymentListRequest: InsurancePaymentListRequest

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

    private var pageIndex = 1

    private var totalPage = 0

    private var insurancePaymentList = ArrayList<InsurancePaymentListItem>()

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

                visibility = View.VISIBLE

                setOnClickListener {
                    val intent =
                        Intent(OASystem.context, AddInsurancePaymentActivity::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.insurancePaymentContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
        binding.insurancePaymentContainer.setRefreshFooter(ClassicsFooter(OASystem.context))

        insurancePaymentListRequest = InsurancePaymentListRequest(groupId)

        insurancePaymentListRequest.pageIndex = pageIndex

        insurancePaymentListRequest.pageSize = 10

        getInsurancePaymentList(1)
    }

    override fun onStart() {
        super.onStart()

        if (OASystem.needRefresh) {
            pageIndex = 1
            insurancePaymentListRequest.pageIndex = pageIndex
            insurancePaymentList.clear()
            OASystem.needRefresh = false
            getInsurancePaymentList(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 getInsurancePaymentList(type: Int) {

        if (!isAdded) {
            return
        }

        apiService.getInsurancePaymentList(insurancePaymentListRequest)
            .enqueue(object : Callback<InsurancePaymentListResponse> {
                override fun onResponse(
                    call: Call<InsurancePaymentListResponse>,
                    response: Response<InsurancePaymentListResponse>
                ) {
                    val insuranceListResponse = response.body()

                    if (insuranceListResponse != null) {
                        if (insuranceListResponse.code == 200) {
                            for (item in insuranceListResponse.data.dataList) {
                                insurancePaymentList.add(item)
                            }

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

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

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

                                3 -> {
                                    binding.insurancePaymentContainer.finishLoadMore()
                                    binding.insurancePaymentContainer.setEnableLoadMore(
                                        pageIndex < totalPage
                                    )
                                    binding.insurancePaymentList.adapter!!.notifyItemInserted(
                                        insurancePaymentList.size
                                    )
                                }
                            }
                        } else {
                            showMessage(insuranceListResponse.msg)
                        }
                    }
                }

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

        val adapter = CardAdapter.Builder<InsurancePaymentListItem>().apply {
            setLayoutId(R.layout.item_insurance_list)
            setData(insurancePaymentList)
            setCanDelete(OASystem.authorization(OASystem.INSURANCE_PAYMENT_INSERT, OASystem.DELETE))
            addBindView { itemView, data ->

                val clientList = data.clientName.trim().split("[*TuT*]")

                if (clientList.size == 1) {
                    itemView.findViewById<TextView>(R.id.customer_name).text = clientList[0]
                } else {
                    itemView.findViewById<TextView>(R.id.customer_name).text = String.format(
                        resources.getString(R.string.client_list_title_format),
                        clientList[0],
                        clientList.size
                    )
                }

                itemView.findViewById<TextView>(R.id.insurance_payment).text = String.format(
                    resources.getString(R.string.price_and_currency_format),
                    data.insuranceCosts,
                    data.currencyStr
                )

                itemView.findViewById<TextView>(R.id.payment_mark).text =
                    data.orbitalPrivateTransferStr

                if (data.attachment.isNotBlank()) {
                    itemView.findViewById<TextView>(R.id.annex_name).text = data.attachment
                } else {
                    itemView.findViewById<TextView>(R.id.annex_name).text =
                        resources.getString(R.string.no_data)
                }

                when (data.isAuditGM) {
                    0 -> {
                        itemView.findViewById<TextView>(R.id.is_verify_status).apply {
                            text = resources.getString(R.string.verify_wait)
                            setTextColor(Color.rgb(23, 171, 227))
                        }
                        itemView.findViewById<ImageView>(R.id.is_verify_icon).setImageResource(R.mipmap.icon_wait)
                    }

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

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

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

                itemView.findViewById<TextView>(R.id.payment_way).text = data.payName
            }
        }.create()

        binding.insurancePaymentList.adapter = adapter

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

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

        binding.insurancePaymentContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                insurancePaymentListRequest.pageIndex = pageIndex
                binding.insurancePaymentList.adapter!!.notifyItemRangeRemoved(0, insurancePaymentList.size)
                insurancePaymentList.clear()
                getInsurancePaymentList(2)
            }

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

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