package com.miya.fastcashier.ui

import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.elvishew.xlog.XLog
import com.google.android.material.tabs.TabLayoutMediator
import com.miya.fastcashier.R
import com.miya.fastcashier.beans.ViewPayOrderData
import com.miya.fastcashier.dao.PayDataDao
import com.miya.fastcashier.databinding.ActivitySearchOrderBinding
import com.miya.fastcashier.databinding.FragmentSearchOrderBinding
import com.miya.fastcashier.databinding.ItemSearchOrderListBinding
import com.miya.fastcashier.service.AccountService
import com.miya.fastcashier.service.PrintService
import com.miya.fastcashier.utils.*
import com.miya.fastcashier.utils.manage.LocalKeyDataMKManageKit
import com.miya.fastcashier.viewmodel.SearchOrderViewModel

/**
 * 查单列表
 */
class SearchOrderActivity : BaseActivity() {
    private lateinit var binding: ActivitySearchOrderBinding

    companion object {
        fun start(context: BaseActivity) {
            val intent = Intent(context, SearchOrderActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySearchOrderBinding.inflate(LayoutInflater.from(this))
        setContentView(binding.root)
        binding.title.llBack.clickWithTrigger { finish() }

        binding.vpPage.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return 2
            }

            override fun createFragment(position: Int): Fragment {
                return when (position) {
                    0 -> SearchOrderFragment(MiYaPayPlantformPayWayEnum.MiyaPayType.WEIXIN)
                    else -> SearchOrderFragment(MiYaPayPlantformPayWayEnum.MiyaPayType.ALIPAY)
                }
            }
        }

        TabLayoutMediator(
            binding.tlIndicator,
            binding.vpPage
        ) { tab, position ->
            when (position) {
                0 -> tab.text = "微信"
                1 -> tab.text = "支付宝"
                else -> tab.text = ""
            }
        }.attach()
    }
}


class SearchOrderFragment(val payType: MiYaPayPlantformPayWayEnum.MiyaPayType) : Fragment() {
    private var binding: FragmentSearchOrderBinding? = null

    private lateinit var adapter: SearchOrderListAdapter
    private lateinit var vm: SearchOrderViewModel

    //    private var onLoading = false
    private var isEnd = false
    private var balanceDate = 0L

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentSearchOrderBinding.inflate(inflater, container, false)
        return binding!!.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (activity == null) {
            return
        }
        isEnd = false
//        onLoading = false
        balanceDate = LocalKeyDataMKManageKit.getBalanceDate()
        val act = requireActivity()
        binding?.run {
            adapter = SearchOrderListAdapter(act, arrayListOf())
            rvContent.layoutManager = LinearLayoutManager(act, LinearLayoutManager.VERTICAL, false)
            rvContent.adapter = adapter
            rvContent.addItemDecoration(
                object : RecyclerView.ItemDecoration() {
                    val itemMargin = dp2px(act, 16F)
                    override fun getItemOffsets(
                        outRect: Rect,
                        view: View,
                        parent: RecyclerView,
                        state: RecyclerView.State
                    ) {
                        outRect.set(itemMargin, itemMargin, itemMargin, 0)
                    }
                }
            )
//            rvContent.addOnScrollListener(object : RecyclerView.OnScrollListener() {
//                //用来标记是否正在向最后一个滑动
//                var isSlidingToLast = false
//
//                override fun onScrollStateChanged(
//                    recyclerView: RecyclerView,
//                    newState: Int
//                ) {
//                    if (isEnd) { //如果已经加载完成，就不处理
//                        return
//                    }
//                    val manager = recyclerView.layoutManager as LinearLayoutManager?
//                    // 当不滚动时
//                    if (manager != null && newState == RecyclerView.SCROLL_STATE_IDLE) {
//                        //获取最后一个完全显示的ItemPosition
//                        val lastVisibleItem = manager.findLastCompletelyVisibleItemPosition()
//                        val totalItemCount = manager.itemCount
//
//                        // 判断是否滚动到底部，并且是向右滚动
//                        if (!onLoading && totalItemCount > 5 && lastVisibleItem > totalItemCount - 5 && isSlidingToLast) { //滑到最后5条的时候，如果不是列表已经结束，那么就
//                            //加载更多功能的代码
//                            onLoading = true
//                            loadMore(adapter.itemCount)
//                        }
//                    }
//                }
//
//                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
//                    //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
//                    isSlidingToLast = dy > 0
//                }
//            })
        }

