<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">已选择 {{ selectedPositions.length }} 个职位</div>
      </el-form-item>
      <el-form-item label="修改状态" required>
        <el-select
          v-model="form.status"
          placeholder="请选择状态"
          style="width: 100%"
        >
          <el-option label="未发布" :value="0" />
          <el-option label="已发布" :value="1" />
          <el-option label="已过期" :value="2" />
        </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 } from 'vue';
import { useBatchUpdateStatus } from '../crud';
import { warningMessage, successMessage } from '../../../../utils/message';
import { ElMessageBox, ElMessage } from 'element-plus';
import * as api from '../api';
import { Session } from '/@/utils/storage';
const props = defineProps({
  crudExpose: {
    type: Object,
    required: true
  }
});

const { batchUpdateStatus } = useBatchUpdateStatus(props.crudExpose);

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

const form = reactive({
  status: null as number | null
});

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

// 确认修改
const handleConfirm = async () => {
  if (form.status === null) {
    warningMessage('请选择要修改的状态');
    return;
  }

  loading.value = true;
  try {
    // 提取所有选中职位的ID
    const positionIds = selectedPositions.value.map(item => item.id);

    // 如果是要发布职位，需要先检查视频状态
    if (form.status === 1) { // 发布状态
      // 检查每个选中职位的视频状态
      for (const position of selectedPositions.value) {
        const response = await api.CheckQuestionVideosStatus({
          position_id: position.id,
          tenant_id: Session.get('tenant_id')
        });

        if (response.code === 2000) {
          const { is_all_completed, total_questions } = response.data;
          
          // 检查视频是否全部完成且存在题目
          if (!is_all_completed || total_questions <= 0) {
            const reason = total_questions <= 0 ? '当前职位没有设置面试题目' : '面试题目视频未全部生成完成';
            await ElMessageBox.alert(
              `无法发布职位 "${position.title}"，原因：\n${reason}`,
              '无法发布',
              {
                confirmButtonText: '确定',
                type: 'warning',
              }
            );
            loading.value = false;
            return;
          }
        } else {
          ElMessage.error('检查视频状态失败，请稍后重试');
          loading.value = false;
          return;
        }
      }

      // 所有职位检查通过后，调用批量发布API
      const publishResponse = await api.batch_publish({
        job_ids: positionIds,
        tenant_id: Session.get('tenant_id')
      });

      if (publishResponse.code === 2000) {
        successMessage('职位批量发布成功');
        dialogVisible.value = false;
        props.crudExpose.doRefresh();
      } else {
        ElMessage.error(publishResponse.msg || '发布失败');
      }
    } else {
      // 其他状态直接调用批量更新API
      await batchUpdateStatus(positionIds, form.status);
      dialogVisible.value = false;
      props.crudExpose.doRefresh();
    }
  } finally {
    loading.value = false;
  }
};

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

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

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