<script setup lang="ts" name="PlanList">
import { ref, onMounted, reactive, watchEffect, nextTick } from 'vue'
import customFab from '@/components/customFab.vue'
import { useDict } from '@/common/utils/dict'
import PullList from '../../components/List/PullList.vue'
import CustomCard from './modules/customCard.vue'
import { TAmGuestReportPlanMobileList, TAmGuestReportPlanMobile } from '@/api/resturant/customerMeal.ts'
import moreOption from '@/static/image/train/moreOption.png'
const { menu_type } = useDict('menu_type')
// import { showSuccessToast } from 'vant'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
// const router = useRouter()
const pullListRef = ref<InstanceType<typeof PullList>>()
const now = new Date()
const nowStamp = now.getTime()
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  guestReason: '',
  menuType: '',
  guestNum: '',
  reportStarttime: '',
  reportEndtime: '',
  addMealExplain: '',
  createBy: userStore.userInfo.userId
})
const reportStarttimeshowPicker = ref(false)
const reportEndtimeshowPicker = ref(false)

/**
 * 选择培训类别
 * @param item
 */
function handleChooseMenuType(item:any) {
  if (queryParams.value.menuType === item.value) {
    queryParams.value.menuType = ''
  } else {
    queryParams.value.menuType = item.value
  }
}

const reportStarttimeonConfirm = (e) => {
  console.log(e)
  queryParams.value.reportStarttime = timestampToTime(e.value)
  // queryParams.value.reportStarttime = selectedValues.join('-')
  // reportStarttimeshowPicker.value = false
}
const reportEndtimeonConfirm = (e) => {
  queryParams.value.reportEndtime = timestampToTime(e.value)
}

// 请求方法，传入PullList组件，需返回{rows: [], total: number}
function onRequest(query?: any, isRefresh?: boolean): Promise<{rows: any[], total: number}> {
  return TAmGuestReportPlanMobileList(query)
}

function onSearch() {
  pullListRef.value?.refresh()
}

const moreOptionFormVisible = ref(false)

function onSearchByMore() {
  moreOptionFormVisible.value = false
  moreOptionFormRef.value.close()
  onSearch()
}

/**
 * 客户报餐详情
 */
function handleDetail(item:any):void {
  // router.push({
  //   path: '/resturant/customerMealDetail',
  //   query: {
  //     guestId: item.id,
  //     type: 'detail'
  //   }
  // })
  uni.navigateTo({
    url: '/resturant/customerMeal/detail?guestId=' + item.id + '&type=detail'
  })
}


/**
 * 修改客户报餐
 */
function handleUpdate(item:any):void {
  // router.push({
  //   path: '/resturant/customerMealDetail',
  //   query: {
  //     guestId: item.id,
  //     type: 'update'
  //   }
  // })
  uni.navigateTo({
    url: '/resturant/customerMeal/detail?guestId=' + item.id + '&type=update'
  })
}

/**
 * 删除客户报餐
 */
function handleDelete(item):void {
  TAmGuestReportPlanMobile(item.id).then(res => {
    console.log(res)
      uni.showToast({
        title: '删除成功',
      })
    pullListRef.value?.refresh()
  })
}
/**
 * 新增客户报餐
 */
function onClickAdd():void {
  // router.push({
  //   path: '/resturant/customerMealDetail',
  //   query: {
  //     type: 'add'
  //   }
  // })

  uni.navigateTo({
    url: '/resturant/customerMeal/detail?type=add'
  })
}

function handleSearchChange(e) {
  queryParams.value.guestReason = e.detail // 手动更新数据:ml-citation{ref="2,8" data="citationList"}
}

const moreOptionFormRef:any = ref(null)

const openMoreOption = () =>{
  moreOptionFormVisible.value = true
  moreOptionFormRef.value.open('right')
}

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 reportStarttimeshowPickerRef:any = ref(null)
const showreportStarttimeshowPickerRef = () =>{
  reportStarttimeshowPickerRef.value.open()
}

const reportEndtimeshowPickerRef:any = ref(null)
const showreportEndtimeshowPickerRef = () =>{
  reportEndtimeshowPickerRef.value.open()
}

</script>

