<template>

  <ContentWrap>
     <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          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 label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </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 @click="openBank"><Icon icon="ep:download" class="mr-5px" /> 模板库</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增</el-button
        >
        <el-button
          type="danger"
          class="ele-btn-del"
          :disabled="!selections.length"
          @click="handleDeletes()"
        >
          批量删除
        </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="taskNum" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="专业" align="center" prop="taskSpecialty" />
      <el-table-column label="试卷任务模式" align="center" prop="taskType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TASK_TYPE" :value="scope.row.taskType" />
        </template>
      </el-table-column>

      <el-table-column label="是否模板" align="center" prop="isTemplate" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYS_YES_NO" :value="scope.row.isTemplate" />
        </template>
      </el-table-column>
      <el-table-column label="是否共享" align="center" prop="share" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYS_YES_NO" :value="scope.row.share" />
        </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"
            prop="createTime"
            :formatter="dateFormatter"
            width="180"
          />
      <el-table-column label="操作" align="center">
        <template #default="scope">
                     <el-button
            link
            type="primary"
            @click="openForm('update', scope.row)"
          >
            修改
          </el-button>
          <el-button
            link
            type="primary"
            @click="openEdit('update', scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.taskId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <SmsChannelForm ref="smsChannelFormRef" @success="getList" />
<task-edit v-if="showEdit" v-model="showEdit" ref="taskEditRef" :data="current"  @done="reload"/>
<task-add v-if="showAdd" v-model="showAdd" ref="taskAddRef" :data="current"  @done="reload"/>
<task-temp v-if="showOpenTemplate" v-model="showOpenTemplate" ref="taskTempRef" :data="current"  @done="reload"/>

</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import * as SmsChannelApi from '@/api/system/task/index';

import TaskEdit from './components/task-edit.vue';
  import TaskTemp from './components/task-temp.vue';
  import TaskAdd from './components/task-add.vue';

defineOptions({ name: 'SystemSmsChannel' })

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

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

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

  const showAdd = ref(false);



const smsChannelFormRef = ref()
const taskEditRef = ref()
const taskAddRef = ref()
const taskTempRef = 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,
  taskName:undefined,
  createTime: [],
  taskType:'1'
})

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
/** 状态切换处理 */
const handleStatusChange = async (row: any) => {
  console.log(row.taskId, row.status+"row.taskId, row.status");
  
  try {
    loading.value = true;
    // 调用API更新状态
    await SmsChannelApi.updateTaskStatus(row.taskId, 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 selections = ref([]);


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

/** 添加/修改操作 */
const formRef = ref();
const openForm = (type: string, row?: object) => {
  showAdd.value = true
  nextTick(() => {
    taskAddRef.value?.open(type, row)
  });
}

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

const openBank = () => {
  showOpenTemplate.value = true
  taskTempRef.value?.open()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
  const res=  await SmsChannelApi.removeTasks(id)
  console.log(res);
  if(res=='删除成功'){
    message.success(res)
  }else{
    message.error(res)
  }
    // 刷新列表
    await getList()
  } catch {}
}

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


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

  selectedRows.value = rows.map((d: any) => d.taskId); // 保存选中的行数据
  const res= await SmsChannelApi.removeTasks(selectedRows.value)
console.log(res);
  if(res=='删除成功'){
    message.success(res)
  }else{
    message.error(res)
  }
    // 刷新列表
    await getList()
  } catch {}
}

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

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