<template>
  <el-dialog width="600px" append-to-body :title="title" v-model="open">
    <el-form label-width="100px" ref="formRef" :model="form" :rules="rules">
      <el-form-item label="当前资产">
        <el-input
          placeholder="自动带入"
          :disabled="true"
          v-model="currentRow.dataAstCnName"
        />
      </el-form-item>
      <el-form-item label="收藏目录" prop="contentOnum">
        <el-select
          placeholder="请选择收藏目录"
          :disabled="disabled"
          v-model="form.contentOnum"
        >
          <el-option
            v-for="item in bookmarkFolder"
            :key="item.content_onum"
            :label="item.content_name"
            :value="item.content_onum"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" :disabled="disabled" @click="submitForm"
          >确定</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import useUserStore from '@/store/modules/user'
import { computed, nextTick } from 'vue'
import {
  getBookmarkFolder,
  addDirectoryCollection,
} from '@/api/dataAsset/directory'

const userStore = useUserStore()
const title = ref('')
const open = ref(false)
const disabled = ref(false)
const { proxy } = getCurrentInstance()
const form = ref({})
const rules = ref({
  contentOnum: [
    { required: true, message: '收藏目录不能为空', trigger: 'blur' },
  ],
})

const bookmarkFolder = ref([])
const setBookmarkFolder = () => {
  getBookmarkFolder().then(({ data }) => {
    bookmarkFolder.value = data
  })
}

const formRef = ref(null)
const currentRow = ref({})
const openDialog = (row) => {
  open.value = true
  form.value = {
    dataAstNo: undefined,
    userId: undefined,
    contentOnum: undefined,
  }
  setBookmarkFolder()
  if (row.dataAstNo) {
    currentRow.value = row
    form.value = {
      ...form.value,
      dataAstNo: String(row.dataAstNo),
      userId: String(userStore.id),
    }
  }
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

const emit = defineEmits(['onSuccess'])
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      addDirectoryCollection(form.value).then((response) => {
        proxy.$modal.msgSuccess('收藏成功')
        open.value = false
        emit('onSuccess')
      })
    }
  })
}

const cancel = () => {
  open.value = false
}

defineExpose({ title, disabled, openDialog })
</script>
