<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量绑定标签"
    width="500px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form :model="form" label-width="100px">
      <el-form-item label="选中职位">
        <div class="selected-count">已选择 {{ selectedQuestions.length }} 个职位</div>
      </el-form-item>
      <el-form-item label="选择标签" required>
        <el-select
          v-model="form.tags"
          multiple
          filterable
          placeholder="请选择要绑定的标签"
          style="width: 100%"
        >
          <el-option
            v-for="item in tagOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="loading">确认绑定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { GetTagList } from './api';
import { useBatchUpdateTags } from '../crud';
import { successMessage, warningMessage } from '../../../../utils/message';
import { Session } from '/@/utils/storage';
const props = defineProps({
  crudExpose: {
    type: Object,
    required: true
  }
});

const { batchUpdateTags } = useBatchUpdateTags(props.crudExpose);

const dialogVisible = ref(false);
const loading = ref(false);
const selectedQuestions = ref<any[]>([]);
const tagOptions = ref<any[]>([]);

const form = reactive({
  tags: [] as number[]
});

// 获取标签列表
const fetchTags = async () => {
  try {
    const res = await GetTagList({ page: 1, limit: 50, tenant_id: Session.get('tenant_id') });
    console.log('res', res);
    if (res.code === 2000 && res.data && res.data.items) {
      tagOptions.value = res.data.items;
    }
  } catch (error) {
    console.error('获取标签数据失败', error);
  }
};

// 打开对话框
const open = (selection: any[]) => {
  selectedQuestions.value = selection;
  dialogVisible.value = true;
  form.tags = [];
};

// 确认绑定
const handleConfirm = async () => {
  if (form.tags.length === 0) {
    warningMessage('请至少选择一个标签');
    return;
  }

  loading.value = true;
  try {
    // 提取所有选中题目的ID
    const questionIds = selectedQuestions.value.map(item => item.id);
    await batchUpdateTags(questionIds, form.tags);
    dialogVisible.value = false;
  } finally {
    loading.value = false;
  }
};

// 对话框关闭后的处理
const handleClosed = () => {
  form.tags = [];
  selectedQuestions.value = [];
};

// 初始化时获取标签数据
onMounted(() => {
  fetchTags();
});

// 暴露方法给父组件
defineExpose({
  open
});
</script>

<style scoped>
.selected-count {
  font-size: 14px;
  color: #606266;
}
</style> 