<template>
  <div>
    <!-- 表单 ref 和 prop绑定  用于重置表单 -->
    <el-form ref="resetFormData" :model="form" label-width="auto" style="width: 750px" size="large">
      <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>
      <!--  添加图文描述-->
      <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>
      <el-form-item label="产品名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="产品价格" prop="price">
        <el-input v-model="form.price" />
      </el-form-item>
      <el-form-item label="产品简介" prop="intro">
        <el-input v-model="form.intro" />
      </el-form-item>
      <el-form-item label="当前库存" prop="inventory">
        <el-input v-model="form.inventory" />
      </el-form-item>
      <el-form-item label="是否为限定类产品" prop="festivalOrder">
        <el-select v-model="form.festivalOrder" placeholder="请选择" @change="(event: any) => loadForm(event, 0)">
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item v-if="form.region=='ture' " label="节日名称">
        <el-input v-model="form.festivalName" />
      </el-form-item> -->
      <el-form-item label="产品类别" prop="type">
        <el-select v-model="typeList.value" placeholder="请选择" @change="(event: any) => loadForm(event, 1)">
          <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value1" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品标签" prop="label">
        <el-input v-model="form.label" type="textarea" placeholder="" />
      </el-form-item>
      <el-form-item label="商品详细描述" prop="introDetail">
        <el-input v-model="form.introDetail" type="textarea" placeholder="产品尺寸，服务等" />
      </el-form-item>
      <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>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
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";
const fileSimple = ref() //单个文件
const uploadedFiles = ref<UploadFile[]>([]);//商品图片数组
const uploadedDescription = ref<UploadFile[]>([]);//商品图文描述数组
const resetFormData = ref()
const form = ref({
  name: '',
  price: '',  //商品价格
  intro: '',//产品简介
  festivalOrder: '',//是否为限定
  type: '',//类别
  label: '',//商品标签
  introDetail: '',//详情描述
  goodImg: '',  //商品图片url
  detailImg: '',  //图文详情url
  inventory: '' //库存
})
//导入组件刷新
const reload : any = inject("reload")
const typeList: any = ref([
  {
    value1: '',
    label: ''
  }
])
const uploadProductImg : any = ref()  //图片上传的ref绑定
const uploadProductDetail : any = ref()  //图片上传的ref绑定
onMounted(() => {
  getTypeList() //加载类别列表，渲染在产品列表的select选项里面
})
const getTypeList = async () => {  //获取类别列表作为可选项
  const res = await myAxios.post('/category/list', {})  //获取商品列表
  for (let key in res.data.data) {    //循环赋值
    typeList.value[key] = {
      value1: res.data.data[key].typeName,
      label: res.data.data[key].typeName
    }
  }
}
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 loadForm = (value: any, flag: number) => {
  flag ? form.value.type = value : form.value.festivalOrder = value  //三元运算符 flag=1 是关于"商品类别"选项的值  flag=0 是关于“是否为节日限定”选项的值
}
//清除表单
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)
}
</script>