package com.base.scanqrclear.ui.main

import android.content.Intent
import android.graphics.Color
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.lifecycle.ViewModelProvider
import com.base.scanqrclear.R
import com.base.scanqrclear.base.BaseFragment
import com.base.scanqrclear.bean.AdScanBean
import com.base.scanqrclear.bean.FunctionUIBean
import com.base.scanqrclear.bean.ScanBean
import com.base.scanqrclear.databinding.FragmentHistoryBinding
import com.base.scanqrclear.ui.contact.ContractCodeActivity
import com.base.scanqrclear.ui.email.EmailCodeActivity
import com.base.scanqrclear.ui.event.EventCodeActivity
import com.base.scanqrclear.ui.message.MessageCodeActivity
import com.base.scanqrclear.ui.product.ProductCodeActivity
import com.base.scanqrclear.ui.telephone.TelephoneCodeActivity
import com.base.scanqrclear.ui.text.TextCodeActivity
import com.base.scanqrclear.ui.website.WebsiteCodeActivity
import com.base.scanqrclear.ui.widget.DeleteQRDialog.showDeleteQRDialog
import com.base.scanqrclear.ui.widget.HistoryMoreDialog.showHistoryMoreDialog
import com.base.scanqrclear.ui.widget.SortByDialog.showSortByDialog
import com.base.scanqrclear.ui.wifi.WifiCodeActivity
import com.base.scanqrclear.utils.BarUtils
import com.base.scanqrclear.utils.CollectionEx.addStepElements
import com.base.scanqrclear.utils.LogEx
import com.google.gson.Gson
import com.gyf.immersionbar.ktx.immersionBar


class HistoryFragment : BaseFragment<FragmentHistoryBinding>(FragmentHistoryBinding::inflate) {

    private var adapter: HistoryAdapter? = null
    private val viewModel by lazy(LazyThreadSafetyMode.NONE) {
        ViewModelProvider(this)[HistoryViewModel::class.java]
    }

