<template>
  <div class="mod-prod-info">
    <!-- 使用el-form构建一个表单，并设置引用 -->
    <el-form ref="dataFormRef" :model="dataForm" label-width="100px">
      <!-- 产品图片上传 -->
      <el-form-item label="产品图片">
        <mul-pic-upload v-model="dataForm.imgs" />
      </el-form-item>

      <!-- 产品上架/下架状态选择 -->
      <el-form-item label="状态">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 产品分类选择 -->
      <el-form-item label="产品分类" prop="categoryId" :rules="[...rules]">
        <el-col :span="8">
          <el-cascader
            v-model="category.selected"
            expand-trigger="hover"
            :options="category.list"
            :props="category.props"
            change-on-select
            @change="handleCategoryChange"
          />
        </el-col>
      </el-form-item>

      <!-- 产品分组多选 -->
      <el-form-item label="产品分组" prop="tagList" :rules="[...rules]">
        <el-col :span="8">
          <el-select v-model="dataForm.tagList" multiple style="width: 250px" placeholder="请选择">
            <el-option v-for="item in tags" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-col>
      </el-form-item>

      <!-- 产品名称输入框 -->
      <el-form-item label="产品名称" prop="prodName" :rules="[...rules]">
        <el-col :span="8">
          <el-input v-model="dataForm.prodName" placeholder="产品名称" maxlength="50" />
        </el-col>
      </el-form-item>

      <!-- 产品卖点文本域 -->
      <el-form-item label="产品卖点" prop="brief" :rules="[...rules]">
        <el-col :span="8">
          <el-input v-model="dataForm.brief" type="textarea" :autosize="{minRows: 2, maxRows: 4}" placeholder="产品卖点" />
        </el-col>
      </el-form-item>

      <!-- 配送方式选择 -->
      <el-form-item label="配送方式">
        <el-checkbox v-model="dataForm.deliveryMode.hasShopDelivery">商家配送</el-checkbox>
        <el-checkbox v-model="dataForm.deliveryMode.hasUserPickUp">用户自提</el-checkbox>
      </el-form-item>

      <!-- 商家配送模板选择，仅当选择了商家配送时显示 -->
      <prod-transport v-show="dataForm.deliveryMode.hasShopDelivery" v-model="dataForm.deliveryTemplateId" />

      <!-- SKU标签组件，用于管理商品规格 -->
      <sku-tag ref="skuTagRef" :sku-list="dataForm.skuList" @change="skuTagChangeSkuHandler" />

      <!-- SKU表格组件，展示SKU详细信息 -->
      <sku-table ref="skuTableRef" v-model="dataForm.skuList" :prod-name="dataForm.prodName" />

      <!-- 产品详情富文本编辑器 -->
      <el-form-item label="产品详情" prop="content">
        <tiny-mce ref="contentRef" v-model="dataForm.content" style="width:1000px" />
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="onSubmit()">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { treeDataTranslate, idList } from '@/utils'
import ProdTransport from './components/prod-transport.vue'
import SkuTag from './components/sku-tag.vue'
import SkuTable from './components/sku-table.vue'
import { Debounce } from '@/utils/debounce'

// 定义事件发射器
const emit = defineEmits(['refreshDataList'])

// 分类树展示与回显数据
const category = reactive({
  list: [], // 分类列表
  selected: [], // 当前选择的分类
  props: {
    value: 'categoryId',
    label: 'categoryName'
  }
})

// 表单模型数据
const dataForm = ref({
  prodName: '',
  brief: '',
  pic: '',
  imgs: '',
  categoryId: 0,
  prodId: 0,
  skuList: [],
  tagList: [],
  content: '',
  status: 1,
  deliveryMode: {
    hasShopDelivery: false,
    hasUserPickUp: false
  },
  deliveryTemplateId: null
})

// 分组标签数据
const tags = ref([])

// 获取路由参数中的产品ID
onMounted(() => {
  dataForm.value.prodId = useRoute().query.prodId
  getDataList()
})

// 引用子组件实例
const skuTableRef = ref(null)
const skuTagRef = ref(null)

/**
 * 获取所有必要的数据列表
 */
