<script setup lang="ts" name="DishSample">
import { ref, onMounted, reactive, watchEffect, nextTick } from 'vue'
// import axios from 'axios'
import { getToken } from '@/common/utils/auth'
import useUserStore from '@/store/modules/user'
// import { useRouter, useRoute } from 'vue-router'
import { listAllSpecifics, insertRetentionSampleAndDetail, tAmRetentionSampleMobileDetail } from '@/api/resturant/dishSample.ts'
// import { FormInstance, showSuccessToast } from 'vant'
// import { formatDate } from '@/component/calendar/generateDates'
import { selectDictLabel } from '@/common/utils/ruoyi'
import { useDict } from '@/common/utils/dict'
const { menu_type, sample_meal } = useDict('menu_type', 'sample_meal')
import request from '@/common/utils/request'
const formatDate = (date, fmt): string => {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}
const padLeftZero = (str) => {
  return ('00' + str).substr(str.length)
}
const userStore = useUserStore()
// const router = useRouter()
// const route = useRoute()
const formRef = ref<FormInstance>()
const form:any = reactive({
  id: '',
  sampleDate: formatDate(new Date(), 'yyyy-MM-dd'),
  sampleHour: '48',
  sampleMeal: '',
  sampleMealText: '',
  fileList: [],
  fileListSub: [],
  detailList: []
})
const loading = ref(false)
const showPicker = ref(false)
const sampleData:any = ref([])
onMounted(() => {
  if (route.query.type === 'detail' || route.query.type === 'update') {
    getDetail()
  }
})

function getDetail() {
  tAmRetentionSampleMobileDetail(route.query.sampleId).then(response => {
    form.id = response.data.id
    form.sampleDate = response.data.sampleDate
    form.sampleHour = response.data.sampleHour
    form.sampleMeal = response.data.sampleMeal
    form.fileList = response.data.fileList
    form.fileListSub = response.data.fileList
    sampleData.value = response.data.detailList
    form.detailList = response.data.detailList
    form.sampleMealText = sample_meal.value.find(item => item.value === response.data.sampleMeal).label
  })
}


function onClickSubmit():void {
  console.log(form)
  // return
  formRef.value?.validate().then(() => {
    insertRetentionSampleAndDetail(form).then(res => {
      showSuccessToast(res.msg)
      setTimeout(() => {
        router.back()
      }, 1000)
    })
  }).catch(e => {
    console.log(e)
  })

}
const onConfirm = ({ selectedOptions }) => {
  form.sampleMeal = selectedOptions[0]?.value
  form.sampleMealText = selectedOptions[0]?.label
  showPicker.value = false


  sampleData.value = []
  listAllSpecifics({ 'menuTime': form.sampleDate }).then(response => {
    response.data.forEach(item => {
      item.sampleGrammage = 100
      if (form.sampleMeal === '1') {
        item.sampleName = item.menuBreakfast
      } else if (form.sampleMeal === '2') {
        item.sampleName = item.menuLunch
      } else {
        item.sampleName = item.menuDinner
      }
    })
    sampleData.value = response.data
    form.detailList = response.data
  })
}
const uploadFileUrl = ref('/file/upload') // 上传文件服务器地址
const headers = ref({
  Authorization: 'Bearer ' + getToken(),
  'from-source': 'platformUi',
  'Content-Type': 'mulipart/form-data'
})
function afterReadFiles(val) {
  // console.log(val)
  val.status = 'uploading'
  let file = val.file
  const formData = new FormData()
  formData.append('file', file)
  request({
    url: '/file/upload',
    data: formData,
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then((res) => { // 成功状态
    console.log('res', res)
    val.status = 'done'
    let data = res.data
    // let newFile =
    form.fileList.push({
      name: data.name,
      url: data.url,
      objectKey: data.objectKey,
      fileSize: file.size,
      fileType: file.type,
      status: 'done',
      message: '上传完成'
    })
    console.log(1)

    console.log(2)

  }).catch(() => { // 失败状态


  })
}
function deleteImg(file, detail) {
  form.fileList.splice(detail.index, 1)
}
function choosesampleMeal() {
  if (route.query.type === 'detail') return
  showPicker.value = true
}

</script>

<template>
  <div class="container full float-bottom">
    <div class="container__body">
      <div class="container__card flex">

        <van-form
          ref="formRef"
          label-align="top">
          <van-cell-group>
            <van-field
              v-model="form.sampleDate"
              readonly
              name="sampleDate"
              label="留样日期"
              placeholder="点击选择城市"
            />
            <van-field
              v-model="form.sampleHour"
              readonly
              name="sampleHour"
              label="有效时间"
            />
            <van-field
              v-model="form.sampleMealText"
              is-link
              readonly
              required
              name="sampleMeal"
              label="留样餐时"
              placeholder="请选择"
              :rules="[{ required:true, message: '请选择留样餐时' }]"
              @click="choosesampleMeal"
            />
            <van-popup v-model:show="showPicker" position="bottom">
              <van-picker
                :columns-field-names="{ text: 'label', value: 'value'}"
                :columns="sample_meal"
                @confirm="onConfirm"
                @cancel="showPicker = false"
              />
            </van-popup>
            <van-cell-group style="margin-top: 3rem;">

              <van-cell :title="'餐谱信息'"/>
            </van-cell-group>
            <div class="canpu-container">
              <div v-for="(item,index) in sampleData" :key="index" class="sample-data">
                <div class="lable-value">
                  <div class="label">餐别：</div>
                  <div class="value">{{ selectDictLabel(menu_type,item.menuType) }}</div>
                </div>
                <div class="lable-value">
                  <div class="label">菜品名称：</div>
                  <div class="value">{{ item.sampleName }}</div>
                </div>
                <div class="lable-value">
                  <div class="label">克数：</div>
                  <div class="value">{{item.sampleGrammage}}</div>
                </div>
              </div>
            </div>
            <van-field
              name="uploader"
              label="上传餐样"
              required
              :rules="[{ required:true, message: '请上传餐样' }]">
              <template #input>
                <van-uploader
                  :disabled="route.query.type === 'detail'"
                  v-model="form.fileListSub"
                  :after-read="afterReadFiles"
                  @delete="(file, detail) => deleteImg(file, detail)"
                />
              </template>
            </van-field>
          </van-cell-group>
        </van-form>


      </div>
    </div>
    <van-button
      v-if="route.query.type === 'add' || route.query.type === 'update'"
      class="button-submit float-bottom"
      type="primary"
      :loading="loading"
      @click="onClickSubmit">{{ route.query.type === 'add' ? '提交' : '修改' }}</van-button>
  </div>
</template>

<style lang="less" scoped>
.canpu-container {
  padding: 0.9rem;
  .sample-data {
    margin-top: 1.2rem;
    padding: 0.9rem;
    background-color: #fff;
    overflow: hidden;
    border-radius: 24rpx;
    box-shadow: 0 4rpx 40rpx  rgba(64, 103, 251, 0.14);
    .lable-value {
      display: flex;
      align-items: flex-start;
      margin-top: 0.5rem;
      .label {
        width: 8rem;
        font-size: 1.2rem;
        color: #333;
      }
      .value{
        font-size: 1.2rem;
        color: #333;
      }
    }
  }
}

</style>
