<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { insertTAmGuestReportPlanInfo, TAmGuestReportPlanMobileDetail } from '@/api/resturant/customerMeal.ts'
import { parseTime, selectDictLabel } from '@/common/utils/ruoyi'
import { useDict } from '@/common/utils/dict'

const { menu_type, bilateral_factory_company } = useDict('menu_type', 'bilateral_factory_company')

const routeType = ref('')
const routeGuestId = ref('')
onLoad((option) => {
  console.log('option',option)
  routeType.value = option.type ? option.type : ''
  routeGuestId.value = option.guestId ? option.guestId : ''
  if (option.type === 'detail' || option.type === 'update') {
    getDetail()
  }
})

const formRef = ref()
const form = reactive({
  id: '',
  eatCompanyId: '',
  menuType: '',
  menuTypeText: '',
  reportStarttime: '',
  reportEndtime: '',
  guestRemarks: '',
  guestReason: '',
  guestNum: '',
  addMealExplain: '',
  staffList: []
})

const isDetail = computed(() => routeType.value === 'detail')
const eatCompanyText = ref('')
const showPickerMenuType = ref(false)
const showPickerEat = ref(false)
const reportStarttimeshowPicker = ref(false)
const reportEndtimeshowPicker = ref(false)
const loading = ref(false)
const datesInRange:any = ref([])
const breakfast = ref(false)
const lunch = ref(false)
const dinner = ref(false)

// 获取详情
function getDetail() {
  TAmGuestReportPlanMobileDetail(routeGuestId.value).then(response => {
    Object.assign(form, response.data)
    form.menuTypeText = menu_type.value.find(item => item.value === response.data.menuType)?.label || ''
    datesInRange.value = response.data.staffList
    changeReportMeal()
  })
}

// 行内早午晚餐反选
function changeReportMeal() {
  breakfast.value = !datesInRange.value.some(item => item.reportBreakfast === '0')
  lunch.value = !datesInRange.value.some(item => item.reportLunch === '0')
  dinner.value = !datesInRange.value.some(item => item.reportDinner === '0')
}

// 提交表单
function onClickSubmit() {
  formRef.value?.validate().then(() => {
    form.staffList = datesInRange.value
    loading.value = true
    insertTAmGuestReportPlanInfo(form).then(res => {
      uni.showToast({ title: res.msg })
      setTimeout(() => uni.navigateBack(), 1000)
    }).finally(() => {
      loading.value = false
    })
  })
}

// 日期选择确认
const reportStarttimeonConfirm = (e) => {
  form.reportStarttime = timestampToTime(e.value)
  reportStarttimeshowPicker.value = false
  onInput(0)
}

const reportEndtimeonConfirm = (e) => {
  form.reportEndtime = timestampToTime(e.value)
  reportEndtimeshowPicker.value = false
  onInput(0)
}




// 日期范围处理
function onInput(event) {
  if (event === 1) {
    form.reportEndtime = ''
    datesInRange.value = []
  }
  
  if (!form.reportStarttime || !form.reportEndtime) {
    datesInRange.value = []
    return
  }
  
  let start = new Date(form.reportStarttime)
  let end = new Date(form.reportEndtime)
  
  if (start > end) {
    form.reportEndtime = ''
    uni.showToast({ title: '开始时间必须小于结束时间', icon: 'none' })
    datesInRange.value = []
    return
  }
  
  datesInRange.value = []
  while (start <= end) {
    const dateStr = parseTime(start, '{y}-{m}-{d}')
    const weekDay = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][start.getDay()]
    
    if (start.getDay() !== 0) { // 排除周日
      datesInRange.value.push({
        reportTime: dateStr,
        reportWeek: weekDay,
        reportBreakfast: '1',
        reportLunch: '1',
        reportDinner: '1'
      })
    }
    
    start.setDate(start.getDate() + 1)
  }
  
  breakfast.value = true
  lunch.value = true
  dinner.value = true
}

// 全选/取消全选
function allCheckMeal(type, val) {
  datesInRange.value.forEach(element => {
    element[type] = val ? '1' : '0'
  })
}

// 单个切换
function handleChangeReportMealSingle(type, val) {
  if (val === '0') {
    switch (type) {
      case 'reportBreakfast': breakfast.value = false; break
      case 'reportLunch': lunch.value = false; break
      case 'reportDinner': dinner.value = false; break
    }
  } else if (!datesInRange.value.some(item => item[type] === '0')) {
    switch (type) {
      case 'reportBreakfast': breakfast.value = true; break
      case 'reportLunch': lunch.value = true; break
      case 'reportDinner': dinner.value = true; break
    }
  }
}

const eatCompanyRef:any = ref(null)
// 打开选择器
function handleChooseEat() {
  if (isDetail.value) return
  eatCompanyRef.value?.open()
}

 


