<template>
  <div class="flexCard">
    <el-card class="richTextPreview" shadow="never">
      <div class="titleText">移动端预览</div>
      <p v-html="previewRichText"></p>
    </el-card>
    <!-- 表单 ref 和 prop绑定  用于重置表单 -->
    <el-card class="form-container" shadow="never">
      <div class="form">
        <el-form ref="resetFormData" :model="detailFrom" label-width="auto" size="large" :rules="rules" :disabled="disabledRichText">
          <div>
            <el-form-item label="添加商品图片">
              <!-- 下面的event的作用,传入当前事件对象 -->
              <PreviewImgUpload :ImgUrlList="previewImgUrl" @update:goodImgArr="detailFrom.goodImg = $event"/>
            </el-form-item>
          </div>
          <div class="NamePrice">
            <el-form-item label="产品名称" prop="name">
              <el-input v-model="detailFrom.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="detailFrom.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="detailFrom.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="detailFrom.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-select v-model="detailFrom.festivalName" placeholder="请选择" >
                <el-option v-for="(item,index) in festivalArr" :key="index" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="产品类别" prop="type" style="width: 240px;">
              <el-select v-model="detailFrom.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" size="large" @click="addLabel">添加</el-button>
            <el-button type="danger" size="large" @click="deleteLabel" v-if="labelList.length > 1">删除</el-button>
          </el-form-item>
          <el-form-item label="商品图文" prop="richText" v-loading="loading">
            <richTextUtil @richTextContent="getInfo" v-model:disableRich="disabledRichText" v-model:context="previewRichText"/>
          </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>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, onBeforeMount  } from 'vue';
import {type FormRules, type UploadUserFile} 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 richTextUtil from '@/layout/components/richTextUtil.vue';
import { useRoute, useRouter} from "vue-router";
import PreviewImgUpload from '@/utils/imgUpload/PreviewImgUpload.vue'
const router = useRouter()

const route = useRoute();  //路由
const resetFormData = ref()
const typeList: any = ref([])
const labelList = ref([''])
const isqualify : any = ref(false)
const typeSelect : any = ref(false)  //类别下拉选项栏的禁用状态
const detailFrom : any = ref({
  name: '',   //商品名称
  price: '',  //商品价格
  intro: '',//产品简介
  festivalName: '', //节日名称
  type: '',//类别
  label: '',//商品标签
  goodImg: '',  //商品图片url
  inventory: '', //库存
  richText: ''
})
const disabledRichText:any = ref(false);
const previewRichText:any = ref('');
const festivalArr : any = ref([])   //节日数组
const previewImgUrl  = ref('')  //预览图字符串
const loading = ref(true)



onBeforeMount(()=>{   //页面加载最早的生命周期
  getProductInfo()   //编辑页查询商品信息
  if(route.params.flag === '0'){
    disabledRichText.value = true;
  }
})
onMounted(() => {
  getTypeList() //加载类别列表，渲染在产品列表的select选项里面
  getFestivalArr()
  setTimeout(()=>{   //定时器
    loading.value = false
  },1500)
})

//节日信息
const getFestivalArr = async () => {
  let tempFestivalArr : any = []   //临时数组，存放每一次获取的节日名称，用于判断
  const res = await myAxios.get('/festival/get')
  // console.log('节日信息--->',res.data.data)
  if(res.data.code === 1) {
    festivalArr.value = res.data.data
    festivalArr.value.forEach((item : any) => {
      tempFestivalArr.push(item.name)
    })
  } else {
    WarnInfo('获取节日失败，检查服务')
  }
  if(!tempFestivalArr.includes(detailFrom.value.festivalName)) {
    detailFrom.value.festivalName = '无'
  }
}

const getProductInfo = async () => {   //商品信息
  const res = await myAxios.post('/goods/getById',{ id: route.params.id })
  console.log('后端查询商品--->',res.data)
  if(res.data.code === 1) {
    previewImgUrl.value = res.data.data.goodImg
    detailFrom.value = res.data.data
    previewRichText.value = res.data.data.richText
    detailFrom.value.festivalName = res.data.data.festivalName.split(';')[0]
    labelList.value = res.data.data.label.split(';')
  }
}

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)
  }
}

//提交表单
const onSubmit = async () => {
  // console.log('提交前的表格',detailFrom.value)
  const values = Object.values(detailFrom.value );
  // 使用some()方法来检查是否有任何值为空
  if (values.some((value: any) => value === null || value === undefined || value === '' || value === 'PHA+PGJyPjwvcD4=')) {
    WarnInfo('请检查表单数据是否完整填写')
    return;  //空返回结束函数
  }
  const res = await myAxios.post('/goods/update', { ...detailFrom.value })
  // console.log(res.data);
  if (res.data.code === 1) {
    SuccessInfo('提交成功')
    await router.replace('/MerchandiseCenter')
  } else {
    WarnInfo('服务错误')
    return;
  }
}
//将 商品类别 赋值到表格里
const loadForm = (value: any) => {
  detailFrom.value.type = value  //三元运算符 flag=1 是关于"商品类别"选项的值  flag=0 是关于“是否为节日限定”选项的值
}
//清除表单
const resetForm = () => {
  resetFormData.value.resetFields()
}
const rules = reactive<FormRules<typeof detailFrom>>({  //表单校验规则
  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 deleteLabel = () => {   //删除标签的方法
  labelList.value.pop()
  addLabelList()   //格式化商品标签
}
const addLabelList = () => {   //格式化商品标签
  var string = ''
  if (!labelList.value.some((item: any) => item === '')) {
    string = labelList.value.join(';')
  } else return;
  detailFrom.value.label = string
}

const customTag = (e:any)=>{   //点击定制
  if(e) {
    detailFrom.value.inventory = 1
    invInput.value = true
    typeSelect.value = true
    detailFrom.value.type = '定制'
  } else {
    detailFrom.value.inventory = 0
    invInput.value = false
    typeSelect.value = false
    detailFrom.value.type = ''
  }
}

const getInfo = (info: any) => {  //富文本赋值
  // console.log('info', info)
  previewRichText.value = info
  detailFrom.value.richText = encode64(info)
}

//字符串转为base64编码
function encode64(text: string): string {
  return btoa(String.fromCharCode(...new TextEncoder().encode(text)))
}

</script>

<style scoped>
.flexCard {
  display: flex;
  height: 100%;
  min-width: 800px;
}

.richTextPreview {
  height: 80vh;
  overflow-y: auto;
  word-break: break-all;
  width: 400px;
  margin-right: 10px;
}

.form-container {
  width: 900px;
  height: 800px;
  overflow: auto;
  /* margin: 0 auto; */
}
.form {
  /* width: 500px; */
  margin: 0 auto;
}

.NamePrice {
  display: flex;
}

.IntroInven {
  display: flex;
}

.festivalBox {
  display: flex;
}

.btnBox {
  display: flex;
  justify-content: space-around;
}

.titleText {
  text-align: center;
  margin: 0 auto;
}
</style>