<template>
  <div class="p-2">
    <el-row :gutter="20">
      <el-col :span="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="AppName" prop="appname">
                  <el-input v-model="queryParams.appname" placeholder="请输入AppName" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="名称" prop="title">
                  <el-input v-model="queryParams.title" placeholder="请输入执行器名称" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="注册方式" prop="addressType">
                  <el-select v-model="queryParams.addressType" placeholder="注册方式" clearable>
                    <el-option label="自动注册" :value="0" />
                    <el-option label="手动录入" :value="1" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-hasPermi="['xxljob:xxljobgroup:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['xxljob:xxljobgroup:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                >修改</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['xxljob:xxljobgroup:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">
                  删除
                </el-button>
              </el-col>
              <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
            </el-row>
          </template>
          <el-table v-loading="loading" :data="executorList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" align="center" prop="id" width="60" />
            <el-table-column label="AppName" align="center" prop="appname" width="150" show-overflow-tooltip />
            <el-table-column label="名称" align="center" prop="title" show-overflow-tooltip />
            <el-table-column label="注册方式" align="center" prop="addressType" width="120">
              <template #default="scope">
                <el-tag :type="scope.row.addressType === 0 ? 'success' : 'info'">
                  {{ scope.row.addressType === 0 ? '自动注册' : '手动录入' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="机器地址" align="center" prop="addressList" show-overflow-tooltip>
              <template #default="scope">
                <div v-if="scope.row.addressType === 1">
                  {{ scope.row.addressList || '-' }}
                </div>
                <div v-else>
                  <div v-if="scope.row.onlineRegistryList && scope.row.onlineRegistryList.length > 0">
                    <el-tag v-for="addr in scope.row.onlineRegistryList" :key="addr" type="success" size="small" class="mr-1 mb-1">
                      {{ addr }}
                    </el-tag>
                  </div>
                  <div v-if="scope.row.offlineRegistryList && scope.row.offlineRegistryList.length > 0">
                    <el-tag v-for="addr in scope.row.offlineRegistryList" :key="addr" type="danger" size="small" class="mr-1 mb-1">
                      {{ addr }}
                    </el-tag>
                  </div>
                  <span v-if="(!scope.row.onlineRegistryList || scope.row.onlineRegistryList.length === 0) &&
                      (!scope.row.offlineRegistryList || scope.row.offlineRegistryList.length === 0)
                    "
                  >
                    暂无注册节点
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
              <template #default="scope">
                <span>{{ proxy.parseTime(scope.row.updateTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button v-hasPermi="['xxljob:xxljobgroup:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button v-hasPermi="['xxljob:xxljobgroup:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="注册节点" placement="top" v-if="scope.row.addressType === 0">
                  <el-button v-hasPermi="['xxljob:xxljobgroup:registry']" link type="primary" icon="Connection" @click="handleViewRegistry(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :total="total"
            @pagination="getList"
          />
        </el-card>

        <!-- 引入执行器表单组件 -->
        <executor-form v-model:visible="formVisible" :edit-type="editType" :row-data="currentRow" @save="handleSave"> </executor-form>

        <!-- 注册节点详情对话框 -->
        <executor-registry v-model:visible="registryVisible" :executor-data="currentRow" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="JobGroup" lang="ts">
import { listJobGroup, delJobGroup } from '@/api/xxljob/executor';
import { JobGroupQuery, JobGroupVO } from '@/api/xxljob/executor/types';
import ExecutorForm from './executorForm.vue';
import ExecutorRegistry from './executorRegistry.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 表单控制状态
const formVisible = ref(false);
const registryVisible = ref(false);
const editType = ref('');
const currentRow = ref<JobGroupVO | null>(null);

const executorList = ref<JobGroupVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();

// 查询参数
const queryParams = reactive<JobGroupQuery>({
  pageNum: 1,
  pageSize: 10,
  appname: '',
  title: '',
  addressType: ''
});

/** 查询执行器列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listJobGroup(queryParams);
    executorList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: JobGroupVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  currentRow.value = null;
  editType.value = 'add';
  formVisible.value = true;
};

/** 修改按钮操作 */
const handleUpdate = (row?: JobGroupVO) => {
  if (row) {
    currentRow.value = row;
  } else {
    const selectedExecutor = executorList.value.find((item) => item.id === ids.value[0]);
    currentRow.value = selectedExecutor || null;
  }
  editType.value = 'edit';
  formVisible.value = true;
};

/** 保存成功后的处理 */
const handleSave = () => {
  getList();
};

/** 查看注册节点 */
const handleViewRegistry = (row: JobGroupVO) => {
  currentRow.value = row;
  registryVisible.value = true;
};

/** 删除按钮操作 */
const handleDelete = async (row?: JobGroupVO) => {
  const executorIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除选择数据项？');
  await delJobGroup(executorIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getList();
});
</script>