        vm = ViewModelProvider(this).get(SearchOrderViewModel::class.java)
        vm.payDataLiveData.observe(act) {
//            onLoading = false
            it.onFailure { e ->
                CenterToasty.error(act, e.message ?: "", Toast.LENGTH_LONG).show()
            }
            it.onSuccess { list ->
                val oldSize = adapter.getDataSource().size

                if (oldSize == 0 && list.size == 0)
                    binding!!.cpEmptyView.visibility = View.VISIBLE
                else
                    binding!!.cpEmptyView.visibility = View.GONE

                adapter.getDataSource().addAll(list)
                if (oldSize == 0) {
                    adapter.notifyDataSetChanged()
                } else {
                    adapter.notifyItemInserted(oldSize)
                }
                if (list.size < PayDataDao.NUM_OF_SINGLE_PAGE) {//如果不足20条，表示已经到底，不用查了
                    isEnd = true
                }
            }
        }
        initEmptyView()
        loadMore(0)
    }

    private fun initEmptyView() {
        binding!!.cpEmptyView.visibility = View.GONE
        binding!!.cpEmptyView.setPromptText(getString(R.string.search_order_prompt_text))
        binding!!.cpEmptyView.setPromptImage(R.mipmap.app_bg_common_empty)
    }

    private fun loadMore(loadIndex: Int) {
        //加载更多
//        vm.getPayData(payType, loadIndex)
        vm.getPayDataByTimeAndUser(payType,AccountService.getUserName(), balanceDate)
//        onLoading = true
    }

    override fun onDestroyView() {
        binding = null
        super.onDestroyView()
    }
}

class SearchOrderListAdapter(
    val context: Context,
    private val list: MutableList<ViewPayOrderData>
) :
    RecyclerView.Adapter<SearchOrderViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchOrderViewHolder {
        return SearchOrderViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.item_search_order_list, parent, false)
        )
    }

    override fun onBindViewHolder(holder: SearchOrderViewHolder, position: Int) {
        holder.setData(list[position])
    }

    override fun getItemCount(): Int {
        return list.size
    }

    fun getDataSource(): MutableList<ViewPayOrderData> {
        return list
    }

}

class SearchOrderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    private val binding: ItemSearchOrderListBinding = ItemSearchOrderListBinding.bind(itemView)

    fun setData(data: ViewPayOrderData) {

        binding.tvDate.text = data.chanelOrderTradeTime
        binding.tvDateTitle.text = "下单时间"
        if (data.refundOrderNo != null && data.refundPrice != null) {
            binding.tvPrice.text =
                "¥" + StringPriceFormat.transStringPriceToDecimalString(data.refundPrice)
            binding.tvOrderNo.text = data.refundOrderNo
            binding.tvSerialNo.text = data.tradeNo
            binding.tvOrderNoTitle.text = "退款订单号"
            binding.tvSerialNoTitle.text = "退款流水号"
            binding.tvPriceTitle.text = "退款金额"
            binding.tvPrice.setTextColor(
                ResourcesCompat.getColor(
                    itemView.resources,
                    R.color.color_FF4E33, null
                )
            )
        } else {
            binding.tvPrice.text =
                "¥" + StringPriceFormat.transStringPriceToDecimalString(data.tradPrice)
            binding.tvOrderNo.text = data.orderNo
            binding.tvOrderNoTitle.text = "订单号"
            binding.tvSerialNoTitle.text = "流水号"
            binding.tvPriceTitle.text = "订单金额"
            binding.tvSerialNo.text = data.tradeNo
            binding.tvPrice.setTextColor(
                ResourcesCompat.getColor(
                    itemView.resources,
                    R.color.color_333333, null
                )
            )
        }

        binding.vBg.setOnLongClickListener {
            binding.groupPrinter.visibility = View.VISIBLE
            true
        }

        binding.tvPrinter.setOnClickListener(object : View.OnClickListener {
            override fun onClick(p0: View?) {
                binding.groupPrinter.visibility = View.GONE
                printer(data)
            }
        })

        binding.vPrinter.setOnClickListener(object : View.OnClickListener {
            override fun onClick(p0: View?) {
                binding.groupPrinter.visibility = View.GONE
            }
        })
    }

    fun printer(data: ViewPayOrderData) {
        var isRefund: Boolean = data.refundOrderNo != null && data.refundPrice != null
        //退款打印
        try {
            XLog.d("开始打印")
            AccountService.getAccountInfo()
                ?.let {
                    ViewPayOrderData.transformPayServiceResponse(data)?.let { it1 ->
                        PrintService.printSearchOrder(
                            it,
                            it1,
                            isRefund
                        )
                    }
                }
        } catch (e: Exception) {
            e.printStackTrace()
            XLog.d("打印异常${e.message}")
        }
    }

}