package com.module.backstage.vm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.module.backstage.R
import com.module.backstage.chart.FancyListBean
import com.module.backstage.repo.HistogramDataFragmentRepo
import com.module.backstage.utils.TimeUtil
import com.module.database.room.entity.LocalOrderBean
import com.quyunshuo.androidbaseframemvvm.base.mvvm.vm.BaseViewModel
import com.quyunshuo.androidbaseframemvvm.common.util.ToastUtil
import com.quyunshuo.androidbaseframemvvm.common.util.UiUtil
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.TimeZone
import javax.inject.Inject

/**
 * HomeFragment 的 VM 层
 *
 * @author Qu Yunshuo
 * @since 2021/8/5 11:11 下午
 */
@HiltViewModel//@HiltViewModel 注解的作用是将 ViewModel 标记为可以由 Hilt 管理的依赖项。当你将 @HiltViewModel 注解添加到 ViewModel 类上时，Hilt 会自动处理 ViewModel 的创建和注入过程。这样，你就不需要手动调用 ViewModelProvider 来获取 ViewModel 实例了。
class HistogramDataFragmentVM @Inject constructor(private val mRepo: HistogramDataFragmentRepo) :
    BaseViewModel() {
    private val TAG = "DataStatFragmentVM"
    private var _allLocalOrder = MutableLiveData<List<FancyListBean>>()
    val allLocalOrder: MutableLiveData<List<FancyListBean>> get() = _allLocalOrder

    /**
     * 搜索指定时间的数据
     */
    fun screen(sTime: String, eTime: String, unit: Int) {
        var startTime = sTime
        var endTime = eTime
        Log.d(TAG, "screen: " + unit)
        //1.校验
        if (!TimeUtil.compare_date(sTime, eTime)) {
            when (unit) {
                0 -> {
                    startTime = "$sTime:00:00"
                    endTime = "$eTime:59:59"
                    val l1: Long = TimeUtil.dateDiff(startTime, endTime, "yyyy-MM-dd")
                    if (l1 > 2) {
                        ToastUtil.showToast(UiUtil.getStringRes(R.string.base_tian))
                        return
                    }
                }

                1 -> {
                    val l2: Long = TimeUtil.dateDiff(sTime, eTime, "yyyy-MM-dd")
                    if (l2 > 31) {
                        ToastUtil.showToast(UiUtil.getStringRes(R.string.base_yue))
                        return
                    }
                }

                2 -> {
                    val i: Int = TimeUtil.mouthDiff(sTime, eTime)
                    if (i > 12) {
                        ToastUtil.showToast(UiUtil.getStringRes(R.string.base_yues))
                        return
                    }
                }

                3 -> {
                    val i1: Int = TimeUtil.yearDateDiff(sTime, eTime)
                    if (i1 == -100) {
                        ToastUtil.showToast(UiUtil.getStringRes(R.string.base_sjcw))
                        return
                    }
                    if (i1 > 10) {
                        ToastUtil.showToast(UiUtil.getStringRes(R.string.base_nian))
                        return
                    }
                }
            }
            //2.数据查询
            viewModelScope.launch {
                val list = mRepo.queryTime(startTime, endTime)
                Log.d(TAG, "screen: " + list + startTime + ":" + endTime)

                //3.查询出来的数据进行汇总：比如按照小时、日、月、年进行汇总
                val map = LinkedHashMap<String, ArrayList<LocalOrderBean>>()
                for (bean in list) {
                    val name: String = bean.name
                    var time = ""
                    val sn: String = bean.sn
                    //时间格式化
                    var sdf: SimpleDateFormat? = null
                    sdf = if (unit == 1) {
                        SimpleDateFormat("yyyy-MM-dd")
                    } else if (unit == 2) {
                        SimpleDateFormat("yyyy-MM")
                    } else if (unit == 3) {
                        SimpleDateFormat("yyyy")
                    } else {
                        SimpleDateFormat("MM-dd HH:00")
                    }


                    val calendar = Calendar.getInstance()
                    try {
                        calendar.time =
                            SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(bean.time)
                    } catch (e: ParseException) {
                        e.printStackTrace()
                    }
                    time = sdf.format(calendar.timeInMillis)
                    //            time=sdf.format(time);
                    if (map.containsKey(time)) {
                        map[time]!!.add(bean)
                    } else {
                        val orderBeans = ArrayList<LocalOrderBean>()
                        orderBeans.add(bean)
                        map[time] = orderBeans
                    }
                }

                val orderList: ArrayList<FancyListBean> = ArrayList<FancyListBean>()
                for ((key, value) in map) {
                    var totalPrice = 0.0
                    for (localOrderBean in value) {
                        totalPrice += localOrderBean.price
                    }

                    val fancyListBean: FancyListBean = FancyListBean(
                        sTime = key,
                        totalNumber = value.size,
                        totalPrice = totalPrice,
                        productName = ""
                    )

                    orderList.add(fancyListBean)
                }
                if (orderList.size == 0) {
                    ToastUtil.switchToastStyleToWarn("这个时间段没有销售数据")
                    return@launch
                }
                _allLocalOrder.value = orderList
                Log.d(TAG, "screen: " + orderList)
            }
        }

    }

    /**
     * 获取今天，明天的日期。
     */
    fun todoTime(sky:Int) :String{
        var year: String
        var month: String
        var day: String
        var hour:String

        val cal = Calendar.getInstance()
        cal.timeZone = TimeZone.getTimeZone("GMT+8:00")
        cal.add(Calendar.DATE, sky) // 在日期中增加天数,1天,跨月，会自动修改，牛逼

        year = cal[Calendar.YEAR].toString()
        month = (cal[Calendar.MONTH] + 1).toString()
        if (month.length < 2) {
            month = "0$month"
        }
        day = cal[Calendar.DATE].toString()
        if (day.length < 2) {
            day = "0$day"
        }
        if (cal[Calendar.AM_PM] == 0) {
            hour = cal[Calendar.HOUR].toString()
            if (hour.length < 2) {
                hour = "0$hour"
            }
        } else {
            hour = (cal[Calendar.HOUR] + 12).toString()
        }
        return "$year-$month-$day 00"
    }

}