<template>
  <div class="message-board-container">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="留言人">
          <el-input
              v-model="searchForm.name"
              placeholder="请输入留言人姓名"
              clearable
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input
              v-model="searchForm.phone"
              placeholder="请输入联系电话"
              clearable
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchMessages">查询</el-button>
          <el-button @click="resetSearchForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据展示区域 -->
    <el-card class="table-card" shadow="hover">
      <el-table
          v-loading="loading"
          :data="messageList"
          border
          stripe
          @selection-change="handleSelectionChange"
          style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="留言人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="deviceName" label="产品名称" width="180" />
        <el-table-column
            prop="content"
            label="留言内容"
            min-width="200"
            show-overflow-tooltip
        />
        <el-table-column
            prop="createTime"
            label="留言时间"
            width="180"
            align="center"
        />
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                icon="el-icon-view"
                @click="viewMessage(scope.row)"
            >
              查看详情
            </el-button>
            <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                @click="deleteMessage(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="fetchMessages"
          style="margin-top: 20px; text-align: right"
      />
    </el-card>

    <!-- 查看详情弹窗 -->
    <el-dialog
        v-model="viewDialogVisible"
        title="留言详情"
        width="600px"
        @close="resetViewForm"
    >
      <el-form
          :model="viewForm"
          label-width="80px"
          disabled
      >
        <el-form-item label="留言人">
          <el-input v-model="viewForm.name" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="viewForm.phone" />
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input v-model="viewForm.deviceName" />
        </el-form-item>
        <el-form-item label="留言时间">
          <el-input v-model="viewForm.createTime" />
        </el-form-item>
        <el-form-item label="留言内容">
          <el-input
              v-model="viewForm.content"
              type="textarea"
              rows="6"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from "@/utils/request.js"

// 定义接口类型（只保留指定字段）
interface MessageItem {
  id: number;
  name: string;         // 留言人
  phone: string;        // 联系电话
  deviceName: string;   // 产品名称（原productName改为deviceName）
  content: string;      // 留言内容
  createTime: string;   // 留言时间
}

interface Pagination {
  pageNum: number;
  pageSize: number;
  total: number;
}

interface SearchForm {
  name: string;
  phone: string;
  dateRange: [string, string] | null;
}

interface ViewForm {
  id: number;
  name: string;
  phone: string;
  deviceName: string;
  content: string;
  createTime: string;
}

// 加载状态
const loading = ref(false);

// 留言列表数据
const messageList = ref<MessageItem[]>([]);

// 分页参数
const pagination = reactive<Pagination>({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 搜索表单（移除status字段）
const searchForm = reactive<SearchForm>({
  name: '',
  phone: '',
  dateRange: null
});

// 选中的ID列表（批量操作）
const selectedIds = ref<number[]>([]);

// 查看详情弹窗相关
const viewDialogVisible = ref(false);
const viewForm = reactive<ViewForm>({
  id: 0,
  name: '',
  phone: '',
  deviceName: '',
  content: '',
  createTime: ''
});

// 获取留言列表
const fetchMessages = async () => {
  try {
    loading.value = true;
    // 构造查询参数（只保留必要参数）
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      name: searchForm.name,
      phone: searchForm.phone,
      // 时间范围参数（如果后端需要）
      startDate: searchForm.dateRange?.[0] || '',
      endDate: searchForm.dateRange?.[1] || ''
    };

    const res = await request.get("/messageData/findByPage", {
      params: params
    });

    console.log('留言列表数据：', res);

    // 适配接口返回数据
    messageList.value = res.data.records || [];
    pagination.total = res.data.total || 0;
  } catch (error) {
    ElMessage.error('获取留言列表失败，请稍后重试');
    console.error('获取留言失败：', error);
  } finally {
    loading.value = false;
  }
};

// 重置搜索表单
const resetSearchForm = () => {
  searchForm.name = '';
  searchForm.phone = '';
  searchForm.dateRange = null;
  pagination.pageNum = 1;
  fetchMessages();
};

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchMessages();
};

// 处理表格选择事件
const handleSelectionChange = (val: MessageItem[]) => {
  selectedIds.value = val.map(item => item.id);
};

// 查看留言详情
const viewMessage = (row: MessageItem) => {
  viewForm.id = row.id;
  viewForm.name = row.name;
  viewForm.phone = row.phone;
  viewForm.deviceName = row.deviceName;
  viewForm.content = row.content;
  viewForm.createTime = row.createTime;
  viewDialogVisible.value = true;
};

// 重置详情表单
const resetViewForm = () => {
  viewForm.id = 0;
  viewForm.name = '';
  viewForm.phone = '';
  viewForm.deviceName = '';
  viewForm.content = '';
  viewForm.createTime = '';
};

// 删除单条留言
const deleteMessage = async (id: number) => {
  try {
    await ElMessageBox.confirm(
        '此操作将永久删除该留言，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    // 调用删除接口（根据实际接口调整）
    await request.post(`/messageData/delete`,[id]);

    ElMessage.success('删除成功');
    fetchMessages(); // 重新加载列表
  } catch (error) {
    if (error !== 'cancel') { // 排除取消操作的报错
      ElMessage.error('删除失败，请稍后重试');
      console.error('删除留言失败：', error);
    } else {
      ElMessage.info('已取消删除');
    }
  }
};

// 批量删除留言
const batchDelete = async () => {
  try {
    if (selectedIds.value.length === 0) {
      ElMessage.warning('请选择要删除的留言');
      return;
    }

    await ElMessageBox.confirm(
        '此操作将永久删除选中的留言，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    // 调用批量删除接口（根据实际接口调整）
    await request.delete('/messageData/batchDelete', {
      data: { ids: selectedIds.value }
    });

    ElMessage.success('批量删除成功');
    fetchMessages(); // 重新加载列表
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败，请稍后重试');
      console.error('批量删除留言失败：', error);
    } else {
      ElMessage.info('已取消删除');
    }
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchMessages();
});
</script>

<style scoped>
.message-board-container {
  padding: 20px;
  margin: 0 auto;
}

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

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.table-actions {
  margin-bottom: 10px;
}
</style>