const getDataList = () => {
  getTagList()
  getCategoryList().then(() => {
    if (dataForm.value.prodId) {
      // 如果存在产品ID，则获取具体产品信息并填充表单
      http({
        url: http.adornUrl(`/prod/prod/info/${dataForm.value.prodId}`),
        method: 'get',
        params: http.adornParams()
      })
        .then(({ data }) => {
          dataForm.value = data
          dataForm.value.deliveryMode = JSON.parse(data.deliveryMode)
          skuTagRef.value?.init(data.skuList)
          skuTableRef.value?.init()
          category.selected = idList(category.list, dataForm.value.categoryId, 'categoryId', 'children').reverse()
          dataForm.value.tagList = data.tagList
        })
    } else {
      nextTick(() => {
        // 初始化表单，清除所有字段
        dataFormRef.value?.resetFields()
        skuTagRef.value?.init()
        dataForm.value.pic = ''
        dataForm.value.imgs = ''
      })
    }
  })
}

/**
 * 获取分类信息并转换为树形结构
 */
const getCategoryList = () => {
  return http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    category.list = treeDataTranslate(data, 'categoryId', 'parentId')
  })
}

/**
 * 处理分类改变事件，更新分类ID
 */
const handleCategoryChange = (val) => {
  dataForm.value.categoryId = val[val.length - 1]
}

// 获取路由实例
const router = useRouter()

// 表单引用
const dataFormRef = ref(null)

/**
 * 提交表单，添加或更新产品信息
 */
const onSubmit = Debounce(() => {
  dataFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    // 校验表单完整性
    if (!dataForm.value.imgs || !dataForm.value.deliveryMode ||
      (dataForm.value.deliveryMode.hasShopDelivery && !dataForm.value.deliveryTemplateId)) {
      errorMsg('请检查表单内容')
      return
    }

    const param = Object.assign({}, dataForm.value)
    // 设置价格和库存
    paramSetPriceAndStocks(param)

    param.deliveryMode = undefined
    param.deliveryModeVo = dataForm.value.deliveryMode
    // 商品主图
    param.pic = dataForm.value.imgs.split(',')[0]

    // 发送HTTP请求保存或更新产品信息
    http({
      url: http.adornUrl('/prod/prod'),
      method: param.prodId ? 'put' : 'post',
      data: http.adornData(param)
    }).then(() => {
      ElMessage({
        message: '操作成功',
        type: 'success',
        duration: 1500,
        onClose: () => {
          // 成功后跳转到产品列表页，并刷新列表
          router.push({ path: '/prod/prodList' })
          emit('refreshDataList')
        }
      })
    })
  })
})

/**
 * 设置商品价格和库存总量
 */
const paramSetPriceAndStocks = (param) => {
  param.totalStocks = 0
  param.price = 0
  param.oriPrice = 0

  for (let i = 0; i < param.skuList.length; i++) {
    const element = param.skuList[i]
    if (element.status !== 1) continue

    if (param.price === 0) param.price = Number.parseFloat(element.price || 0)

    param.price = Math.min(param.price, element.price)
    if (param.price === element.price) param.oriPrice = Number.parseFloat(element.oriPrice || 0)

    param.totalStocks += Number.parseInt(element.stocks || 0)
  }

  if (param.skuList.length === 1) {
    param.skuList[0].prodName = dataForm.value.prodName
  }
}

/**
 * 处理SKU变化事件，更新SKU名称
 */
const skuTagChangeSkuHandler = (skuList) => {
  const prodName = dataForm.value.prodName
  skuList.forEach(sku => {
    if (sku.properties) {
      sku.skuName = ''
      const properties = sku.properties.split(';')
      for (const property of properties) {
        sku.skuName += property.split(':')[1] + ' '
      }
      sku.prodName = prodName + ' ' + sku.skuName.trim()
    }
  })
  dataForm.value.skuList = skuList
}

/**
 * 显示错误消息
 */
const errorMsg = (message) => {
  ElMessage({
    message,
    type: 'error',
    duration: 1500
  })
}

/**
 * 获取所有的分组信息
 */
const getTagList = () => {
  http({
    url: http.adornUrl('/prod/prodTag/listTagList'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    tags.value = data
  })
}
</script>
