<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量修改申请状态"
    width="500px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form :model="form" label-width="100px" ref="formRef" :rules="rules">
      <el-form-item label="新状态" prop="new_status">
        <el-select v-model="form.new_status" placeholder="请选择新状态" style="width: 100%">
          <el-option :value="0" label="待面试" />
          <el-option :value="1" label="已通知面试" />
          <el-option :value="2" label="已面试" />
          <el-option :value="3" label="已录用" />
          <el-option :value="4" label="已拒绝" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="note">
        <el-input
          v-model="form.note"
          type="textarea"
          placeholder="请输入备注信息"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确认</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { updateBatchStatus } from '../api';

const dialogVisible = ref(false);
const loading = ref(false);
const formRef = ref<FormInstance>();

const form = reactive({
  new_status: undefined as number | undefined,
  note: '',
  application_ids: [] as number[]
});

const rules = {
  new_status: [{ required: true, message: '请选择新状态', trigger: 'change' }]
};

const emit = defineEmits(['success']);
const props = defineProps({
  crudExpose: {
    type: Object,
    required: true
  }
});

// 打开对话框
const open = (selection: any[]) => {
  dialogVisible.value = true;
  form.application_ids = selection.map(item => item.id);
  form.new_status = undefined;
  form.note = '';
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    
    loading.value = true;
    try {
      const data = {
        application_ids: form.application_ids,
        new_status: form.new_status as number,
        note: form.note,
        tenant_id: '1'
      };
      
      const res = await updateBatchStatus(data);
      
      if (res.code === 2000) {
        ElMessage.success('批量修改状态成功');
        dialogVisible.value = false;
        emit('success');
        props.crudExpose.doRefresh();
      } else {
        ElMessage.error(res.msg || '操作失败');
      }
    } catch (error) {
      console.error('批量修改状态失败:', error);
      ElMessage.error('操作失败，请重试');
    } finally {
      loading.value = false;
    }
  });
};

// 关闭对话框时重置表单
const handleClosed = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

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