package com.zj365.health.weight

import android.content.Context
import androidx.recyclerview.widget.GridLayoutManager
import com.tamsiree.rxkit.RxTimeTool
import com.xty.base.dialog.BaseDialog
import com.xty.common.recycleUtils.RecycleItem
import com.xty.common.util.CommonToastUtils
import com.zj365.health.R
import com.zj365.health.adapter.TimesAdapter
import com.zj365.health.adapter.WeekAdapter
import com.zj365.health.databinding.DialogTimeAppointMentBinding
import com.xty.network.model.EnableTime
import java.text.SimpleDateFormat
import java.util.*

class TimeAppointmentDialog(
    context: Context,
    var getNowEnable: (time: String) -> Unit,
    var confirm: (ymd: String, time: String, week: Int) -> Unit
) : BaseDialog(context) {
    val weekAdapter by lazy { WeekAdapter(0, true) }
    val dayAdapter by lazy { WeekAdapter() }

    val morningAdapter by lazy { TimesAdapter(mutableMapOf()) }
    val evenAdapter by lazy { TimesAdapter(mutableMapOf()) }
    var listWeekNumTime = mutableListOf<String>()
    var listWeekNum = mutableListOf<Int>()
    var listWeek = mutableListOf<String>()
    var listDay = mutableListOf<String>()
    val weekArray by lazy { context.resources.getStringArray(R.array.week_day) }
    var mornArray = mutableListOf<String>() //早上预约的时间
    var evenArray = mutableListOf<String>()  //下午预约的时间
    val binding by lazy { DialogTimeAppointMentBinding.inflate(layoutInflater) }

    private val startTime = "09:00:00"  //开始时间
    private val endTime = "13:00:00" //结束时间  即5点到6点这段时间也可以预约6点之后无发预约

    var HourPer = 0  //一个小时能预约的人数
    var weekNow = 0 //当前选中的周

    override fun setLayout() = binding.root

    override fun initView() {
        super.initView()
        percentHeight = 2 / 3f
        setDialogPadding(20, 0, 20, 0)
        getWeeks()
        initWeekAdapter()
        initTimeAdapter()
        binding.mClose.setOnClickListener { dismiss() }
        binding.mConfirm.setOnClickListener {
            //week 从0 开始 0为周日  1 -6 为周一到周六
            if (morningAdapter.current == -1 && evenAdapter.current == -1) {
                CommonToastUtils.showToast("请选择时间")
                return@setOnClickListener
            }
            val selectTime = if (morningAdapter.current == -1) {
                "${evenAdapter.data[evenAdapter.current]}:00"
            } else {
                "${morningAdapter.data[morningAdapter.current]}:00"
            }

            confirm.invoke(
                listWeekNumTime[dayAdapter.position],
                selectTime,
                if (weekNow == 0) 7 else weekNow
            )
            dismiss()
        }
    }

    private fun getWeeks() {
        for (i in 0..6) {
            val now = Calendar.getInstance()
            now.add(Calendar.DATE, i)
            val week = now.get(Calendar.DAY_OF_WEEK)
            val day = if (now.get(Calendar.DATE) < 10) "0${now.get(Calendar.DATE)}" else "${
                now.get(Calendar.DATE)
            }"

            val year = now.get(Calendar.YEAR)
            val month =
                if (now.get(Calendar.MONTH) + 1 < 10) "0${now.get(Calendar.MONTH) + 1}" else "${
                    now.get(Calendar.MONTH) + 1
                }"
            listWeekNumTime.add("$year-$month-$day")
            listWeek.add(weekArray[week - 1])
            listWeekNum.add(week - 1)
            listDay.add("$day")
        }
    }

    //设置周  对应天数
    private fun initWeekAdapter() {
        binding.mWeekRecycle.layoutManager = GridLayoutManager(context, 7)
        binding.mWeekRecycle.adapter = weekAdapter
        weekAdapter.setNewInstance(listWeek)

        binding.mDayRecycle.layoutManager = GridLayoutManager(context, 7)
        binding.mDayRecycle.adapter = dayAdapter
        dayAdapter.setNewInstance(listDay)
        dayAdapter.notifyDataSetChanged()
        weekNow = listWeekNum[0]
        dayAdapter.setOnItemClickListener { _, view, position ->
            getNowEnable.invoke(listWeekNumTime[position])
            dayAdapter.position = position
            dayAdapter.notifyDataSetChanged()
            weekNow = listWeekNum[position]
        }
    }

    //设置具体时间
    private fun initTimeAdapter() {
        val recycleItem = RecycleItem(context, 4, 1)
        recycleItem.setSpace(50, 50)
        binding.mMorinRecycle.addItemDecoration(recycleItem)
        binding.mMorinRecycle.layoutManager = GridLayoutManager(context, 4)
        binding.mMorinRecycle.adapter = morningAdapter

        morningAdapter.setOnItemClickListener { _, view, position ->
            morningAdapter.current = position
            morningAdapter.notifyDataSetChanged()
            evenAdapter.current = -1
            evenAdapter.notifyDataSetChanged()
        }

        binding.mEvenRecycle.addItemDecoration(recycleItem)
        binding.mEvenRecycle.layoutManager = GridLayoutManager(context, 4)
        binding.mEvenRecycle.adapter = evenAdapter

        evenAdapter.setOnItemClickListener { _, view, position ->
            evenAdapter.current = position
            evenAdapter.notifyDataSetChanged()
            morningAdapter.current = -1
            morningAdapter.notifyDataSetChanged()
        }
    }

    fun showInfoDialog(num: Int) {
        show()
        HourPer = num
        setAdapterInfo()
    }

    //时间段9-12  13-18
    private fun setAdapterInfo() {
        if (mornArray.isNotEmpty() && evenArray.isNotEmpty()) {
            morningAdapter.setNewInstance(mornArray)
            evenAdapter.setNewInstance(evenArray)
            return
        }
        val currect = 60 / HourPer  //一个小时的时间间隔
        val minSec = 60 * 1000 * currect //时间间对应的好描述
        val curTimeString = RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))
        var mornStartTime = RxTimeTool.string2Milliseconds("$curTimeString $startTime")
        mornArray.add(RxTimeTool.milliseconds2String(mornStartTime, SimpleDateFormat("HH:mm")))
        for (j in 1 until HourPer * (12 - 9)) {  //循环一个时间段内部的时间
            mornStartTime += minSec
            mornArray.add(RxTimeTool.milliseconds2String(mornStartTime, SimpleDateFormat("HH:mm")))
        }
        var evenStartTime = RxTimeTool.string2Milliseconds("$curTimeString $endTime")
        evenArray.add(RxTimeTool.milliseconds2String(evenStartTime, SimpleDateFormat("HH:mm")))
        for (k in 1 until HourPer * (18 - 13)) {
            evenStartTime += minSec
            evenArray.add(RxTimeTool.milliseconds2String(evenStartTime, SimpleDateFormat("HH:mm")))
        }
        morningAdapter.setNewInstance(mornArray)
        evenAdapter.setNewInstance(evenArray)
        //进来就请求一下当天的数据
        getNowEnable.invoke(listWeekNumTime[0])
    }

    fun refresh(list: MutableList<EnableTime>) {
        val sb = mutableMapOf<String, String>()
        list.forEach {
            sb[it.startTime] = ""
        }

        //当天已经过去的时间无法预约
        val currt = RxTimeTool.getCurTimeString(SimpleDateFormat("yyyy-MM-dd"))
        if (currt == listWeekNumTime[dayAdapter.position]) {  //如果是当天日期
            morningAdapter.data.forEach {
                var itTImeLong = RxTimeTool.string2Milliseconds("$currt $it:00")
                if (itTImeLong <= RxTimeTool.curTimeMills) {
                    sb["$it:00"] = ""
                }
            }
            evenAdapter.data.forEach {
                var itTImeLong = RxTimeTool.string2Milliseconds("$currt $it:00")
                if (itTImeLong <= RxTimeTool.curTimeMills) {
                    sb["$it:00"] = ""
                }
            }
        }

        morningAdapter.times = sb
        evenAdapter.times = sb
        morningAdapter.current = -1
        evenAdapter.current = -1
        morningAdapter.notifyDataSetChanged()
        evenAdapter.notifyDataSetChanged()
    }
}