package com.module.backstage.fragment.date

import android.graphics.Color
import android.util.Log
import android.view.MotionEvent
import android.view.View
import androidx.fragment.app.viewModels
import com.github.mikephil.charting.listener.ChartTouchListener
import com.github.mikephil.charting.listener.OnChartGestureListener
import com.hboxs.serialport.plc.DialogClickListener
import com.module.backstage.chart.BarChartManager
import com.module.backstage.chart.FancyListBean
import com.module.backstage.databinding.BackstageFragmentHistogramDataBinding
import com.module.backstage.dialog.DateDialog
import com.module.backstage.vm.HistogramDataFragmentVM
import com.module.database.room.entity.LocalOrderBean
import com.quyunshuo.androidbaseframemvvm.base.ktx.observeLiveData
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseFragment
import com.quyunshuo.androidbaseframemvvm.common.util.ToastUtil
import dagger.hilt.android.AndroidEntryPoint
import java.util.Collections
import kotlin.math.max

/**
 * 柱状图统计查看Fragment
 *
 * @author Qu Yunshuo
 * @since 2021/8/1 11:46 下午
 */
@AndroidEntryPoint
class HistogramDataFragment : BaseFragment<BackstageFragmentHistogramDataBinding, HistogramDataFragmentVM>(),
    View.OnClickListener {

    private var hour: Int = 0;
    private var day: Int = 1;
    private var month: Int = 2;
    private var year: Int = 3;
    private var unit: Int = hour
    private var startTime: String = ""
    private var endTime: String = ""

    private val TAG = "DataStatFragment"
    var barChartManager: BarChartManager? = null
    override val mViewModel: HistogramDataFragmentVM by viewModels()
    override fun createVB() = BackstageFragmentHistogramDataBinding.inflate(layoutInflater)
    var dateStatFragment: DateDialog? = null


    override fun BackstageFragmentHistogramDataBinding.initView() {
        barChartManager = BarChartManager(barChar1)
        barChar1.setVisibility(View.INVISIBLE)
        barChar1.setPinchZoom(false)
        barChar1.setDrawBarShadow(false)
        barChar1.setDrawGridBackground(false)
        barChar1.setOnChartGestureListener(object : OnChartGestureListener {
            // 手势监听器
            override fun onChartGestureStart(
                me: MotionEvent,
                lastPerformedGesture: ChartTouchListener.ChartGesture
            ) {
                // 按下
            }

            override fun onChartGestureEnd(
                me: MotionEvent,
                lastPerformedGesture: ChartTouchListener.ChartGesture
            ) {
                // 抬起,取消
            }

            override fun onChartLongPressed(me: MotionEvent) {
                // 长按
            }

            override fun onChartDoubleTapped(me: MotionEvent) {
                // 双击
            }

            override fun onChartSingleTapped(me: MotionEvent) {
                // 单击
            }

            override fun onChartFling(
                me1: MotionEvent,
                me2: MotionEvent,
                velocityX: Float,
                velocityY: Float
            ) {
                // 甩动
            }

            override fun onChartScale(me: MotionEvent, scaleX: Float, scaleY: Float) {
                // 缩放

            }

            override fun onChartTranslate(me: MotionEvent, dX: Float, dY: Float) {
                // 移动
            }
        })
        tvEndTime.setOnClickListener(this@HistogramDataFragment)
        tvStartTime.setOnClickListener(this@HistogramDataFragment)
        tvScreen.setOnClickListener(this@HistogramDataFragment)
        rgFancy.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                mBinding.rbHour.id -> {
                    unit = hour
                }

                mBinding.rbYear.id -> {
                    unit = year
                }

                mBinding.rbDay.id -> {
                    unit = day
                }

                mBinding.rbMonth.id -> {
                    unit = month
                }

                else -> {}
            }
            mBinding.tvStartTime.text = "请选择开始时间"
            mBinding.tvEndTime.text = "请选择结束时间"
            startTime = ""
            endTime = ""

        }

        //查询今日数据
        mViewModel.screen(mViewModel.todoTime(0), mViewModel.todoTime(1),unit)

    }

    override fun initObserve() {
        observeLiveData(mViewModel.allLocalOrder, ::setData)
    }

    fun allLocalOrder(localOrderBeans: List<LocalOrderBean>?) {
        Log.d(TAG, "allLocalOrder: " + localOrderBeans)
    }

    override fun initRequestData() {
    }

    private fun setData(list: List<FancyListBean>) {

        val xValues = arrayOfNulls<String>(list.size)
        //x轴个数
        val xAxisValues: MutableList<Float> = ArrayList()
        val yAxisValues: MutableList<List<Float>> = ArrayList()
        val labels: MutableList<String> = ArrayList()
        val colours: MutableList<Int> = ArrayList()
        // 柱1
        val x1: MutableList<Float> = ArrayList()
        // 柱2
        val x2: MutableList<Float> = ArrayList()
        labels.add("")
        labels.add("")
        colours.add(Color.WHITE)
        colours.add(Color.parseColor("#FFA352"))
        for (i in list.indices) {
            val listProductNameBean: FancyListBean = list[i]
            xValues[i] = listProductNameBean.sTime
            xAxisValues.add(i + 1.0f)
            x1.add(listProductNameBean.totalPrice.toFloat())
            x2.add(listProductNameBean.totalNumber.toFloat())
        }
        //获取最大值
        val max = Collections.max(x1)
        val max1 = Collections.max(x2)
        val max2 = (max(max.toDouble(), max1.toDouble()) + 50f).toFloat()
        yAxisValues.add(x1)
        yAxisValues.add(x2)
        showData(xAxisValues, yAxisValues, labels, colours, xValues, max2)
    }

    fun showData(
        xAxisValues: List<Float>,
        yAxisValues: List<List<Float>>,
        labels: List<String>,
        colours: List<Int>,
        xValues: Array<String?>,
        max: Float
    ) {
        mBinding.barChar1.setVisibility(View.VISIBLE)
        barChartManager?.showMoreBarChart(xAxisValues, yAxisValues, labels, colours, xValues, max)
        barChartManager?.setXAxis(xValues.size.toFloat(), 0f, xValues.size)
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            mBinding.tvStartTime.id -> {
                showDateDialog(true)
            }

            mBinding.tvEndTime.id -> {
                showDateDialog(false)
            }

            mBinding.tvScreen.id -> {
                if (startTime == "" || endTime == "") {
                    ToastUtil.switchToastStyleToWarn("请选择时间")
                    return
                }

                if (startTime == endTime ) {
                    ToastUtil.switchToastStyleToWarn("请不要输入相同的时间")
                    return
                }
                //开始搜索
                mViewModel.screen(startTime, endTime,unit)
            }

            else -> {}
        }
    }

    private fun showDateDialog(isStartTime: Boolean) {
        if (dateStatFragment == null) {
            dateStatFragment = this@HistogramDataFragment.context?.let { DateDialog(it) }
        }
        dateStatFragment?.setListener(object : DialogClickListener {
            override fun onClickListener(type: Int, text: String?) {
                when (type) {
                    dateStatFragment?.type1 -> {
                        if (isStartTime) {
                            mBinding.tvStartTime.text = text
                            startTime = text!!
                        } else {
                            mBinding.tvEndTime.text = text
                            endTime = text!!
                        }
                        Log.d(TAG, "text: " + text)
                    }

                    else -> {}
                }
            }

        })
        dateStatFragment?.type = unit
        dateStatFragment?.show()
    }

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