// 确认 - 就餐公司
const onConfirmEat = (e) => {
  console.log(e)
  let selectedOptions= e.value
  form.eatCompanyId = selectedOptions[0]?.value
  eatCompanyText.value = selectedOptions[0]?.label
  showPickerEat.value = false
}

const menuTypeRef:any = ref(null)
function handleChooseMenuType() {
  if (isDetail.value) return
  menuTypeRef.value.open()
  showPickerMenuType.value = true
}
// 确认 - 就餐类别
const onConfirmMenuType = (e) => {
    let selectedOptions= e.value
  form.menuType = selectedOptions[0]?.value
  form.menuTypeText = selectedOptions[0]?.label
  showPickerMenuType.value = false
}

const reportStarttimePickerRef:any = ref(null)
function handlechooseBeginDate() {
  if (isDetail.value) return
  reportStarttimePickerRef.value.open()
}
const reportEndtimePickerRef:any = ref(null)
function handleChooseEndTime() {
  if (isDetail.value) return
  reportEndtimePickerRef.value.open()
}

// 表单验证规则
const rules = reactive({
  guestReason: [
    { required: true, message: '请输入就餐事由' }
  ],
  guestNum: [
    { required: true, message: '请输入就餐人数' }
  ],
  eatCompanyId: [
    { required: true, message: '请选择就餐公司' }
  ],
  menuType: [
    { required: true, message: '请选择就餐餐别' }
  ],
  reportStarttime: [
    { required: true, message: '请选择食谱开始时间' }
  ],
  reportEndtime: [
    { required: true, message: '请选择食谱结束时间' }
  ],
  addMealExplain: [
    { required: false, message: '请输入加餐说明' }
  ],
  guestRemarks: [
    { required: false, message: '请输入备注' }
  ]
})


