<template>
  <Dialog title="优选集团内容编辑" v-model="dialogVisible" class="!w-60%">
    <el-form
      ref="formRef"
      :model="formData"
      label-width="170px"
      v-loading="formLoading"
    >
      <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="handleEditBrandData" type="primary">
          编 辑{{ formData.brandIntroduce && formData.brandIntroduce.length ? `（${formData.brandIntroduce.length}）` : '' }}
        </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" class="!w-80%">
    <div class="flex items-center justify-between">
      <div class="color-orange-400">温馨提示：品牌图片规格为宽368px*高192px</div>
      <el-button type="primary" @click="handleAdd"><Icon icon="ep:plus" class="mr-5px" />新 增</el-button>
    </div>
    <el-table :data="brandData" ref="brandTableRef" :stripe="true" height="60vh">
      <el-table-column label="品牌名称" align="center" prop="content">
        <template #default="scope">
          <el-input type="textarea" :rows="1" 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="3" 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>
import { WebContentApi } from '@/api/menduner/system/web'
import { cloneDeep } from 'lodash-es'

/** 页面内容 表单 */
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, id) => {
	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 brandTableRef = ref(null)
const brandData = ref([])
const handleAdd = () => {
  brandData.value.push({ content: '', url: '', desc: '' })

  nextTick(() => {
    const wrapper = brandTableRef.value?.$el?.querySelector('.el-table__body-wrapper')
    if (wrapper) {
      const rows = wrapper.querySelectorAll('.el-table__row')
      
      if (rows.length) {
        const lastRow = rows[rows.length - 1]
        brandTableRef.value.setScrollTop(lastRow.offsetTop + lastRow.offsetHeight - wrapper.offsetHeight)
      }
    }
  })
}

// 品牌编辑
const handleEditBrandData = () => {
  brandData.value = formData.value.brandIntroduce && formData.value.brandIntroduce.length ? cloneDeep(formData.value.brandIntroduce) : []
  showBrandDialog.value = true
}

// 删除品牌项
const handleDeleteBrand = (index) => {
  if (!brandData.value[index]) return
  brandData.value.splice(index, 1)
}

const handleBrandSubmit = () => {
  if (brandData.value && brandData.value.length) {
    const checkValue = brandData.value.every(item => item.content.trim() && item.url && item.desc.trim())
    if (!checkValue) return message.warning('请将列表中的项填写完整')
  }
  formData.value.brandIntroduce = brandData.value || []
  showBrandDialog.value = false
}

/** 提交表单 */
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>