<template>
  <div class="container-box">
    <div class="header-bar">
      <h2>程序管理</h2>
      <el-button type="primary" @click="showProgramDialog = true">
        <el-icon><Plus /></el-icon>
        添加程序
      </el-button>
    </div>

    <el-divider></el-divider>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <div class="loading-spinner"></div>
      <p>正在加载程序数据...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-state">
      <el-alert title="加载失败" :message="error" type="error" show-icon />
      <el-button type="primary" @click="fetchPrograms">重试</el-button>
    </div>

    <!-- 程序列表 -->
    <div v-else>
      <el-table :data="programs" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="程序名称" min-width="160" align="center" />
        <el-table-column prop="type" label="类型" width="100" align="center" />
        <el-table-column prop="owner" label="负责人" width="120" align="center" />
        <el-table-column prop="createdAt" label="创建时间" width="170" align="center" />
        <el-table-column prop="remark" label="备注" min-width="140" align="center" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-bar">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :total="total"
          @current-change="handlePageChange"
          layout="total, prev, pager, next"
        />
      </div>
    </div>

    <!-- 新增/编辑程序弹窗 -->
    <el-dialog
      :title="isEditing ? '编辑程序' : '添加程序'"
      v-model="showProgramDialog"
      width="420px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="programForm"
        :rules="formRules"
        ref="programFormRef"
        label-width="90px"
      >
        <el-form-item label="程序名称" prop="name">
          <el-input v-model="programForm.name" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="programForm.type" placeholder="选择类型">
            <el-option label="Web" value="Web" />
            <el-option label="服务" value="Service" />
            <el-option label="工具" value="Tool" />
            <el-option label="其他" value="Other" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="owner">
          <el-input v-model="programForm.owner" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="programForm.remark" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showProgramDialog = false">取消</el-button>
        <el-button type="primary" @click="submitProgramForm"> 保存 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
} from "element-plus";
import { Plus } from "@element-plus/icons-vue";

// 数据与状态
const programs = ref<any[]>([]);
const loading = ref(false);
const error = ref("");
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

const showProgramDialog = ref(false);
const isEditing = ref(false);
const programForm = reactive({
  id: null,
  name: "",
  type: "",
  owner: "",
  remark: "",
});
const programFormRef = ref<FormInstance>();

const formRules: FormRules = {
  name: [
    { required: true, message: "请输入程序名称", trigger: "blur" },
    { min: 2, max: 32, message: "名称长度2-32字符", trigger: "blur" },
  ],
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  owner: [{ required: true, message: "请输入负责人", trigger: "blur" }],
};

async function fetchPrograms() {
  loading.value = true;
  error.value = "";
  try {
    // TODO: 替换为真实API
    await new Promise((r) => setTimeout(r, 250));
    // 假数据
    const all = [
      {
        id: 1,
        name: "门户网站",
        type: "Web",
        owner: "张三",
        createdAt: "2023-11-08 09:22:53",
        remark: "官网",
      },
      {
        id: 2,
        name: "自动备份服务",
        type: "Service",
        owner: "李四",
        createdAt: "2024-01-16 15:40:01",
        remark: "每日凌晨自动执行",
      },
      {
        id: 3,
        name: "运维工具",
        type: "Tool",
        owner: "王五",
        createdAt: "2023-12-02 12:51:29",
        remark: "",
      },
      // ...更多
    ];
    total.value = all.length;
    programs.value = all.slice(
      (page.value - 1) * pageSize.value,
      page.value * pageSize.value
    );
  } catch (err: any) {
    error.value = err.message || "获取程序列表失败";
  } finally {
    loading.value = false;
  }
}

const handlePageChange = (val: number) => {
  page.value = val;
  fetchPrograms();
};

function resetProgramForm() {
  programForm.id = null;
  programForm.name = "";
  programForm.type = "";
  programForm.owner = "";
  programForm.remark = "";
}

function handleEdit(row: any) {
  isEditing.value = true;
  programForm.id = row.id;
  programForm.name = row.name;
  programForm.type = row.type;
  programForm.owner = row.owner;
  programForm.remark = row.remark;
  showProgramDialog.value = true;
}

async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm(
      `确定要删除程序「${row.name}」? 删除后不可恢复。`,
      "警告",
      { type: "warning" }
    );
    // TODO: 替换为真实API
    await new Promise((r) => setTimeout(r, 250));
    ElMessage.success("删除成功");
    fetchPrograms();
  } catch {
    // 取消删除
  }
}

async function submitProgramForm() {
  await programFormRef.value?.validate();
  loading.value = true;
  try {
    if (isEditing.value) {
      // TODO: 替换为真实API更新
      await new Promise((r) => setTimeout(r, 250));
      ElMessage.success("程序更新成功");
    } else {
      // TODO: 替换为真实API新增
      await new Promise((r) => setTimeout(r, 250));
      ElMessage.success("程序添加成功");
    }
    showProgramDialog.value = false;
    fetchPrograms();
  } catch (e: any) {
    ElMessage.error(e.message || "操作失败，请重试");
  } finally {
    loading.value = false;
  }
}

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

<style scoped>
</style>
