<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="3" label="录用" />
          <el-option :value="4" label="拒绝" />
          <el-option :value="5" 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, candidateToTalentPool } from '../api';
import { Session } from '/@/utils/storage';

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: Session.get('tenant_id')
      };
      
      const res = await updateBatchStatus(data);
      
      if (res.code === 2000) {
        // 如果是拒绝并加入人才库，则调用加入人才库接口
        if (form.new_status === 5 || form.new_status === 3) {
          const talentPoolPromises = form.application_ids.map(id => 
            candidateToTalentPool({
              job_application_id: id,
              to_external_pool: form.new_status === 5 ? true : false,
              recommendation_reason: "该候选人技术栈与未来项目匹配，虽然本次面试未通过，但有很大潜力，建议加入人才库持续跟进。",
              source: 1 // 1:面试拒绝后加入
            })
          );
          
          try {
            await Promise.all(talentPoolPromises);
            ElMessage.success('已成功将候选人加入人才库');
          } catch (error) {
            console.error('加入人才库失败:', error);
            ElMessage.warning('状态更新成功，但加入人才库失败');
          }
        } else {
          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> 