package com.pan_american.android.ui.group_common.commission_confirm

import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseActivity
import com.pan_american.android.base.BaseResponse
import com.pan_american.android.base.CustomAlertDialog
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.group_common_modle.commission_confirm.adapter.CommissionConfirmListAdapter
import com.pan_american.android.data.model.group_common_modle.commission_confirm.entity.CommissionConfirmListItem
import com.pan_american.android.data.model.group_common_modle.commission_confirm.network.CommissionConfirmListRequest
import com.pan_american.android.data.model.group_common_modle.commission_confirm.network.CommissionConfirmListResponse
import com.pan_american.android.data.model.group_common_modle.commission_confirm.network.UpdateCommissionStatusRequest
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityCommissionConfirmBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class CommissionConfirmActivity : BaseActivity<ActivityCommissionConfirmBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

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

    private val commissionConfirmListRequest = CommissionConfirmListRequest()

    private val commissionConfirmList = ArrayList<CommissionConfirmListItem>()

    private var listInit = false

    override fun getViewBinding() = ActivityCommissionConfirmBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        screenAdaptation(binding)

        initTitle()
        initViews()
        initEvents()
    }

    override fun initTitle() {

        titleBinding = LayoutTitleBinding.bind(binding.root).apply {

            titleText.text = resources.getString(R.string.commission_confirm)

            backButton.setOnClickListener {

                back()
            }
        }
    }

    override fun initViews() {

        binding.companyName.text = OASystem.userInfo.companyName
        binding.department.text = OASystem.userInfo.depName
        binding.staff.text = OASystem.userInfo.cnName
        binding.commit.setText(resources.getString(R.string.search))

    }

    override fun initEvents() {

        binding.filterSwitch.setOnClickListener {
            binding.commissionFilter.apply {
                if (binding.commissionFilter.visibility == View.VISIBLE) {
                    visibility = View.GONE
                    binding.filterSwitch.text = resources.getString(R.string.show)
                } else {
                    visibility = View.VISIBLE
                    binding.filterSwitch.text = resources.getString(R.string.hide)
                }
            }
        }

        binding.startTime.setOnClickListener {
            showDatePicker(resources.getString(R.string.start_time_select_hint), binding.startTime)
        }

        binding.endTime.setOnClickListener {
            showDatePicker(resources.getString(R.string.end_time_select_hint), binding.endTime)
        }

        binding.commit.setOnClickListener {

            if (binding.startTime.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.start_time_select_hint))
                return@setOnClickListener
            } else {
                commissionConfirmListRequest.startDate = binding.startTime.text.toString()
            }

            if (binding.startTime.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.end_time_select_hint))
                return@setOnClickListener
            } else {
                commissionConfirmListRequest.endDate = binding.endTime.text.toString()
            }

            when(binding.confirmStatus.checkedRadioButtonId) {

                binding.confirmAll.id -> {
                    commissionConfirmListRequest.confirm = -1
                }

                binding.confirmed.id -> {
                    commissionConfirmListRequest.confirm = 1
                }

                binding.unconfirmed.id -> {
                    commissionConfirmListRequest.confirm = 0
                }
            }

            when(binding.deliverStatus.checkedRadioButtonId) {

                binding.deliverAll.id -> {
                    commissionConfirmListRequest.send = -1
                }

                binding.delivered.id -> {
                    commissionConfirmListRequest.send = 1
                }

                binding.undelivered.id -> {
                    commissionConfirmListRequest.send = 0
                }
            }

            if (listInit) {

                binding.commissionConfirmList.adapter!!.notifyItemRangeRemoved(0, commissionConfirmList.size)

                commissionConfirmList.clear()

                listInit = false
            }

            getCommissionConfirmList()
        }
    }

    private fun getCommissionConfirmList() {

        apiService.getCommissionConfirmList(commissionConfirmListRequest).enqueue(object : Callback<CommissionConfirmListResponse> {
            override fun onResponse(
                call: Call<CommissionConfirmListResponse>,
                response: Response<CommissionConfirmListResponse>
            ) {

                val listResponse = response.body()

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

                        for (item in listResponse.data.list) {
                            commissionConfirmList.add(item)
                        }

                        binding.totalText.text = String.format(resources.getString(R.string.total_text_format), listResponse.data.costPrice)

                        initList()

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

            override fun onFailure(p0: Call<CommissionConfirmListResponse>, p1: Throwable) {
                showErrorInfo(R.string.commission_confirm_list_get_error)
            }
        })
    }

    private fun initList() {

        if (commissionConfirmList.size == 0) {
            showMessage(resources.getString(R.string.no_data))
            listInit = false
            return
        }

        val layoutManager = LinearLayoutManager(OASystem.context)

        binding.commissionConfirmList.layoutManager = layoutManager

        val adapter = CommissionConfirmListAdapter(commissionConfirmList)

        adapter.onItemClick = object : CommissionConfirmListAdapter.OnItemClick {
            override fun itemDetailClick(position: Int) {

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

                showPopupWindow {

                    val recyclerTitle = picturePreViewPopView.findViewById<TextView>(R.id.recycler_title)
                    val recyclerView = picturePreViewPopView.findViewById<RecyclerView>(R.id.recycler_view)

                    recyclerTitle.text = resources.getString(R.string.commission_detail)

                    recyclerView.layoutManager = LinearLayoutManager(OASystem.context)

                    val commissionDetailAdapter = ListAdapter.Builder<String>().apply {
                        setData(commissionConfirmList[position].chiArr)
                        setLayoutId(R.layout.item_selector)
                        addBindView { itemView, data ->
                            itemView.findViewById<TextView>(R.id.selector_item_name).text = data
                        }
                    }.create()

                    recyclerView.adapter = commissionDetailAdapter

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

            override fun itemConfirmClick(position: Int) {

                if (commissionConfirmList[position].isConfirm == 0) {
                    CustomAlertDialog.Builder().apply {
                        setTitle(resources.getString(R.string.hint))
                        setMessage(String.format(resources.getString(R.string.commission_confirm_hint), commissionConfirmList[position].teamName, commissionConfirmList[position].temp))
                        setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                            dialog.dismiss()
                        }
                        setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                            updateCheckState(position)
                        }
                    }.show()
                }
            }
        }

        binding.commissionConfirmList.adapter = adapter

        listInit = true
    }

    private fun updateCheckState(position: Int) {

        apiService.updateCommissionConfirmStatus(UpdateCommissionStatusRequest(arrayListOf(commissionConfirmList[position].id))).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(p0: Call<BaseResponse>, response: Response<BaseResponse>) {

                val updateResponse = response.body()

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

                        showMessage(resources.getString(R.string.confirm_success))

                        if (listInit) {

                            binding.commissionConfirmList.adapter!!.notifyItemRangeRemoved(0, commissionConfirmList.size)

                            commissionConfirmList.clear()

                            listInit = false
                        }

                        getCommissionConfirmList()

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

            override fun onFailure(p0: Call<BaseResponse>, p1: Throwable) {
                showErrorInfo(R.string.commission_confirm_status_change_error)
            }
        })
    }
}