<template>
  <div class="totalBox">
    <div class="fromBox">
      <!-- 表单 ref 和 prop绑定  用于重置表单 -->
      <el-form ref="resetFormData" :model="form" label-width="auto" style="width: 750px;" size="large">
        <div class="totalPicture">
          <div class="boxPicture1">
            <el-form-item label="添加课程展示图片">
              <!-- 下面的event的作用,传入当前事件对象 -->
              <el-upload ref="uploadProductImg" action="#" list-type="picture-card" :auto-upload="false" multiple="true"
                :on-remove="handleRemove" @change="(event: any) => handleChange(event, 0)"
                :on-exceed="Exceed_ProductImg" limit="1">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </div>
          <!--  添加图文描述-->
          <div class="boxPicture2">
            <el-form-item label="添加课程展示图">
              <el-upload ref="uploadProductDetail" action="#" list-type="picture-card" :auto-upload="false"
                multiple="true" :on-change="(event: any) => handleChange(event, 1)" :on-exceed="Exceed_ProductDetail"
                limit="1" :on-remove="handleRemove">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </div>
        </div>
        <div class="NamePrice">
          <div class="name">
            <el-form-item label="体验课名称" prop="name">
              <el-input v-model="form.name" />
            </el-form-item>
          </div>
          <div class="price">
            <el-form-item label="体验课价格" prop="price">
              <el-input v-model="form.price" style="width: 90px;" />
            </el-form-item>
          </div>
        </div>
        <el-form-item label="课程简介" prop="intro">
          <el-input v-model="form.intro" type="textarea" style="width: 600px;" />
        </el-form-item>
        <!-- 使用弹窗 -->
        <el-form-item label="产品类别" prop="type">
          <el-select v-model="selectValue" disabled style="width: 110px;" />
        </el-form-item>
        <el-form-item label="商品标签" prop="label">
          <el-input v-model="form.label" type="textarea" placeholder="使用英文;分隔符分开" style="width: 600px;" />
        </el-form-item>
        <el-form-item label="商品详细描述" prop="introDetail">
          <el-input v-model="form.introDetail" type="textarea" placeholder="产品尺寸，服务等" style="width: 600px;" />
        </el-form-item>
        <div class="totalButton">
          <el-form-item>
            <el-button type="primary" @click="onSubmit">上架</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="resetForm">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="timeTable">
      <appointTime></appointTime>
    </div>
  </div>
  
</template>

<script setup lang="ts">
import { ref, onMounted, inject } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, type UploadFile, type UploadProps, genFileId, type UploadRawFile } from 'element-plus';
import myAxios from "@/api/myAxios";
import appointTime from '@/layout/components/appointTime.vue';
const fileSimple = ref() //单个文件
const uploadedFiles = ref<UploadFile[]>([]);//商品图片数组
const uploadedDescription = ref<UploadFile[]>([]);//商品图文描述数组
const resetFormData = ref()
const selectValue = '服务类'
const dialogVisible = ref(false)
const count = ref(1)
const form = ref({
  name: '',
  price: '',  //商品价格
  intro: '',//产品简介
  type: '',//类别
  label: '',//商品标签
  introDetail: '',//详情描述
  goodImg: '',  //商品图片url
  detailImg: '',  //图文详情url
  timePeriod: '',
  people: 0,
  date: []
})
//导入组件刷新
const reload: any = inject("reload")
const uploadProductImg: any = ref()  //图片上传的ref绑定
const uploadProductDetail: any = ref()  //图片上传的ref绑定
// const startTime = ref('')
// const endTime = ref('')
// const timeList = ref(
//   {
//     days: [0,1,2,3],  //表示第几天，0是当日
//     slot: Array.from({ length:8 },()=>({
//       startTime: '',
//       endTime: ''
//     }))
//   }
// )
const timeList = ref([
  {
    slot: Array.from({ length: 8 }, () => ({
      startTime: '',
      endTime: ''
    }))
  }
])
//时间段数组对象
const arr = ref([
  {
    timeSlot: '',
    isAvailable: 1,
    numberRange: ''
  }
]);
const myDate = new Date();
onMounted(() => {
  console.log(myDate.getHours());   //打印当前小时数
})
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
//提交表单
const onSubmit = async () => {
  const values = Object.values(form.value);
  // 使用some()方法来检查是否有任何值为空
  if (values.some(value => value === null || value === undefined || value === '')) {
    ElMessage({
      type: 'warning',
      message: '请检查表单数据是否完整填写'
    })
    return;  //空返回结束函数
  }
  const res = await myAxios.post('/goods/add', { ...form.value })
  if (res.data.code === 1) {
    ElMessage({
      type: 'success',
      message: "提交成功"
    })
    reload() //上传完后重置表单
  } else {
    ElMessage.error("服务错误")
    return;
  }
}
//图片上传请求  此请求只要选择了图片，就会默认上传
const handleChange = async (file: any, flag: number) => {
  fileSimple.value = file
  let formData = new FormData()  //这一步很重要 创建一个FormData对象
  formData.append("file", fileSimple.value.raw)  //fileSimple.value.raw 才是文件主体  将其以文件的格式插入formData
  const res = await myAxios({   //编写请求，与以前的请求不同，这一次要指定好头部类型和文件类型
    url: '/file/upload/server/not_login',
    method: 'post',
    headers: {
      'content-Type': 'multipart/form-data'
    },
    data: {
      biz: "test",
      // 取出formData对象中的file
      file: formData.get("file")
    }
  })
  if (res.data.code === 1) {
    //三元运算   当flag为0时，赋值给商品图片  flag为1时，赋值给详情图片
    flag ? form.value.detailImg = res.data.data : form.value.goodImg = res.data.data
  }
}
//清除表单
const resetForm = () => {
  resetFormData.value.resetFields()
}
const Exceed_ProductImg: UploadProps['onExceed'] = (files) => { //覆盖商品照片
  uploadProductImg.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadProductImg.value!.handleStart(file)
}
const Exceed_ProductDetail: UploadProps['onExceed'] = (files) => {  //覆盖商品详情图片
  uploadProductDetail.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadProductDetail.value!.handleStart(file)
}
const showDatePop = () => {
  dialogVisible.value = true
}
const handleClose = () => {
  dialogVisible.value = false;
}
const addList = (index: number, row: number) => {
  console.log(index, row);
  // if (count.value <= 6) {
  //   timeList.value[row+1] = {
  //     startTime: '',
  //     endTime: ''
  //   }
  // }
}
const subList = (index: number, row: number) => {
  // arr.value[index].splice(index, 1)
}
</script>

<style scoped>
.totalBox {
  display: flex;
}

.fromBox {
  border: 1px solid red;
  width: 750px;
  height: 750px;
}

.totalPicture {
  display: flex;
}

.NamePrice {
  display: flex;
}

.totalButton {
  display: flex;
  justify-content: space-evenly;
  /*  盒子里面水平分隔开 */
}

.date-picker {
  flex: 0.3;
  /* 日期选择区域占据左边 */
  display: inline-block;
  margin-bottom: 10px;
}

.father {
  display: flex;
  justify-content: space-around;
  align-items: center;
  border: 1px solid red;
}

.box {
  margin-bottom: 20px;
  /* 每个日期或时间段之间的间距 */
  border: 1px solid yellow;
}

.inner {
  margin-bottom: 10px;
  border: 1px solid orange;
}
</style>