<template>
  <el-calendar :disabled-date="disabledDate" class="calbox">
    <template #date-cell="{ data }">
      <div @click="dateForm(data)">
        <p :class="[
          selectedDates.includes(data.day) ? 'is-selected' : '',
          isFutureDate(data.day) ? '' : 'disabled'
        ]" @click="handleDateClick(data.day)" class="calendar-date-cell">
          {{ data.day.split('-').slice(1).join('-') }}
          <!-- {{ data.isSelected ? '✔️' : '' }} -->
          <span v-if="selectedDates.includes(data.day)" style="height: 1px;width: 1px">✔️</span>
        </p>
      </div>
    </template>
  </el-calendar>
  <el-drawer v-model="drawer" :title="'当前选择的日期是：' + periodObj.specificDate" :with-header="true" @open="drawerOpen"
    @closed="drawerClean">
    <div style="margin-bottom: 20px;">选择当天时间点</div>
    <div class="timebox" v-for="(item, index) in periodObj.bookingTimeAddRequestList" style="margin-bottom: 40px">
      <span>选择时间点</span>
      <el-time-select 
        v-model="timePickArr[index]" 
        format='HH:mm' 
        style="width: 240px" 
        start="07:00"
        step="00:05" end="20:00"
        placeholder="选择时间点" 
        value-format="HH:mm"
        :style="{ width: '236px', marginLeft: '20px' }"
        @change="saveTime(index)"
        />
      <el-button circle @click="addList(index)"><el-icon>
          <Plus />
        </el-icon></el-button>
      <el-button circle @click="subList(index)" v-if="index > 0"><el-icon>
          <Minus />
        </el-icon></el-button>
    </div>
    <div style="display: flex; align-items: center">
      <el-checkbox v-model="isBook" label="可否预约" size="large" style="margin-right: 15px" />
      <el-button type="success" round @click="saveInfo">保存</el-button>
      <el-button type="danger" round @click="closeForm">取消</el-button>
      <el-button type="primary" round @click="resetForm">重置</el-button>
    </div>
  </el-drawer>
  <el-button type="success" round @click="emittValue" style="margin: 10px 0 10px 25px;">保存</el-button>
  <!-- 展示已经选择的时间端 -->
  <el-card style="max-width: 450px" shadow="hover">
    <template #header>
      <div class="card-header">
        <span>已选择的时间(日历状态:{{ calendarIsSave }})</span>
      </div>
    </template>
    <el-tree
        style="max-width: 600px"
        :data="cardDateTree"
        default-expand-all
    />
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, defineEmits } from 'vue'
import emitter from "@/utils/emitter";
import {WarnInfo} from "@/utils/messageInfo";

const cardDateTree : any= ref([])    //卡片里树组件变量
const calendarIsSave = ref('未保存')
const Selectdate = ref('')
const selectedDates = ref<string[]>([])  //选中的日期
const dateDrawerData: any = ref<{
  visible: boolean
  timeDataList: { value1: string; value2: [Date, Date] }[]  //数组类型
}>({
  visible: false,        // 设定一个初始值
  timeDataList: []      // 设定一个初始值
})
const drawer = ref(false)
const periodObj: any = ref(
  {
    specificDate: '',
    isAvailable: 0,
    bookingTimeAddRequestList: [
      {
        timePoint: ''
      }
    ]
  }
)
const periodMap = new Map()  //将点击保存的数据存入map，也为后续遍历出来做准备
const timePickMap = new Map()  //暂存每次的时间段
const count = ref(0)  //计数君
const timePickArr: any = ref([])
const minArr: any = ref([])
const maxArr: any = ref([])
const isTrue = ref(false)  //判断当前键是否有值
const isBook = ref(true)
const appointmentDateAddRequestList: any = ref([])  //传给后端的预约时间
const emit = defineEmits(['calendar-Info'])
onMounted(() => {
  for (let i = 0; i <= 50; i++) {  //初始化人数选择的数组
    minArr.value[i] = 5 + i
    maxArr.value[i] = 6 + i
  }
})
const dateForm = (object: any) => {   //赋值当前日期和弹出抽屉
  const nowClick = new Date(object.date).toISOString().split('T')[0]   //格式化时间  年-月-日
  if (isFutureDate(nowClick)) {
    Selectdate.value = object.day
    periodObj.value.specificDate = object.day
    drawer.value = true
  } else {
    return;
  }
}
const closeForm = () => {  //缺重置表单
  drawer.value = false
}
const addList = (index: number) => {  //添加当前日期的时间段
  count.value += 1
  if (count.value <= 15 && judgeNull(periodObj.value.bookingTimeAddRequestList)) {
    periodObj.value.bookingTimeAddRequestList.push(
      {
        timePoint: ''
      }
    )
    timePickArr.value.push([])
  } else {
    WarnInfo('请填写完前一段日期后再添加')
  }
  // console.log(index,'--->',periodObj.value);
}
const subList = (index: number) => {
  if (index != 0) {
    periodObj.value.bookingTimeAddRequestList.splice(index, 1)
  }
  calendarIsSave.value = '未保存'
  //更新日期、时间段集合
  periodMap.set(periodObj.value.specificDate,periodObj.value)
  timePickMap.set(periodObj.value.specificDate,timePickArr.value)
  cardDateTree.value.splice(0,cardDateTree.value.length)
  periodMap.forEach(loopPeriodMap)
}
const saveTime = (index: number) => {  //将时间点存入periodObj对象中
  // console.log('时间点数组--->',timePickArr.value);
  try {
    periodObj.value.bookingTimeAddRequestList[index].timePoint = timePickArr.value[index]
  } catch {
    periodObj.value.bookingTimeAddRequestList[index].timePoint = ''
  }
}