    override fun initView() {
        super.initView()
        binding.flTop.updatePadding(top = BarUtils.getStatusBarHeight())

    }

    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        initAdapter()
        viewModel.initData()
    }

    private fun initAdapter() {
        adapter = HistoryAdapter()
        binding.rv.adapter = adapter
        adapter?.moreAction = { view, bean ->
            requireContext().showHistoryMoreDialog(view, detailAction = {
                jumpByScanBean(bean)
            }, removeAction = {
                viewModel.removeBean(bean)
                if (tab == 0) {
                    createUI()
                } else {
                    scanUI()
                }
            })
        }
        adapter?.itemClick = { item ->
            jumpByScanBean(item)
        }
    }

    private fun jumpByScanBean(item: ScanBean) {
        val activity = requireActivity() as MainActivity?

        when (item.scanType) {
            FunctionUIBean.KEY_WIFI -> {
                activity?.startActivity(Intent(activity, WifiCodeActivity::class.java).apply {
                    putExtra("data", Gson().toJson(item))
                })
            }

            FunctionUIBean.KEY_TEXT -> {
                activity?.startActivity(Intent(activity, TextCodeActivity::class.java).apply {
                    putExtra("data", Gson().toJson(item))
                })
            }

            FunctionUIBean.KEY_EMAIL -> {
                activity?.startActivity(Intent(activity, EmailCodeActivity::class.java).apply {
                    putExtra("data", Gson().toJson(item))
                })
            }

            FunctionUIBean.KEY_WEBSITE -> {
                activity?.startActivity(Intent(activity, WebsiteCodeActivity::class.java).apply {
                    putExtra("data", Gson().toJson(item))
                })
            }

            FunctionUIBean.KEY_PRODUCT -> {
                activity?.startActivity(Intent(activity, ProductCodeActivity::class.java).apply {
                    putExtra("data", Gson().toJson(item))
                })
            }

            FunctionUIBean.KEY_EVENT -> {
                activity?.startActivity(Intent(activity, EventCodeActivity::class.java).apply {
                    putExtra("data", Gson().toJson(item))
                })
            }

            FunctionUIBean.KEY_TELEPHONE -> {
                activity?.startActivity(Intent(activity, TelephoneCodeActivity::class.java).apply {
                    putExtra("data", Gson().toJson(item))
                })
            }

            FunctionUIBean.KEY_CONTACT -> {
                activity?.startActivity(Intent(activity, ContractCodeActivity::class.java).apply {
                    putExtra("data", Gson().toJson(item))
                })
            }

            FunctionUIBean.KEY_MESSAGE -> {
                activity?.startActivity(Intent(activity, MessageCodeActivity::class.java).apply {
                    putExtra("data", Gson().toJson(item))
                })
            }
        }
    }

    override fun initListener() {
        super.initListener()
        binding.tvScan.setOnClickListener {
            scanUI()
        }
        binding.tvCreate.setOnClickListener {
            createUI()
        }
        binding.llRemove.setOnClickListener {
            requireContext().showDeleteQRDialog {

                viewModel.removeList(tab)

                if (tab == 0) {
                    createUI()
                } else {
                    scanUI()
                }
            }
        }

        if (tab == 0) {
            createUI()
        } else {
            scanUI()
        }
        binding.llSort.setOnClickListener {
            requireContext().showSortByDialog {
                LogEx.logDebug(TAG, "sortType=$sortType aesOrDes=$aesOrDes")
                if (tab == 0) {
                    createUI()
                } else {
                    scanUI()
                }
            }
        }

    }

    private fun scanUI() {
        tab = 1
        binding.tvScan.background = ContextCompat.getDrawable(requireContext(), R.drawable.bg_6473f8_10)
        binding.tvScan.setTextColor(Color.parseColor("#FFFFFF"))

        binding.tvCreate.background = ContextCompat.getDrawable(requireContext(), R.drawable.bg_transparent)
        binding.tvCreate.setTextColor(Color.parseColor("#666666"))

        changeRvData(false)
    }

    private fun createUI() {
        tab = 0
        binding.tvCreate.background = ContextCompat.getDrawable(requireContext(), R.drawable.bg_6473f8_10)
        binding.tvCreate.setTextColor(Color.parseColor("#FFFFFF"))

        binding.tvScan.background = ContextCompat.getDrawable(requireContext(), R.drawable.bg_transparent)
        binding.tvScan.setTextColor(Color.parseColor("#666666"))

        changeRvData(true)
    }

    private fun changeRvData(isCreateOrScan: Boolean) {
        val uiRefresh = {
            val qrState = if (isCreateOrScan) 0 else 1
            val createList = viewModel.historyList.filter { it.createType == qrState }
            binding.llEmpty.isVisible = createList.isEmpty()
            val sortList = sortList(createList)
            adapter?.submitList(sortList.addStepElements { AdScanBean() })
        }
        if (viewModel.dataRefreshFinish.get()) {
            uiRefresh.invoke()
        } else {
            viewModel.dataRefreshBack = {
                requireActivity().runOnUiThread {
                    uiRefresh.invoke()
                }
            }
        }
    }

    private fun sortList(createList: List<ScanBean>): List<ScanBean> {

        if (sortType == SORT_NAME) {
            return if (aesOrDes) {
                createList.sortedBy { it.listContent }
            } else {
                createList.sortedByDescending { it.listContent }
            }
        }
        if (sortType == SORT_TIME) {
            return if (aesOrDes) {
                createList.sortedByDescending { it.createTime }
            } else {
                createList.sortedBy { it.createTime }
            }
        }
        if (sortType == SORT_TYPE) {
            return if (aesOrDes) {
                createList.sortedBy { it.scanType }
            } else {
                createList.sortedByDescending { it.scanType }
            }
        }
        return createList
    }

    override fun onResume() {
        super.onResume()
        immersionBar {
            statusBarColor("#FFFFFFFF")
            statusBarDarkFont(true)
        }
    }


    companion object {
        var tab: Int = 0 // create=0 scan=1
        const val SORT_NAME = "sort_name"
        const val SORT_TIME = "sort_time"
        const val SORT_TYPE = "sort_type"
        var sortType: String = SORT_NAME
        var aesOrDes = true//aes :ture  des:false
    }
}