<template>
  <Dialog :title="title" v-model="show" width="800px">
    <el-form v-loading="formLoading" :model="form" ref="formRef" :rules="rules" label-width="60px">
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="标签" prop="tags">
            <el-select
              v-model="form.tags"
              multiple
              filterable
              collapse-tags
              collapse-tags-tooltip
              allow-create
              default-first-option
              :reserve-keyword="false"
              placeholder="请选择标签或输入"
              clearable
              @change="tipChange"
              style="width: 100%"
            >
              <el-option
                v-for="item in tipOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24" :offset="0">
          <el-form-item label="内容" prop="content">
            <UploadFile v-if="libType == 1" v-model="form.files" :limit="1" :isShowTip="false" />
            <UploadImg
              v-else-if="libType == 2"
              v-model:modelValue="form.files"
              width="100px"
              height="100px"
            />
            <Editor v-else v-model:modelValue="form.content" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24" :offset="0">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" :disabled="formLoading" @click="handleSave">保 存</el-button>
      </span>
    </template>
  </Dialog>
</template>

<script setup name="DialogResource">
import * as ResourceApi from '@/api/system/library/resource'
import { getDictOptions } from '@/utils/dict'
import * as dictApi from '@/api/system/dict/dict.data'

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

const show = ref(false)
const title = ref('')
const formType = ref('create')
const libType = ref(1)

const form = ref({})
const formLoading = ref(false)
const rules = ref({
  title: { required: true, message: '标题不可为空', trigger: 'blur' }
})

const tipOptions = ref([])

function getOptions() {
  tipOptions.value = getDictOptions('knowledge_tags')
}

async function open(type, info, id) {
  show.value = true
  title.value = type == 'update' ? '修改资源' : '新增资源'
  formType.value = type
  libType.value = info.libType
  resetForm(info.libId)
  getOptions()
  if (id) {
    formLoading.value = true
    try {
      form.value = await ResourceApi.getResource(id)
    } finally {
      formLoading.value = false
    }
  }
}

function resetForm(libId) {
  form.value = {
    libId,
    title: '',
    tags: [],
    files: '',
    content: '',
    remark: null,
    isDefault: false
  }
}

async function tipChange(val) {
  const valStr = val.at(-1)
  if (!tipOptions.value.some((it) => it.value == valStr)) {
    await dictApi.createDictData({
      label: valStr,
      value: valStr,
      sort: 1,
      status: 0,
      dictType: 'knowledge_tags'
    })
    tipOptions.value.push({ label: valStr, value: valStr })
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const formRef = ref()

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
async function handleSave() {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await ResourceApi.createResource(form.value)
      message.success(t('common.createSuccess'))
    } else {
      await ResourceApi.updateResource(form.value)
      message.success(t('common.updateSuccess'))
    }
    show.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>

<style lang="scss" scoped></style>
