<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >

    <el-form-item label="试卷编号" prop="paperId">
        <el-input
          v-model="queryParams.paperId"
          placeholder="请输入试卷编号"
          clearable
          class="!w-240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="启用状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择启用状态"
          class="!w-240px"
          clearable
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SYS_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openAddForm"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openSet"
        >
          <Icon icon="ep:set-up" class="mr-5px" /> 抽卷调整
        </el-button>
         <el-button
          type="primary"
          plain
          @click="openDown"
        >
          <Icon icon="ep:files" class="mr-5px" /> 生成笔试试卷
        </el-button>
        <!-- 批量删除按钮 -->
        <!-- <el-button
          type="danger"
          :disabled="selectedRows.length === 0"
          @click="batchDelete"
        >
          批量删除
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表展示 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :row-key="row => row.id" ref="tableRef"  @selection-change="handleSelectionChange">

      <!-- 多选列 -->
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column label="试卷id" align="center" prop="paperId" /> -->
      <el-table-column label="试卷编号" align="center" prop="num" />
      <el-table-column label="使用次数" align="center" prop="counts" />
      <el-table-column label="抽卷方式" align="center" prop="rollUp">
        <template #default="scope">
          <span v-if="scope.row.rollUp === '0'">固定</span>
          <span v-else-if="scope.row.rollUp === '1'">AB卷</span>
          <span v-else-if="scope.row.rollUp === '2'">随机</span>
          <span v-else-if="scope.row.rollUp === '3'">自选</span>
        </template>
      </el-table-column>
      <el-table-column label="AB卷" align="center" prop="isAb">
        <template #default="scope">
          <span v-if="scope.row.isAb === '0'">A卷</span>
          <span v-else-if="scope.row.isAb === '1'">B卷</span>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="status" width="120">
    <template #default="scope">
      <el-switch
        v-model="scope.row.status"
        :active-value="'0'"
        :inactive-value="'1'"
        @change="handleStatusChange(scope.row)"
      />
    </template>
  </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openLook('look', scope.row.paperId)"
            v-hasPermi="['system:sms-channel:update']"
          >
            查看
          </el-button>
          <el-button
            link
            type="primary"
            @click="openEdit('update', scope.row)"
            v-hasPermi="['system:sms-channel:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.paperId)"
            v-hasPermi="['system:sms-channel:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 弹窗组件 -->
  <paper-add
    v-model="showAdd"
    :task-Id="props.taskId"
    :task-specialty="props.taskSpecialty"
    ref="taskAddRef"
    @done="reload"
  />
  <paper-edit
    v-model="showEdit"
    :data="current"
    ref="taskEditRef"
     @done="reload"
  />
  <paper-look
    v-model="showLook"
    ref="taskLookRef"
    :paper-Id="currentPaperId"  
  />
  <paper-set
    v-model="showSet"
    :task-Id="taskId"
    ref="taskSetRef"
     @done="reload"
  />
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick,onMounted,watch} from 'vue';
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as PaperApi from '@/api/system/paper';
import PaperEdit from './components/step-edit.vue';
import PaperAdd from './components/step-add.vue';
import PaperLook from './components/step-look.vue';
import PaperSet from './components/step-set.vue';
import { useI18n } from 'vue-i18n';

defineOptions({ name: 'SystemPaper' });

const { t } = useI18n();
const message = useMessage();

const props = defineProps({
  taskSpecialty: {
    type: String,
    default: '',
  },
  taskId: {
    type: String,
    default: '',
  },
});

// 定义数据项的类型
interface PaperItem {
  paperId: number; // 假设每个项目都有 paperId
  counts: number;
  rollUp: string;
  isAb: string;
  status: string;
  num:string;
  // 你可以根据需要扩展更多字段
}

// 当前编辑的数据
const current = ref<object>();

// 弹窗显示状态
const showEdit = ref(false);
const showLook = ref(false);
const showAdd = ref(false);
const showSet = ref(false);

// ref 对应的组件实例
const taskAddRef = ref();
const taskEditRef = ref();
const taskLookRef = ref();
const taskSetRef = ref();

const loading = ref(false); // 列表的加载状态
const total = ref(0); // 列表的总页数
const list = ref<PaperItem[]>([]); // 列表的数据，明确指定类型
const queryFormRef = ref(); // 搜索表单的 ref

// 多选框绑定的变量，指定为 PaperItem 类型的数组
const selectedRows = ref<PaperItem[]>([]);

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  paperId: undefined,
  status: undefined,
  createTime: [],
  taskId:props.taskId
});

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const res = await PaperApi.pagePapers(queryParams);
    list.value = res.list;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};
const reload = () => {
 
  getList();
};


// 搜索操作
const handleQuery = () => {
  queryParams.pageNo = 1;
  getList();
};

// 重置操作
const resetQuery = () => {
  queryFormRef.value.resetFields();
  handleQuery();
};

// 打开新增表单
const openAddForm = () => {
  showAdd.value = true;
  nextTick(() => {
    taskAddRef.value?.open();
  });
};

const openSet = () => {
  showSet.value = true;
  nextTick(() => {
    taskSetRef.value?.open();
  });
};

/** 表格选中数据 */
  const selections = ref([]);
const openDown = async () => {

   try {
    const rows = selections.value;
  if (!rows.length) {
    message.error('请至少选择一条数据');
    return;
  }

  selectedRows.value = rows.map((d: any) => d.paperId); // 保存选中的行数据
  await PaperApi.openDown(selectedRows.value)
    message.success(t('下载成功'))
    // 刷新列表
    await getList()
  } catch {}

};
  

const handleSelectionChange = (rows) => {
  selections.value = rows;
}


// 打开编辑弹窗
const openEdit = (type: string, row?: object) => {
  showEdit.value = true;
  current.value = row;
  nextTick(() => {
    taskEditRef.value?.open(type, row);
  });
};
const currentPaperId = ref<number | null>(null);

const openLook = (type: string, paperId?: number) => {
  showLook.value = true;
  currentPaperId.value = paperId ?? null;  // 设置当前选中的 paperId
  nextTick(() => {
    taskLookRef.value?.open(type, paperId);
  });
};



// 删除操作
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm();
    await PaperApi.removePaper(id);
    message.success(t('common.delSuccess'));
    await getList();
  } catch (error) {
    console.error(error);
  }
};

// 批量删除操作
const batchDelete = async () => {
  try {
    const ids = selectedRows.value.map(item => item.paperId); // 使用 paperId 属性
    if (ids.length > 0) {
      await message.delConfirm();
      await PaperApi.removePapers(ids); // 调用批量删除接口
      message.success(t('common.delSuccess'));
      await getList();
      selectedRows.value = []; // 清空选择的行
    }
  } catch (error) {
    console.error(error);
  }
};


const handleStatusChange = async (row: any) => {
  console.log(row.paperId, row.status+"row.taskId, row.status");
  
  try {
    loading.value = true;
    // 调用API更新状态
    await PaperApi.updatePaperStatus(row.paperId, row.status);
    message.success(row.status === '0' ? '已启用' : '已停用');
    // 刷新列表
    await getList();
  } catch (error) {
    // 如果请求失败，恢复原来的状态
    row.status = row.status === '0' ? '1' : '0';
    message.error('状态更新失败');
  } finally {
    loading.value = false;
  }
};

// 初始化操作
onMounted(() => {
  getList();
});
watch(selectedRows, (newVal) => {
  console.log('选中的行:', newVal);
});

</script>
