<template>
  <Dialog title="优选集团内容编辑" v-model="dialogVisible" style="width: 60%;">
    <el-form
      ref="formRef"
      :model="formData"
      label-width="170px"
      v-loading="formLoading"
    >
			<!-- <el-form-item label="企业ID" prop="enterpriseId" :rules="[{ required: true, message: '请输入企业ID', trigger: 'blur'}]">
        <el-input v-model="formData.enterpriseId" />
      </el-form-item>
      <el-form-item label="企业名称" prop="title" :rules="[{ required: true, message: '请输入企业名称', trigger: 'blur'}]">
        <el-input v-model="formData.title" />
      </el-form-item> -->
      <el-form-item label="企业名称" prop="enterpriseId" :rules="[{ required: true, message: '请选择企业', trigger: 'blur'}]">
        <el-select-v2
          ref="selectRef"
          v-model="formData.enterpriseId"
          :options="enterpriseList"
          placeholder="请输入企业名称进行查找"
          filterable
          :props="{ label: 'name', value: 'id' }"
          @blur="handleChange"
        />
      </el-form-item>
      <el-form-item label="顶部轮播图左上角LOGO" prop="logo">
        <UploadImg v-model="formData.logo" height="150px" width="150px" />
      </el-form-item>
      <el-form-item label="顶部轮播图" prop="carousel" :rules="[{ required: true, message: '请上传企业轮播图', trigger: 'change'}]">
        <UploadImgs v-model="formData.carousel" :limit="20" />
      </el-form-item>
			<el-form-item label="简介标题" prop="introduce.title" :rules="[{ required: true, message: '请输入简介标题', trigger: 'blur'}]">
        <el-input v-model="formData.introduce.title" />
      </el-form-item>
			<el-form-item label="集团简介" prop="introduce.describe" :rules="[{ required: true, message: '请输入简介内容', trigger: 'blur'}]">
        <Editor v-model:modelValue="formData.introduce.describe" />
      </el-form-item>
			<el-form-item label="简介小图" prop="introduce.thumbnail">
        <UploadImgs v-model="formData.introduce.thumbnail" :limit="20" />
      </el-form-item>
			<el-form-item label="简介大图" prop="introduce.bigPicture.url">
        <UploadImg v-model="formData.introduce.bigPicture.url" height="150px" width="300px" />
      </el-form-item>
			<el-form-item label="简介大图高度" prop="introduce.bigPicture.height">
        <el-input v-model="formData.introduce.bigPicture.height" />
      </el-form-item>
      <el-form-item label="品牌介绍" prop="">
        <el-button @click="showBrandDialog = true" type="primary">编 辑</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <Dialog title="品牌介绍" v-model="showBrandDialog" style="width: 70%;">
    <div class="text-right">
      <el-button type="primary" @click="handleAdd"><Icon icon="ep:plus" class="mr-5px" />新 增</el-button>
    </div>
    <el-table :data="formData.brandIntroduce" :stripe="true">
      <el-table-column label="品牌名称" align="center" prop="content">
        <template #default="scope">
          <el-input type="textarea" :rows="2" v-model="scope.row.content" />
        </template>
      </el-table-column>
      <el-table-column label="品牌图片" align="center" prop="url" width="300">
        <template #default="scope">
          <UploadImg v-model="scope.row.url" height="150px" width="280px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌简介" align="center" prop="desc">
        <template #default="scope">
          <el-input type="textarea" :rows="6" v-model="scope.row.desc" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="60">
        <template #default="scope">
          <el-button link type="danger" @click="handleDeleteBrand(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="handleBrandSubmit" type="primary">确 定</el-button>
      <el-button @click="showBrandDialog = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { WebContentApi } from '@/api/menduner/system/web'

/** 页面内容 表单 */
defineOptions({ name: 'WebContentForm' })
defineProps({ enterpriseList: Array })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const editId = ref()
const currentKey = ref('')
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
	enterpriseId: '',
	title: '',
  logo: '',
	carousel: [],
	brandIntroduce: [],
	introduce: {
		title: '集团简介',
    describe: '',
		thumbnail: [],
		bigPicture: {
			height: 115,
			url: ''
		}
	}
})

const showBrandDialog = ref(false)

const formRef = ref() // 表单 Ref
const selectRef = ref()

const handleChange = () => {
  formData.value.title = selectRef.value.currentPlaceholder
}

/** 打开弹窗 */
const result = ref({})
const open = async (key: string, id?: number) => {
	currentKey.value = key
  resetForm()
  dialogVisible.value = true
  formLoading.value = true

  try {
    const data = await WebContentApi.getWebContent(1)
		result.value = data
		
    // 编辑
    if (id && result.value[key] && Object.keys(result.value[key]).length > 0 && result.value[key][id]) {
			formData.value = result.value[key][id]
      editId.value = id
      formData.value.enterpriseId = id
    }
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 品牌介绍
const handleDeleteBrand = (index) => {
  if (!formData.value.brandIntroduce[index]) return
  delete formData.value.brandIntroduce[index]
}
const handleBrandSubmit = () => {
  const checkValue = formData.value.brandIntroduce.every(item => item.content.trim() && item.url && item.desc.trim())
  if (!checkValue) return message.warning('请将列表中的项填写完整')
  showBrandDialog.value = false
}

// 提交表单
const handleAdd = () => {
  formData.value.brandIntroduce.push({ content: '', url: '', desc: '' })
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
	
	result.value[currentKey.value][formData.value.enterpriseId] = formData.value
  if (editId.value !== formData.value.enterpriseId) delete result.value[currentKey.value][editId.value]
  else delete result.value[currentKey.value][formData.value.enterpriseId].enterpriseId

  // 提交请求
  formLoading.value = true
  try {
    await WebContentApi.updateWebContent(result.value)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
		enterpriseId: '',
		title: '',
    logo: '',
		carousel: [],
		brandIntroduce: [],
		introduce: {
			title: '集团简介',
			describe: '',
			thumbnail: [],
			bigPicture: {
				height: 0,
				url: ''
			}
		}
	}
  editId.value = ''
}
</script>