<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      v-loading="formLoading"
    >
      <el-form-item label="上传图片尺寸" prop="imgSize" required>
        <el-input v-model="formData.imgSize" disabled />
      </el-form-item>
      <el-form-item label="图片" prop="url" required>
        <div style="width: 100%;">
          <UploadImg v-model="formData.url" :validSpecifications="true" height="150px" width="300px" :fileSize="10" :maxWidth="maxWidth" :maxHeight="maxHeight" />
        </div>
        <div style="display: flex; color: orange; align-items: center;"><Icon :size="20" icon="ep:warning" class="mr-3px" />提示：请严格按照图片规格上传</div>
      </el-form-item>
      <el-form-item label="展示现有企业详情">
        <el-switch v-model="showEnterprise" style="display: block;" />
        <div>点击图片跳转场景：1、跳转到平台现有企业详情页面（有定制集团页面的则会跳转到集团页面），2.跳转已关联的公众号链接或其它外部链接</div>
      </el-form-item>
      <el-form-item v-if="showEnterprise" label="平台现有企业" prop="link">
        <el-select-v2
          ref="selectRef"
          v-model="formData.link"
          :options="enterpriseList"
          placeholder="请输入企业名称进行查找"
          filterable
          :props="{ label: 'name', value: 'id' }"
        />
      </el-form-item>
      <el-form-item v-else label="跳转链接" prop="link" placeholder="请填写">
        <el-input v-model="formData.link" />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请填写" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请填写" />
      </el-form-item>
      <el-form-item label="状态" prop="status" required>
        <el-radio-group v-model="formData.status">
          <el-radio value="0">激活</el-radio>
          <el-radio value="1">禁用</el-radio>
        </el-radio-group>
      </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>
</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 formData = ref({
  imgSize: '',
  link: '',
  title: '',
  status: '0',
  sort: 0,
  url: ''
})
const maxWidth = ref(0)
const maxHeight = ref(0)

const imgSizeList = {
  'pcLeft': [869, 1512],
  'pcAdvertisement': [900, 530],
  'pcBackendAdvertisement': [900, 530],
  'pcHomeCarousel': [792, 392],
  'pcLoginCarousel': [792, 392],
  'appHomeCarousel': [750, 350],
  'appAdvertisement': [331, 442],
  'pcLoginBackground': [1920, 940],
  'pcTop': [1920, 80],
  'pcHomePreferred': [378, 173],
  // 'appHomeColumn': [72, 72]
}
const editId = ref('')
const formType = ref('')
const currentKey = ref('')
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const query = ref({
  id: undefined,
  pcTop: undefined,
  pcLeft: undefined,
  pcRight: undefined,
  pcAdvertisement: undefined,
  pcHomeCarousel: undefined,
  pcLoginCarousel: undefined,
  pcLoginBackground: undefined,
  pcBackendAdvertisement: undefined,
  appHomeCarousel: undefined,
  appAdvertisement: undefined,
  status: undefined
})
const showEnterprise = ref(true)

const formRules = reactive({
  url: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, key: string, title: string, mark?: string) => {
  formType.value = type
  resetForm()
  currentKey.value = key
  dialogVisible.value = true
  dialogTitle.value = title + (type === 'add' ? '新增' : '编辑')
  formLoading.value = true

  try {
    query.value = await WebContentApi.getWebContent(1)
    // 编辑
    if (mark) {
      editId.value = mark
      const { img: url, link, title, status, sort } = query.value[key].find(e => e.mark === mark)
      formData.value = { url, link, title, status, sort }
    }
  } finally {
    formLoading.value = false
  }

  formData.value.imgSize = `宽${imgSizeList[key][0]}px*高${imgSizeList[key][1]}px`
  maxWidth.value = imgSizeList[key][0]
  maxHeight.value = imgSizeList[key][1]
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  
  const mark = new Date().getTime().toString()
  const obj = { img: formData.value.url, link: formData.value.link, mark, title: formData.value.title, status: formData.value.status, sort: formData.value.sort }
  if (formType.value === 'add') {
    query.value[currentKey.value] = query.value[currentKey.value] ? [...query.value[currentKey.value], obj] : [obj]
  } else {
    const index = query.value[currentKey.value].findIndex(e => e.mark === editId.value)
    if (index === -1) return
    query.value[currentKey.value][index] = obj
  }
  
  // // 提交请求
  formLoading.value = true
  try {
    await WebContentApi.updateWebContent(query.value)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  editId.value = ''
  query.value = {
    id: undefined,
    pcTop: undefined,
    pcLeft: undefined,
    pcRight: undefined,
    pcAdvertisement: undefined,
    pcHomeCarousel: undefined,
    pcLoginCarousel: undefined,
    pcLoginBackground: undefined,
    pcBackendAdvertisement: undefined,
    appHomeCarousel: undefined,
    appAdvertisement: undefined,
    status: undefined
  }
  formData.value = {
    imgSize: '',
    link: '',
    title: '',
    status: '0',
    url: '',
    sort: 0
  }
  formRef.value?.resetFields()
}
</script>