const saveInfo = () => {  //保存当前日期的时间和人数信息
  //时间段和人数判空
  if (!judgeNull(periodObj.value.bookingTimeAddRequestList)) {
    WarnInfo('请填写完整时间段和人数！')
    return;
  }
  isBook ? periodObj.value.isAvailable = 1 : periodObj.value.isAvailable = 0
  periodMap.set(periodObj.value.specificDate, periodObj.value)
  timePickMap.set(periodObj.value.specificDate, timePickArr.value)
  cardDateTree.value.splice(0,cardDateTree.value.length)
  drawer.value = false
  periodMap.forEach(loopPeriodMap)
  // console.log('periodObj--->', periodObj.value);
}

const loopPeriodMap = ( value: any,key: any,map: any ) => {
  console.log('value---->', value , 'key---->', key)
  cardDateTree.value.push({
    label:key,
    children: dealTreeChildren(value.bookingTimeAddRequestList)
  })
}

const dealTreeChildren = ( arr : any ) => {   //处理map集合中时间段和人数格式，最后返回给树
  // console.log('arr--->',arr)
  let labelArrObj : any = []
  arr.forEach((item : any) => {
    labelArrObj.push({
      label: '时间：' + item.timePoint
    })
  })
  // console.log('value---->', arr)
  return labelArrObj;
}

const drawerClean = () => {   //清空对象
  periodObj.value = {
    specificDate: Selectdate.value,
    isAvailable: 0,
    bookingTimeAddRequestList: [
      {
        timePoint: ''
      }
    ]
  }
  timePickArr.value = []
  count.value = 0;
}

const drawerOpen = () => {  //抽屉打开时
  isTrue.value = periodMap.has(periodObj.value.specificDate)  //判断之前有没有存过这个值
  if (isTrue.value) {
    periodObj.value = periodMap.get(periodObj.value.specificDate)
    timePickArr.value = timePickMap.get(periodObj.value.specificDate)
    console.log('timePickArr--->', timePickArr.value);
  }
}

const resetForm = () => {  //重置表格
  drawerClean()  //视觉上先删除
  if (isTrue.value) {  //存过的一律从map中清除
    periodMap.delete(periodObj.value.specificDate)
    timePickMap.delete(periodObj.value.specificDate)
  }
  calendarIsSave.value = '未保存'
  cardDateTree.value.splice(0,cardDateTree.value.length)
  periodMap.forEach(loopPeriodMap)
}

const emittValue = () => {  //点击保存后将值传给父组件
  appointmentDateAddRequestList.value.splice(0, appointmentDateAddRequestList.value.length)  //防止用户狂点
  periodMap.forEach(mapFun)
  if(appointmentDateAddRequestList.value.length === 0) {
    WarnInfo('请添加信息后再保存')
    return;
  }
  emit('calendar-Info', appointmentDateAddRequestList.value)
  emitter.on('clear', () => {   //清空日期map集合
    periodMap.clear()
  })
  calendarIsSave.value = '已保存'
}

const mapFun = (value: any, key: any, map: any) => {  //遍历map的统一函数
  if (periodMap.has(key)) {
    appointmentDateAddRequestList.value.push(value)
  }
  console.log(appointmentDateAddRequestList.value);
}

const judgeNull = (List: any) => {  //时间段和人数统一判空方法
  // console.log('List--->', List);
  if (List.some((item: any) => item.timePoint === '')) {
    return false;
  }
  return true;
}

const disabledDate = (date: any) => {   //判断日期是否是今天
  const today = new Date()
  const dateString = date.toISOString().split('T')[0]
  const todayString = today.toISOString().split('T')[0]
  return dateString < todayString
}

const isFutureDate = (date: any) => {  //禁用之前的
  const today = new Date().toISOString().split('T')[0]
  return date >= today
}

const handleDateClick = (date: any) => {
  const dateStr = date
  if (isFutureDate(dateStr)) {
    if (selectedDates.value.includes(dateStr)) {
      selectedDates.value = selectedDates.value.filter(d => d !== dateStr)
    } else {
      selectedDates.value.push(dateStr)
      if (!dateDrawerData.value[dateStr]) {
        dateDrawerData.value[dateStr] = {
          visible: true,
          timeDataList: []
        }
      } else {
        dateDrawerData.value[dateStr].visible = true;
      }
    }
  }
}
</script>

<style scoped>
.calbox {
  width: 450px;
  height: 300px;
  font-size: 12px;
  --el-calendar-cell-width: 30px;
}

.timebox {
  margin-bottom: 20px;
}

:deep(.el-calendar__body) {
  padding: 12px 28px 12px 0px;
}

.calendar-date-cell {
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

/*这是过去日期不能选中的样式，请勿删除*/
.disabled {
  color: #dcdfe6;
  pointer-events: none;
}
</style>