<template>
  <div class="totalBox">
    <!-- 表单 ref 和 prop绑定  用于重置表单 -->
    <div class="fromBox">
      <el-form ref="resetFormData" :model="form" label-width="auto" size="large" :rules="rules">
        <div>
          <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, 2)" :on-exceed="Exceed_ProductImg"
              limit="7">
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </div>
        <!--  添加图文描述-->
        <div>
          <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 class="NamePrice">
          <el-form-item label="产品名称" prop="name">
            <el-input v-model="form.name" maxlength="12" minlength="2" show-word-limit style="width: 260px;" />
          </el-form-item>
          <el-form-item label="产品价格" prop="price">
            <el-input-number v-model="form.price" min="0" :precision="2" :step="0.5" />
            <p>元</p>
          </el-form-item>
        </div>
        <div class="IntroInven">
          <el-form-item label="产品简介" prop="intro">
            <el-input v-model="form.intro" type="textarea" placeholder="产品尺寸，服务等" maxlength="30" show-word-limit
              style="width: 300px;" />
          </el-form-item>
          <div>
            <el-form-item label="库存" prop="inventory">
              <el-input-number v-model="form.inventory" min="0" :precision="0" :step="1" :disabled="invInput" />
            </el-form-item>
          </div>
        </div>
        <div class="festivalBox">
          <el-form-item label="节日名称" prop="festivalName" style="width: 300px;">
            <el-input v-model="form.festivalName" />
          </el-form-item>
          <el-form-item label="产品类别" prop="type" style="width: 240px;">
            <el-select v-model="form.type" placeholder="请选择" @change="(event: any) => loadForm(event)" :disabled="typeSelect">
              <el-option v-for="item in typeList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <div>
            <el-checkbox v-model="isqualify" label="定制商品" size="large" border style="margin-left: 10px;" @change="customTag" />
          </div>
        </div>
        <el-form-item label="商品标签" prop="label">
          <div v-for="(item, index) in labelList" :key="index">
            <el-input v-model="labelList[index]" type="text" style="width: 150px;" maxlength="5" show-word-limit
              @blur="addLabelList" />
          </div>
          <el-button type="primary" @click="addLabel">添加</el-button>
        </el-form-item>
        <el-form-item label="商品详细描述" prop="introDetail">
          <el-input v-model="form.introDetail" type="textarea" placeholder="产品尺寸，服务等" maxlength="100" show-word-limit />
        </el-form-item>
        <div class="btnBox">
          <el-form-item>
            <el-button type="primary" @click="onSubmit" :disabled="saveBtn">保存</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="resetForm">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, inject, reactive } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { type UploadProps, genFileId, type UploadRawFile, type FormInstance, type FormRules } from 'element-plus';
import { SuccessInfo, WarnInfo, CommInfo } from '@/utils/messageInfo';   //封装ElMessage提示
import myAxios from "@/api/myAxios";
import { saveBtn, invInput } from '@/utils/entityProduct/globalVar';
import { validateName, validateIntro, validateDetail } from '@/utils/entityProduct/FormRules';
import { handleChange, handleRemove, form, Exceed_ProductImg } from '@/utils/entityProduct/picUpload';
const resetFormData = ref()
const reload: any = inject("reload")  //导入组件刷新
const typeList: any = ref([])
const uploadProductImg: any = ref()  //图片上传的ref绑定
const uploadProductDetail: any = ref()  //图片上传的ref绑定
const labelList = ref([''])
const isqualify : any = ref(false)
const typeSelect : any = ref(false)  //类别下拉选项栏的禁用状态
onMounted(() => {
  getTypeList() //加载类别列表，渲染在产品列表的select选项里面
})
const getTypeList = async () => {  //获取类别列表作为可选项
  const res = await myAxios.post('/category/list/web', {})  //获取商品列表
  for(let key in res.data.data) {
    typeList.value.push(res.data.data[key].typeName)
  }
  console.log('typeList---->',typeList.value);
}
//提交表单
const onSubmit = async () => {
  const values = Object.values(form.value );
  // 使用some()方法来检查是否有任何值为空
  if (values.some((value: any) => value === null || value === undefined || value === '' || value === 0)) {
    WarnInfo('请检查表单数据是否完整填写')
    return;  //空返回结束函数
  }
  const res = await myAxios.post('/goods/add', { ...form.value })
  // console.log(res.data);
  if (res.data.code === 1) {
    SuccessInfo('提交成功')
    form.value = {}  //12.18改
    reload() //上传完后重置表单
  } else {
    WarnInfo('服务错误')
    return;
  }
}
//将 商品类别 赋值到表格里
const loadForm = (value: any) => {
  form.value.type = value  //三元运算符 flag=1 是关于"商品类别"选项的值  flag=0 是关于“是否为节日限定”选项的值
}
//清除表单
const resetForm = () => {
  resetFormData.value.resetFields()
}
const Exceed_ProductDetail: UploadProps['onExceed'] = (files) => {  //覆盖商品详情图片
  uploadProductDetail.value!.clearFiles()   //清空已上传的文件列表
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadProductDetail.value!.handleStart(file)  //手动选择文件
}
const rules = reactive<FormRules<typeof form>>({  //表单校验规则
  name: [{ validator: validateName, trigger: 'blur' }],
  intro: [{ validator: validateIntro, trigger: 'blur' }],
  introDetail: [{ validator: validateDetail, trigger: 'blur' }]
})
const addLabel = () => {   //添加商品标签按钮的方法
  if (labelList.value[labelList.value.length - 1] === '') {
    WarnInfo('请填写完')
    return;
  }
  if (labelList.value.length < 4) {
    labelList.value.push('')
  }
}
const addLabelList = () => {   //格式化商品标签
  var string = ''
  if (!labelList.value.some((item: any) => item === '')) {
    string = labelList.value.join(';')
  } else return;
  form.value.label = string
}
const customTag = (e:any)=>{   //点击定制
  if(e) {
    form.value.inventory = 1
    invInput.value = true
    typeSelect.value = true
    form.value.type = '定制'
  } else {
    form.value.inventory = 0
    invInput.value = false
    typeSelect.value = false
    form.value.type = ''
  }
}
</script>

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

.fromBox {
  width: 700px;
  height: 750px;
  margin: 0 auto;
}

.NamePrice {
  display: flex;
}

.IntroInven {
  display: flex;
}

.festivalBox {
  display: flex;
}

.btnBox {
  display: flex;
  justify-content: space-around;
}
</style>