<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">
            <el-icon style="margin-right: 5px"><Plus /></el-icon>新增基础信息
          </el-button>
        </div>
      </template>

      <div class="filter-container">
        <el-input
            v-model="queryParams.keyword"
            placeholder="请输入基础信息名称或规格"
            style="width: 220px; margin-right: 10px;"
            clearable
            @keyup.enter="handleQuery"
        />

        <el-select v-model="queryParams.category" placeholder="基础信息类别" clearable style="width: 150px; margin-right: 10px;">
          <el-option label="采购件" value="PURCHASE" />
          <el-option label="自制件" value="SELF_MADE" />
        </el-select>

        <el-select v-model="queryParams.type" placeholder="物料类型" clearable style="width: 150px; margin-right: 10px;">
          <el-option label="电子料" value="ELEC" />
          <el-option label="结构件" value="STRUCT" />
        </el-select>

        <el-select v-model="queryParams.isEnabled" placeholder="状态" clearable style="width: 100px; margin-right: 10px;">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>

        <el-button type="primary" plain @click="handleQuery">搜索</el-button>
        <el-button plain @click="resetQuery">重置</el-button>
      </div>

      <el-table
          v-loading="loading"
          :data="tableData"
          border
          stripe
          style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />

        <el-table-column prop="name" label="基础信息名称" min-width="150" show-overflow-tooltip />

        <el-table-column prop="category" label="类别" width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.category === 'PURCHASE'">采购件</el-tag>
            <el-tag v-else-if="scope.row.category === 'SELF_MADE'" type="success">自制件</el-tag>
            <el-tag v-else type="info">{{ scope.row.category || '-' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="type" label="类型" width="100" align="center">
          <template #default="scope">
            <span v-if="scope.row.type === 'ELEC'">电子料</span>
            <span v-else-if="scope.row.type === 'STRUCT'">结构件</span>
            <span v-else>{{ scope.row.type || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="spec" label="规格型号" min-width="150" show-overflow-tooltip />

        <el-table-column prop="unit" label="单位" width="70" align="center" />

        <el-table-column prop="visibilityLevel" label="可见等级" width="90" align="center">
          <template #default="scope">
            L{{ scope.row.visibilityLevel }}
          </template>
        </el-table-column>

        <el-table-column label="资料" width="100" align="center">
          <template #default="scope">
            <el-button
                v-if="scope.row.generalImage"
                link type="primary"
                :icon="Picture"
                title="查看图片"
                @click="openLink(scope.row.generalImage)"
            />
            <el-button
                v-if="scope.row.generalManual"
                link type="primary"
                :icon="Document"
                title="查看说明书"
                @click="openLink(scope.row.generalManual)"
            />
          </template>
        </el-table-column>

        <el-table-column prop="isEnabled" label="是否启用" width="100" align="center">
          <template #default="scope">
            <el-switch
                v-model="scope.row.isEnabled"
                :active-value="1"
                :inactive-value="0"
                :loading="scope.row.statusLoading"
                @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 20px; text-align: right;">
        <el-pagination
            background
            layout="total, prev, pager, next, sizes"
            :total="total"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            @size-change="getList"
            @current-change="getList"
        />
      </div>

    </el-card>
  </div>
</template>

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

// 【关键修改】引入刚才定义的 API 文件
import {
  listMaterialBase,
  delMaterialBase,
  updateMaterialBase
} from '@/api/material_base';

// --- 类型定义 ---
interface MaterialBaseVO {
  id: number;
  name: string;
  category: string;
  type: string;
  spec: string;
  unit: string;
  visibilityLevel: number;
  generalManual?: string;
  generalImage?: string;
  isEnabled: number; // 1 or 0
  statusLoading?: boolean; // 辅助字段
}

interface QueryParams {
  pageNum: number;
  pageSize: number;
  keyword: string;
  category: string;
  type: string;
  isEnabled?: number;
}

// --- 响应式数据 ---
const loading = ref(false);
const total = ref(0);
const tableData = ref<MaterialBaseVO[]>([]);

const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  category: '',
  type: '',
  isEnabled: undefined
});

// --- 业务逻辑方法 ---

// 获取数据
const getList = () => {
  loading.value = true;
  // 调用 API 文件中的 listMaterialBase
  listMaterialBase(queryParams)
      .then((response: any) => {
        // 我们的 request.ts 已经处理了 code!=200，这里直接拿 data
        if (response && response.data) {
          tableData.value = response.data.items;
          total.value = response.data.total;
        } else {
          tableData.value = [];
          total.value = 0;
        }
      })
      .catch((err) => {
        console.error(err);
        tableData.value = [];
      })
      .finally(() => {
        loading.value = false;
      });
};

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

// 重置
const resetQuery = () => {
  queryParams.keyword = '';
  queryParams.category = '';
  queryParams.type = '';
  queryParams.isEnabled = undefined;
  handleQuery();
};

// 新增
const handleAdd = () => {
  ElMessage.info("请实现新增弹窗逻辑");
  // 逻辑：dialogVisible.value = true
};

// 编辑
const handleEdit = (row: MaterialBaseVO) => {
  console.log("点击编辑", row);
  ElMessage.info(`准备编辑 ID: ${row.id}`);
  // 逻辑：调用 getMaterialBase(row.id) 回显数据
};

// 状态切换 (实时保存)
const handleStatusChange = (row: MaterialBaseVO) => {
  row.statusLoading = true;
  const text = row.isEnabled === 1 ? "启用" : "停用";

  const updateData = {
    id: row.id,
    isEnabled: row.isEnabled
  };

  // 调用 API 文件中的 updateMaterialBase
  updateMaterialBase(updateData)
      .then(() => {
        ElMessage.success(`已${text} "${row.name}"`);
      })
      .catch(() => {
        // 失败回滚
        row.isEnabled = row.isEnabled === 1 ? 0 : 1;
      })
      .finally(() => {
        row.statusLoading = false;
      });
};

// 删除
const handleDelete = (row: MaterialBaseVO) => {
  ElMessageBox.confirm(
      `是否确认删除名称为 "${row.name}" 的数据项? \n如果该物料已有库存记录，删除将会被拒绝。`,
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
  ).then(() => {
    // 调用 API 文件中的 delMaterialBase
    delMaterialBase(row.id)
        .then(() => {
          ElMessage.success("删除成功");
          if (tableData.value.length === 1 && queryParams.pageNum > 1) {
            queryParams.pageNum--;
          }
          getList();
        });
  }).catch(() => {
    // 取消
  });
};

// 打开链接
const openLink = (url: string) => {
  if (!url) return;
  window.open(url, '_blank');
}

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

<style scoped>
.app-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.filter-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 20px;
}
</style>