<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量设置分类"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form :model="form" label-width="100px">
      <el-form-item label="选择分类">
        <el-select
          v-model="form.categoryId"
          placeholder="请选择分类"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { GetcategoryList } from '../api';
import { useBatchUpdateCategory } from '../crud';
import { ElMessage } from 'element-plus';
import { Session } from '/@/utils/storage';
const props = defineProps({
  crudExpose: {
    type: Object,
    required: true
  }
});

const dialogVisible = ref(false);
const loading = ref(false);
const selectedRows = ref([]);
const categoryOptions = ref([]);
const form = reactive({
  categoryId: null
});

const { batchUpdateCategory } = useBatchUpdateCategory(props.crudExpose);

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

// 打开对话框
const open = (selection) => {
  selectedRows.value = selection;
  form.categoryId = null;
  dialogVisible.value = true;
};

// 确认按钮
const handleConfirm = async () => {
  if (!form.categoryId) {
    ElMessage.warning('请选择分类');
    return;
  }
  
  loading.value = true;
  try {
    // 获取所有选中行的ID
    const questionIds = selectedRows.value.map(row => row.id);
    await batchUpdateCategory(questionIds, form.categoryId);
    dialogVisible.value = false;
    // 手动调用刷新方法
    props.crudExpose.doRefresh();
  } finally {
    loading.value = false;
  }
};

// 初始化时获取分类数据
onMounted(() => {
  fetchCategories();
});

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