function timestampToTime(timestamp ,type: string = 'date') {
  const date = new Date(timestamp); // 时间戳转 Date 对象
  const year = date.getFullYear();  // 年
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月（补零）
  const day = String(date.getDate()).padStart(2, '0'); // 日（补零）
  const hours = String(date.getHours()).padStart(2, '0'); // 时（补零）
  const minutes = String(date.getMinutes()).padStart(2, '0'); // 分（补零）
  const seconds = String(date.getSeconds()).padStart(2, '0'); // 秒（补零）
  if(type=='date') {
    return `${year}-${month}-${day}`;
  }
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
const formatter = (type, value) =>{
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  if (type === 'hour') {
    return `${value}时`
  }
  if (type === 'minute') {
    return `${value}分`
  }
  return value
}
const now = new Date()
const nowStamp = now.getTime()
</script>

<template>
<div class="container full float-bottom">
  <div class="container__body">
    <div class="container__card flex form-card-container">
      <uv-form ref="formRef" labelWidth="140" label-position="top" :rules="rules" :model="form">
        <uv-cell-group>
          <uv-form-item customStyle="padding: 20rpx 32rpx;" borderBottom label="就餐事由" prop="guestReason" required>
            <uv-input
              v-model="form.guestReason"
              placeholder="请输入就餐事由"
              :disabled="isDetail"
              disabledColor="#fff"
              border="none"
            />
          </uv-form-item>
          
          <uv-form-item customStyle="padding: 20rpx 32rpx;" borderBottom label="就餐人数" prop="guestNum" required>
            <uv-input
              v-model="form.guestNum"
              type="number"
              placeholder="请输入就餐人数"
              :disabled="isDetail"
              disabledColor="#fff"
              border="none"
            />
          </uv-form-item>
          
          <uv-form-item customStyle="padding: 20rpx 32rpx;" borderBottom label="就餐公司" prop="eatCompanyId" required  @click="handleChooseEat">
            <uv-input
              v-model="eatCompanyText"
              disabled
              disabledColor="#fff"
              placeholder="请选择"
              border="none"
            />
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-picker
            keyName="label"
            ref="eatCompanyRef"
            :columns="[bilateral_factory_company]"
            @confirm="onConfirmEat"
          />
          
          <uv-form-item customStyle="padding: 20rpx 32rpx;" borderBottom label="就餐餐别" prop="menuType" required  @click="handleChooseMenuType">
            <uv-input
              v-model="form.menuTypeText"
              disabled
              disabledColor="#fff"
              placeholder="请选择"
              border="none"
            />
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          
          <uv-picker
            ref="menuTypeRef"
            keyName="label"
            :columns="[menu_type]"
            @confirm="onConfirmMenuType"
          />
          
          <uv-form-item customStyle="padding: 20rpx 32rpx;" borderBottom label="食谱开始时间" prop="reportStarttime" required  @click="handlechooseBeginDate">
            <uv-input
              v-model="form.reportStarttime"
              disabled
              disabledColor="#fff"
              placeholder="请选择食谱开始时间"
              border="none"
            />
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          
          <uv-datetime-picker
            ref="reportStarttimePickerRef"
            :value="form.reportStarttime"
            mode="date"
            :min-date="nowStamp"
            :formatter="formatter"
            @confirm="reportStarttimeonConfirm"
          />
          
          <uv-form-item customStyle="padding: 20rpx 32rpx;" borderBottom label="食谱结束时间" prop="reportEndtime" required  @click="handleChooseEndTime">
            <uv-input
              v-model="form.reportEndtime"
              disabled
              disabledColor="#fff"
              placeholder="请选择食谱结束时间"
              border="none"
            />
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          
          <uv-datetime-picker
            ref="reportEndtimePickerRef"
            :value="form.reportEndtime"
            mode="date"
            :min-date="nowStamp"
            :formatter="formatter"
            @confirm="reportEndtimeonConfirm"
          />
          
          <uv-form-item customStyle="padding: 20rpx 32rpx;" borderBottom label="加餐说明" prop="addMealExplain">
            <uv-input
              v-model="form.addMealExplain"
              placeholder="请输入加餐说明"
              :disabled="isDetail"
              disabledColor="#fff"
              border="none"
            />
          </uv-form-item>
          
          <uv-form-item customStyle="padding: 20rpx 32rpx;" borderBottom label="备注" prop="guestRemarks">
            <uv-input
              v-model="form.guestRemarks"
              placeholder="请输入备注"
              :disabled="isDetail"
              disabledColor="#fff"
              border="none"
            />
          </uv-form-item>
        </uv-cell-group>
        
        <uv-cell-group style="margin-top: 30px;">
          <uv-cell title="报餐清单">
            <template #right-icon>
              <view class="flex-center-container">
                <view class="all-check-container">
                  <uv-switch
                    :disabled="isDetail"
                    v-model="breakfast"
                    @change="(event) => allCheckMeal('reportBreakfast', event)"
                  />
                  <text class="check-text">早餐</text>
                </view>
                <view class="all-check-container">
                  <uv-switch
                    :disabled="isDetail"
                    v-model="lunch"
                    @change="(event) => allCheckMeal('reportLunch', event)"
                  />
                  <text class="check-text">午餐</text>
                </view>
                <view class="all-check-container">
                  <uv-switch
                    :disabled="isDetail"
                    v-model="dinner"
                    @change="(event) => allCheckMeal('reportDinner', event)"
                  />
                  <text class="check-text">晚餐</text>
                </view>
              </view>
            </template>
          </uv-cell>
          
          <uv-cell 
            v-for="(item, index) in datesInRange" 
            :key="index"
            :title="`${item.reportTime}（${item.reportWeek}）`"
          >
            <template #right-icon>
              <view class="flex-center-container">
                <view class="check-container">
                  <text class="check-text">早</text>
                  <uv-switch
                    :disabled="isDetail"
                    v-model="item.reportBreakfast"
                    active-value="1"
                    inactive-value="0"
                    @change="(event) => handleChangeReportMealSingle('reportBreakfast', event)"
                  />
                </view>
                <view class="check-container">
                  <text class="check-text">午</text>
                  <uv-switch
                    :disabled="isDetail"
                    v-model="item.reportLunch"
                    active-value="1"
                    inactive-value="0"
                    @change="(event) => handleChangeReportMealSingle('reportLunch', event)"
                  />
                </view>
                <view class="check-container">
                  <text class="check-text">晚</text>
                  <uv-switch
                    :disabled="isDetail"
                    v-model="item.reportDinner"
                    active-value="1"
                    inactive-value="0"
                    @change="(event) => handleChangeReportMealSingle('reportDinner', event)"
                  />
                </view>
              </view>
            </template>
          </uv-cell>
        </uv-cell-group>
      </uv-form>
    </div>
  </div>    



     <uv-button
      :loading="loading"
      class="button-submit float-bottom"
      shape="circle"
      color="linear-gradient(to bottom, #4773FC, #6D9BFD)"
      customStyle="margin-top: 50rpx" 
      @click="onClickSubmit">{{ routeType === 'add' ? '提交' : '修改' }}</uv-button>
</div>
</template>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  box-sizing: border-box;
}

.flex-center-container {
  display: flex;
  align-items: center;
  
  .all-check-container {
    display: flex;
    align-items: center;
    margin-left: 20rpx;
    
    .check-text {
      margin-left: 10rpx;
      font-size: 28rpx;
    }
  }
  
  .check-container {
    display: flex;
    align-items: center;
    margin-right: 20rpx;
    
    .check-text {
      margin-right: 10rpx;
      font-size: 28rpx;
    }
  }
}
</style>