package com.pan_american.android.ui.efficiency_tools.daily_payment

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
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.BaseRequest
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.base.ListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.common.network.DeleteRequest
import com.pan_american.android.data.model.daily_payment.entity.DailyPaymentCardListItem
import com.pan_american.android.data.model.daily_payment.network.DailyPaymentListRequest
import com.pan_american.android.data.model.daily_payment.network.DailyPaymentListResponse
import com.pan_american.android.data.model.daily_payment.network.DailyPaymentSiftResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityDaliyPaymentListBinding
import com.pan_american.android.databinding.LayoutTitleBinding
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 DailyPaymentListActivity : BaseActivity<ActivityDaliyPaymentListBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private var isDisplay = true

    private var dailyPaymentCardListItems = ArrayList<DailyPaymentCardListItem>()

    val apiService = ServiceCreator.create<APIService>()

    private lateinit var dailyPaymentListRequest: DailyPaymentListRequest

    private var pageIndex = 1

    private var totalPage = 0

    private var siftInit = false

    private var listInit = false

    private var selectorList = ArrayList<Selector>()

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

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

        dailyPaymentListRequest = DailyPaymentListRequest()

        if (!OASystem.authorization(OASystem.DAILY_PAYMENT, OASystem.PROCESS)) {
            dailyPaymentListRequest.createUserId = OASystem.userInfo.userId
        }

        dailyPaymentListRequest.pageIndex = pageIndex
        dailyPaymentListRequest.pageSize = 10

        initTitle()
        initViews()
        //先获取筛选列表信息，再初始化界面
        initSiftItems()
    }

    override fun onStart() {
        super.onStart()

        getDailyPaymentList()
    }

    override fun initTitle() {

        titleBinding = LayoutTitleBinding.bind(binding.root).apply {
            titleText.text = resources.getString(R.string.daily_payment_list_title)

            if (OASystem.authorization(OASystem.DAILY_PAYMENT, OASystem.ADD)) {
                addButton.apply {
                    visibility = View.VISIBLE

                    setOnClickListener {
                        val intent = Intent(OASystem.context, AddDailyPaymentActivity::class.java)
                        startActivity(intent)
                    }
                }
            }

            backButton.setOnClickListener {
                back()
            }
        }

    }

    override fun initViews() {
        binding.commit.setText(resources.getString(R.string.sift))
    }

    override fun initEvents() {
        initSiftOnClickListener()
    }

    private fun filterSwitch() {
        if (isDisplay) {
            binding.dailyPaymentFilter.visibility = View.GONE
            binding.filterSwitch.text = resources.getString(R.string.show)
            isDisplay = false
        } else {
            binding.dailyPaymentFilter.visibility = View.VISIBLE
            binding.filterSwitch.text = resources.getString(R.string.hide)
            isDisplay = true
        }
    }

    private fun initSiftItems() {
        if (!siftInit) {
            apiService.getPaymentSiftDataSource(BaseRequest())
                .enqueue(object : Callback<DailyPaymentSiftResponse> {
                    override fun onResponse(
                        call: Call<DailyPaymentSiftResponse>,
                        response: Response<DailyPaymentSiftResponse>
                    ) {
                        val dailyPaymentSiftResponse = response.body()
                        if (dailyPaymentSiftResponse != null) {
                            if (dailyPaymentSiftResponse.code == 200) {
                                OASystem.dailyPaymentUserName =
                                    dailyPaymentSiftResponse.data.userNameData
                                OASystem.paymentType = dailyPaymentSiftResponse.data.feeTypeData
                                OASystem.paymentSubType =
                                    dailyPaymentSiftResponse.data.feeTypeSubData

                                siftInit = true

                                initEvents()
                            } else {
                                showMessage(dailyPaymentSiftResponse.msg)
                            }
                        }
                    }

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

    private fun initSiftOnClickListener() {
        binding.filterSwitch.setOnClickListener {
            filterSwitch()
        }

        binding.paymentType.setOnClickListener {

            selectorList.clear()

            val selectAll = Selector().apply {
                id = -1
                name = resources.getString(R.string.all)
            }

            selectorList.add(selectAll)

            for (item in OASystem.paymentType) {
                selectorList.add(item)
            }

            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(selectorList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {

                            text = data.name

                            if (binding.paymentType.text == data.name) {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color_blue,
                                        null
                                    )
                                )
                            } else {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color,
                                        null
                                    )
                                )
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            popupWindow.dismiss()
                            binding.paymentType.text = selectorList[position].name
                            dailyPaymentListRequest.feeTypeId = selectorList[position].id

                            if (dailyPaymentListRequest.feeTypeId == -1) {
                                dailyPaymentListRequest.feeSubTypeId = -1
                                binding.paymentSubType.text = resources.getString(R.string.all)
                            }
                        }
                    }
            }
        }

        binding.paymentSubType.setOnClickListener {

            if (dailyPaymentListRequest.feeTypeId == -1) {
                showMessage(resources.getString(R.string.select_payment_type))
                return@setOnClickListener
            }

            selectorList.clear()

            val selectAll = Selector().apply {
                id = -1
                name = resources.getString(R.string.all)
            }

            selectorList.add(selectAll)

            for (item in OASystem.paymentSubType) {
                if (dailyPaymentListRequest.feeTypeId == item.sTid) {
                    selectorList.add(item)
                }
            }

            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(selectorList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {

                            text = data.name

                            if (binding.paymentSubType.text == data.name) {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color_blue,
                                        null
                                    )
                                )
                            } else {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color,
                                        null
                                    )
                                )
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            popupWindow.dismiss()
                            binding.paymentSubType.text = selectorList[position].name
                            dailyPaymentListRequest.feeSubTypeId = selectorList[position].id
                        }
                    }
            }
        }

        binding.createUser.setOnClickListener {

            if (!OASystem.authorization(OASystem.DAILY_PAYMENT, OASystem.PROCESS)) {
                return@setOnClickListener
            }

            selectorList.clear()

            val selectAll = Selector().apply {
                id = -1
                cnName = resources.getString(R.string.all)
            }

            selectorList.add(selectAll)

            for (item in OASystem.dailyPaymentUserName) {
                selectorList.add(item)
            }

            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(selectorList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {

                            text = data.cnName

                            if (binding.createUser.text == data.cnName) {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color_blue,
                                        null
                                    )
                                )
                            } else {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color,
                                        null
                                    )
                                )
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            popupWindow.dismiss()
                            binding.createUser.text = selectorList[position].cnName
                            dailyPaymentListRequest.createUserId = selectorList[position].id
                        }
                    }
            }
        }

        binding.commit.setOnClickListener {

            if (binding.paymentDescription.text.isNotBlank()) {
                dailyPaymentListRequest.feeDesc = binding.paymentDescription.text.toString()
            } else {
                dailyPaymentListRequest.feeDesc = ""
            }

            when (binding.financeDepartVerify.checkedRadioButtonId) {
                binding.financeAll.id -> {
                    dailyPaymentListRequest.financialAuditStatus = -1
                }

                binding.financeWait.id -> {
                    dailyPaymentListRequest.financialAuditStatus = 0
                }

                binding.financePassed.id -> {
                    dailyPaymentListRequest.financialAuditStatus = 1
                }

                binding.financeReject.id -> {
                    dailyPaymentListRequest.financialAuditStatus = 2
                }
            }

            when (binding.generalManagerVerify.checkedRadioButtonId) {
                binding.generalAll.id -> {
                    dailyPaymentListRequest.managerAuditStatus = -1
                }

                binding.generalWait.id -> {
                    dailyPaymentListRequest.managerAuditStatus = 0
                }

                binding.generalPassed.id -> {
                    dailyPaymentListRequest.managerAuditStatus = 1
                }

                binding.generalReject.id -> {
                    dailyPaymentListRequest.managerAuditStatus = 2
                }
            }

            pageIndex = 1

            dailyPaymentListRequest.pageIndex = pageIndex

            listInit = false

            dailyPaymentCardListItems.clear()

            binding.commit.setButtonStatus(1)

            initDailyPaymentList(1)
        }
    }

    private fun initDailyPaymentList(type: Int) {

        if (!listInit) {
            apiService.getDailyPaymentList(dailyPaymentListRequest)
                .enqueue(object : Callback<DailyPaymentListResponse> {
                    override fun onResponse(
                        call: Call<DailyPaymentListResponse>,
                        response: Response<DailyPaymentListResponse>
                    ) {
                        val dailyPaymentResponse = response.body()
                        if (dailyPaymentResponse != null) {
                            if (dailyPaymentResponse.code == 200) {

                                for (item in dailyPaymentResponse.data.dataList) {
                                    dailyPaymentCardListItems.add(item)
                                }

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

                                when (type) {
                                    1 -> {
                                        totalPage = getTotalPage(
                                            dailyPaymentResponse.data.dataCount,
                                            dailyPaymentResponse.data.currPageSize
                                        )
                                        binding.dailyPaymentContainer.setEnableLoadMore(pageIndex < totalPage)
                                        initList()
                                        listInit = true
                                    }

                                    2 -> {
                                        binding.dailyPaymentContainer.finishRefresh()
                                        totalPage = getTotalPage(
                                            dailyPaymentResponse.data.dataCount,
                                            dailyPaymentResponse.data.currPageSize
                                        )
                                        binding.dailyPaymentContainer.setEnableLoadMore(pageIndex < totalPage)
                                        initList()
                                        listInit = true
                                    }

                                    3 -> {
                                        binding.dailyPaymentContainer.finishLoadMore()
                                        binding.dailyPaymentContainer.setEnableLoadMore(pageIndex < totalPage)
                                        binding.dailyPaymentList.adapter!!.notifyItemInserted(
                                            dailyPaymentCardListItems.size
                                        )
                                        listInit = true
                                    }
                                }
                            } else {
                                showMessage(dailyPaymentResponse.msg)
                            }
                        }

                        binding.commit.setButtonStatus(0)
                    }

                    override fun onFailure(call: Call<DailyPaymentListResponse>, t: Throwable) {
                        binding.commit.setButtonStatus(0)
                        showMessage(resources.getString(R.string.network_error))
                    }
                })
        } else {
            if (OASystem.needRefresh) {
                pageIndex = 1
                dailyPaymentListRequest.pageIndex = pageIndex
                dailyPaymentCardListItems.clear()
                listInit = false
                initDailyPaymentList(2)
            }
        }
    }

    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.dailyPaymentList.layoutManager = layoutManager

        val adapter = CardAdapter.Builder<DailyPaymentCardListItem>().apply {
            setLayoutId(R.layout.item_daily_payment)
            setData(dailyPaymentCardListItems)
            setCanDelete(OASystem.authorization(OASystem.DAILY_PAYMENT, OASystem.DELETE))
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.payment_name).text = data.instructions
                itemView.findViewById<TextView>(R.id.payment_revert).text = data.companyName
                itemView.findViewById<TextView>(R.id.payment_creator).text = data.createUser
                itemView.findViewById<TextView>(R.id.total_payment).text =
                    String.format(resources.getString(R.string.rmb_price), data.sumPrice)
                itemView.findViewById<TextView>(R.id.create_time).text = data.createTime
                itemView.findViewById<TextView>(R.id.finance_status).text = data.fAuditDesc
                itemView.findViewById<TextView>(R.id.general_status).text = data.mAuditDesc
                itemView.findViewById<TextView>(R.id.finance_reviewer).text = data.fAuditName
                itemView.findViewById<TextView>(R.id.general_reviewer).text = data.mAuditName

                when (data.fAudit) {
                    0 -> {
                        itemView.findViewById<ImageView>(R.id.finance_icon)
                            .setImageResource(R.mipmap.icon_wait)
                        itemView.findViewById<TextView>(R.id.finance_status)
                            .setTextColor(Color.rgb(23, 171, 227))
                    }

                    1 -> {
                        itemView.findViewById<ImageView>(R.id.finance_icon)
                            .setImageResource(R.mipmap.icon_passed)
                        itemView.findViewById<TextView>(R.id.finance_status)
                            .setTextColor(Color.rgb(84, 213, 77))
                    }

                    2 -> {
                        itemView.findViewById<ImageView>(R.id.finance_icon)
                            .setImageResource(R.mipmap.icon_reject)
                        itemView.findViewById<TextView>(R.id.finance_status)
                            .setTextColor(Color.rgb(210, 45, 34))
                    }
                }

                when (data.mAudit) {
                    0 -> {
                        itemView.findViewById<ImageView>(R.id.general_icon)
                            .setImageResource(R.mipmap.icon_wait)
                        itemView.findViewById<TextView>(R.id.general_status)
                            .setTextColor(Color.rgb(23, 171, 227))
                    }

                    1 -> {
                        itemView.findViewById<ImageView>(R.id.general_icon)
                            .setImageResource(R.mipmap.icon_passed)
                        itemView.findViewById<TextView>(R.id.general_status)
                            .setTextColor(Color.rgb(84, 213, 77))
                    }

                    2 -> {
                        itemView.findViewById<ImageView>(R.id.general_icon)
                            .setImageResource(R.mipmap.icon_reject)
                        itemView.findViewById<TextView>(R.id.general_status)
                            .setTextColor(Color.rgb(210, 45, 34))
                    }
                }

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

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

        binding.dailyPaymentList.adapter = adapter

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

                    val intent =
                        Intent(OASystem.context, AddDailyPaymentActivity::class.java).apply {
                            putExtra("from_list", true)
                            putExtra("daily_payment_id", dailyPaymentCardListItems[position].id)
                            putExtra("finance_status", dailyPaymentCardListItems[position].fAudit)
                            putExtra("manager_status", dailyPaymentCardListItems[position].mAudit)
                        }

                    startActivity(intent)
                }

                override fun onItemDelete(position: Int) {
                    CustomAlertDialog.Builder(OASystem.context).apply {
                        setTitle(resources.getString(R.string.alert))
                        setMessage(resources.getString(R.string.payment_alert_dialog))
                        setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                            dialog.dismiss()
                        }
                        setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                            deleteDailyPayment(position)
                        }
                        setCancelable(false)
                    }.show()
                }
            }

        binding.dailyPaymentContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                dailyPaymentListRequest.pageIndex = pageIndex
                dailyPaymentCardListItems.clear()
                listInit = false
                initDailyPaymentList(2)
            }

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

    private fun deleteDailyPayment(position: Int) {
        apiService.deleteDailyPayment(DeleteRequest(dailyPaymentCardListItems[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) {
                            dailyPaymentCardListItems.removeAt(position)
                            binding.dailyPaymentList.adapter!!.notifyItemRemoved(position)
                            binding.dailyPaymentList.adapter!!.notifyItemRangeChanged(
                                position, dailyPaymentCardListItems.size
                            )
                            showMessage(resources.getString(R.string.delete_success))
                        } else {
                            showMessage(baseResponse.msg)
                        }
                    }
                }

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

    private fun getDailyPaymentList() {
        if (!OASystem.authorization(OASystem.DAILY_PAYMENT, OASystem.PROCESS)) {
            binding.createUser.text = OASystem.userInfo.cnName
        }

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

        initDailyPaymentList(1)
    }
}