<template>

  <ContentWrap>
     <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
     
      <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="openForm('create')"
          v-hasPermi="['system:sms-channel:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增</el-button
        >

        <el-button
  type="warning"
  class="ele-btn-icon"
  :disabled="!selections.length"
  @click="papreSet()"
>
  批量分配
</el-button>

      </el-form-item>
    </el-form> 
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list"   @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="考试批次" align="center" prop="batch" />
      <el-table-column label="考试开始时间" align="center" prop="startTime" />
      <el-table-column label="考试结束时间" align="center" prop="endTime" />
      <el-table-column label="开始考试前分钟，允许入场" align="center" prop="allowEntry" />
      <el-table-column label="开始考试后分钟，禁止入场" align="center" prop="endAllowEntry" />
      <el-table-column label="开始考试后分钟，允许交卷" align="center" prop="allowSubmission" />
      <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="openEdit('update', scope.row)"
            v-hasPermi="['system:sms-channel:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.sessionId)"
            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>




  <session-edit v-model="showEdit" :data="current" :task-Id="taskId" @done="reload"   ref="taskEditRef" />
  <paper-set v-model="showSet" :task-Id="taskId" :rows="selectedRows" @done="reload"/>
</template>
<script lang="ts" setup>

import * as SmsChannelApi from '@/api/system/session';

import SessionSearch from './components/step-search.vue';
import SessionEdit from './components/step-edit.vue';
import PaperSet from './components/step-set.vue';
import { DICT_TYPE } from '@/utils/dict';

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

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

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

  /** 是否显示编辑弹窗 */
  const showEdit = ref(false);

  const showLook = ref(false);

  const showAdd = ref(false);

  const showSet = ref(false);
  

const taskEditRef = ref()




const loading = ref(false) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryFormRef = ref() // 搜索的表单
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  signature: undefined,
  status: undefined,
  createTime: [],
  taskId: props.taskId
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await SmsChannelApi.pageSessions(queryParams)
    console.log(res)
    list.value = res
    total.value = res.total
  } finally {
    loading.value = false
  }
}

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

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

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

  const selectedRows = ref<string[]>([]);

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

  selectedRows.value = rows.map((d: any) => d.sessionId); // 保存选中的行数据
  showSet.value = true; // 打开弹窗
};

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

/** 添加/修改操作 */
const formRef = ref();
const openForm = (type: string, ) => {
  showEdit.value = true

  console.log( current.value )
  taskEditRef.value?.open(type)
}

const openEdit = (type: string, row?: object) => {
  showEdit.value = true
  current.value = row
  console.log( current.value )
  taskEditRef.value?.open(type, row)
  
}

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


const reload = (where) => {
  getList()
  };

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SmsChannelApi.removeSession(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