<template>
    <div class="query-wrap">
    
      <div class="option-container search-pad">
        <van-search
          class="search-input"
          :value="queryParams.guestReason"
          @change="handleSearchChange"
          shape="round"
          placeholder="请输入就餐事由"
          useActionSlot
          @search="onSearch"
          @clear="onSearch">
          <template #action>
            <div class="search-btn" @click="onSearch">搜索</div>
          </template>
        </van-search>
        <img
          class="more-option"
          :src="moreOption"
          alt=""
          @tap="openMoreOption">
      </div>
    </div>
    <!-- </div> -->
    <PullList ref="pullListRef" v-model:query-string="queryParams" :isFixed="false" zHeight="83vh" :request-method="onRequest">
      <template #default="{ item, index }">
        <div style="padding: 0 30rpx;" >
          <CustomCard
            :item="item"
            @handle-detail="handleDetail"
            @handle-update="handleUpdate"
          />
        </div>
      </template>
    </PullList>
    <customFab  icon @click="onClickAdd" />
    <!-- 右侧弹出 -->
    <uv-popup 
      ref="moreOptionFormRef" 
      mode="right" 
      :custom-style="{ width: '620rpx', height: '100%' }"
    >
      <view class="label">
        <view class="title">就餐类别</view>
        
        <view class="option-select-container">
          <view
            class="option-item"
            :class="[queryParams.menuType === item.value ? 'active-item' : '']"
            v-for="(item, index) in menu_type"
            :key="index"
            @click="handleChooseMenuType(item)"
          >
            {{ item.label }}
          </view>
        </view>
        <uv-form ref="formRef" labelWidth="140" label-position="top" label :model="queryParams">


          <uv-form-item customStyle="padding: 20rpx 32rpx;" borderBottom label="就餐人数">
            <uv-input 
              v-model="queryParams.guestNum"
              placeholder="请输入就餐人数"
            />
          </uv-form-item>



          <uv-form-item customStyle="padding: 20rpx 32rpx;" borderBottom label="食谱开始时间"   @click="showreportStarttimeshowPickerRef">
            <uv-input 
              v-model="queryParams.reportStarttime"
              placeholder="请选择食谱开始时间"
              disabled
              border="none" 
              disabledColor="#fff"
            />
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-datetime-picker
            ref="reportStarttimeshowPickerRef"
            :show="reportStarttimeshowPicker"
            mode="date"
            :minDate="nowStamp"
            :formatter="formatter"
            @confirm="reportStarttimeonConfirm"
            @cancel="reportStarttimeshowPicker = false"
          />



          <uv-form-item customStyle="padding: 20rpx 32rpx;" borderBottom label="食谱开始时间"   @click="showreportEndtimeshowPickerRef">
            <uv-input 
              v-model="queryParams.reportEndtime"
              placeholder="请选择食谱结束时间"
              disabled
              border="none" 
              disabledColor="#fff"
            />
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-datetime-picker
            ref="reportEndtimeshowPickerRef"
            :show="reportEndtimeshowPicker"
            mode="date"
            :minDate="nowStamp"
            :formatter="formatter"
            @confirm="reportEndtimeonConfirm"
            @cancel="reportEndtimeshowPicker = false"
          />
           <uv-form-item customStyle="padding: 20rpx 32rpx;"  label="加餐说明">
            <uv-input
              v-model="queryParams.addMealExplain"
              placeholder="请输入加餐说明"
            />
          </uv-form-item>
           <div class="more-option-search-btn">
            <uv-button style="width: 100%;" type="primary" @click="onSearchByMore">确认</uv-button>
          </div>
        </uv-form>
        
      </view>
    </uv-popup>



</template>

<style lang="less" scoped>

  .option-container {
    display: flex;
    align-items: center;
    .more-option {
       height: 32rpx;
      width: 32rpx;
      margin-left: 24rpx;
    }
    .search-input {
      flex: 1;

    }
  }

.search-pad {
  padding: 30rpx;
  box-sizing: border-box;
}
.van-search {
  position: relative;
  z-index: 1;
  padding: 1rem;
  // min-height: 4.4rem;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 40rpx  rgba(64, 103, 251, 0.14);
  // overflow: hidden;
}
.label{
  .title{
    margin-top: 1.2rem;
    padding-left: 1.2rem;
    font-size: 1.4rem;
    font-weight: 700;
    color: rgba(62, 62, 62, 1);
  }
  .option-select-container {
    padding: 1.2rem;
    padding-left: 0;
    display: flex;
    flex-wrap: wrap;
    .option-item {
      border: thin solid rgb(222, 219, 219);
      box-shadow: 0 4rpx 40rpx  rgba(64, 103, 251, 0.14);
      padding: 0.5rem 1.2rem;
      margin-top: 0.8rem;
      border-radius: 10em;
      margin-left: 1.2rem;
    }
    .active-item {
      border: thin solid rgba(71, 115, 252, 1);
    }
  }
}
.more-option-search-btn {
  padding: 24rpx;
  position: absolute;
  bottom: 80rpx;
  width: 100%;
  left: 0;
}
:deep(.van-pull-refresh__head) {
  height: 0;
}
.search-pad {
  padding: 30rpx;
  box-sizing: border-box;
}
:deep(.van-search) {
  position: relative;
  z-index: 1;
  padding: 20rpx;
  // min-height: 4.4rem;
  border-radius:24rpx;
  box-shadow: 0 4rpx 40rpx rgba(64, 103, 251, 0.14);
  // overflow: hidden;
}
.search-btn {
  padding: 0 16.6rpx;
}
</style>
