<template>
  <div class="container-box">
    <div class="header-bar">
      <h2>需求管理</h2>
      <div>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增需求
        </el-button>
        <el-button type="primary" @click="handleRefush">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="mb-4">
        <el-form-item label="需求标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入需求标题"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="需求状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="待处理" :value="1" />
            <el-option label="处理中" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已拒绝" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 需求列表 -->
    <el-table v-loading="loading" :data="demandList" style="width: 100%" border>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="标题" min-width="100" />
      <el-table-column
        prop="desc"
        label="描述"
        min-width="300"
        show-overflow-tooltip
      />
      <el-table-column prop="applicant" label="申请人" width="120" />
      <el-table-column prop="phone" label="电话" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination" v-if="total > 0">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 需求表单组件 -->
    <Edit
      :visible="dialogVisible"
      :title="dialogTitle"
      :demand="form"
      @close="handleFormClose"
      @submit="handleFormSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { Plus, Refresh } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Edit from "./components/edit.vue";
import { getDemandList, deleteDemand } from "@/api/demand";

// 状态管理
const loading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref("新增需求");

// 搜索表单
const searchForm = reactive({
  title: "",
  status: "",
});

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
});

// 总数据量
const total = ref(0);

// 需求列表
const demandList = ref<any[]>([]);

// 表单数据
const form = reactive({
  id: "",
  title: "",
  desc: "",
  applicant: "",
  status: 1,
});

// 状态类型映射
const getStatusType = (status: string | number) => {
  const typeMap: Record<string | number, string> = {
    1: "info",
    2: "warning",
    3: "success",
    4: "danger",
  };
  return typeMap[status] || "info";
};

// 状态文本映射
const getStatusText = (status: string | number) => {
  const textMap: Record<string | number, string> = {
    1: "待处理",
    2: "处理中",
    3: "已完成",
    4: "已拒绝",
  };
  return textMap[status] || String(status);
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchDemandList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.title = "";
  searchForm.status = "";
  pagination.current = 1;
  fetchDemandList();
};

// 获取需求列表
const fetchDemandList = async () => {
  loading.value = true;
  try {
    const data = await getDemandList();

    if (data.code === 200) {
      let filteredList = [...data.list];

      // 根据搜索条件过滤数据
      if (searchForm.title) {
        filteredList = filteredList.filter((item) =>
          item.title.includes(searchForm.title),
        );
      }
      if (searchForm.status) {
        filteredList = filteredList.filter(
          (item) => item.status === searchForm.status,
        );
      }

      // 模拟分页
      total.value = filteredList.length;
      const start = (pagination.current - 1) * pagination.size;
      const end = start + pagination.size;
      demandList.value = filteredList.slice(start, end);
    } else {
      ElMessage.error("获取需求列表失败");
    }
  } catch (error) {
    ElMessage.error("网络错误，请稍后重试");
    console.error("获取需求列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  fetchDemandList();
};

// 页码变化
const handleCurrentChange = (current: number) => {
  pagination.current = current;
  fetchDemandList();
};

// 新增需求
const handleAdd = () => {
  dialogTitle.value = "新增需求";
  Object.assign(form, {
    id: "",
    title: "",
    desc: "",
    applicant: "",
    status: 1,
  });
  dialogVisible.value = true;
};

// 编辑需求
const handleEdit = (row: any) => {
  dialogTitle.value = "编辑需求";
  Object.assign(form, row);
  dialogVisible.value = true;
};

// 删除需求
const handleDelete = async (id: number) => {
  ElMessageBox.confirm("确定要删除这个需求吗？", "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const result = await deleteDemand(id);

        if (result.code === 200) {
          ElMessage.success("删除成功");
          fetchDemandList();
        } else {
          ElMessage.error(result.msg || "删除失败");
        }
      } catch (error) {
        ElMessage.error("网络错误，请稍后重试");
        console.error("删除需求失败:", error);
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 刷新需求
const handleRefush = () => {
  fetchDemandList();
};

// 处理表单关闭
const handleFormClose = () => {
  dialogVisible.value = false;
};

// 处理表单提交
const handleFormSubmit = () => {
  dialogVisible.value = false;
  fetchDemandList();
};

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

<style lang="less" scoped>
.container-box {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
  }
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}
</style>
