<template>
  <div class="message-manage-view">
    <!-- 搜索栏 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="消息类型">
          <el-select
            v-model="searchForm.messageType"
            placeholder="全部"
            clearable
            style="width: 150px"
          >
            <el-option label="通知" value="notice" />
            <el-option label="公告" value="announcement" />
            <el-option label="警告" value="warning" />
            <el-option label="系统消息" value="system" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="全部"
            clearable
            style="width: 150px"
          >
            <el-option label="草稿" value="draft" />
            <el-option label="待发送" value="pending" />
            <el-option label="发送中" value="sending" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-form-item>

        <el-form-item label="优先级">
          <el-select
            v-model="searchForm.priority"
            placeholder="全部"
            clearable
            style="width: 150px"
          >
            <el-option label="紧急" value="urgent" />
            <el-option label="重要" value="important" />
            <el-option label="普通" value="normal" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="operation-card" shadow="never">
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        创建消息
      </el-button>
      <el-button @click="loadMessages">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </el-card>

    <!-- 消息列表 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="messageList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />

        <el-table-column label="类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getMessageTypeTag(row.messageType || '')">
              {{ getMessageTypeLabel(row.messageType || '') }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="优先级" width="100" align="center">
          <template #default="{ row }">
            <MessagePriorityBadge :priority="row.priority" />
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <MessageStatusBadge :status="row.status || ''" />
          </template>
        </el-table-column>

        <el-table-column label="发送方式" width="150" align="center">
          <template #default="{ row }">
            <el-tag
              v-for="method in row.sendMethods"
              :key="method"
              size="small"
              style="margin: 2px"
            >
              {{ getSendMethodLabel(method) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="发送时间" width="180" align="center">
          <template #default="{ row }">
            {{ row.scheduledTime || '立即发送' }}
          </template>
        </el-table-column>

        <el-table-column label="创建时间" width="180" align="center" prop="createdAt" />

        <el-table-column label="操作" width="300" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>

            <el-button
              v-if="row.status === 'draft'"
              link
              type="primary"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>

            <el-button
              v-if="['pending', 'draft'].includes(row.status || '')"
              link
              type="success"
              @click="handleSend(row)"
            >
              立即发送
            </el-button>

            <el-button
              v-if="row.status === 'failed'"
              link
              type="warning"
              @click="handleRetry(row)"
            >
              重试
            </el-button>

            <el-button
              v-if="row.status === 'pending'"
              link
              type="warning"
              @click="handleReschedule(row)"
            >
              改期
            </el-button>

            <el-button
              v-if="['pending', 'sending'].includes(row.status || '')"
              link
              type="danger"
              @click="handleCancel(row)"
            >
              取消
            </el-button>

            <el-button
              v-if="['draft', 'cancelled', 'failed'].includes(row.status || '')"
              link
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadMessages"
        @current-change="loadMessages"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      :title="isEdit ? '编辑消息' : '创建消息'"
      width="900px"
      :close-on-click-modal="false"
    >
      <MessageAdd
        ref="messageAddRef"
        :model-value="currentMessage"
        :is-edit="isEdit"
      />
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button @click="handleSaveDraft">保存草稿</el-button>
        <el-button type="primary" @click="handleSubmit">
          {{ isEdit ? '更新' : '创建并发送' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="消息详情"
      width="900px"
      :close-on-click-modal="false"
    >
      <div v-if="currentDetail" class="detail-content">
        <!-- 基本信息 -->
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="标题">
            {{ currentDetail.title }}
          </el-descriptions-item>
          <el-descriptions-item label="消息类型">
            <el-tag :type="getMessageTypeTag(currentDetail.messageType || '')">
              {{ getMessageTypeLabel(currentDetail.messageType || '') }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <MessagePriorityBadge :priority="currentDetail.priority || ''" />
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <MessageStatusBadge :status="currentDetail.status || ''" />
          </el-descriptions-item>
          <el-descriptions-item label="发送方式" :span="2">
            <el-tag
              v-for="method in currentDetail.sendMethods"
              :key="method"
              style="margin-right: 8px"
            >
              {{ getSendMethodLabel(method) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="内容" :span="2">
            <div style="white-space: pre-wrap">{{ currentDetail.content }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="计划发送时间">
            {{ currentDetail.scheduledTime || '立即发送' }}
          </el-descriptions-item>
          <el-descriptions-item label="实际发送时间">
            {{ currentDetail.actualSendTime || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ currentDetail.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ currentDetail.updateTime }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 发送统计 -->
        <el-divider content-position="left">发送统计</el-divider>
        <MessageStatistic :statistics="currentDetail" />
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 改期对话框 -->
    <el-dialog
      v-model="rescheduleDialogVisible"
      title="改期发送"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form label-width="100px">
        <el-form-item label="新发送时间">
          <el-date-picker
            v-model="newScheduledTime"
            type="datetime"
            placeholder="选择新的发送时间"
            :disabled-date="disablePastDate"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rescheduleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReschedule">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Search,
  RefreshLeft,
  Plus,
  Refresh
} from '@element-plus/icons-vue';
import { messageApi } from '@/apis/message';
import { MessagePriorityBadge, MessageStatusBadge } from '@/components/message';
import { MessageAdd, MessageStatistic } from './components';
import type { MessageVO, TbSysMessage } from '@/types';

// 搜索表单
const searchForm = reactive<Partial<TbSysMessage> & { page?: number; size?: number }>({
  title: '',
  messageType: undefined,
  status: undefined,
  priority: undefined
});

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

// 列表数据
const loading = ref(false);
const messageList = ref<MessageVO[]>([]);

// 创建/编辑对话框
const createDialogVisible = ref(false);
const isEdit = ref(false);
const messageAddRef = ref();
const currentMessage = ref<TbSysMessage>({
  title: '',
  content: '',
  messageType: 'notice',
  priority: 'normal',
  sendMode: 'immediate',
  scheduledTime: '',
  maxRetryCount: 3,
  sendMethods: ['system'],
  targets: []
});

// 详情对话框
const detailDialogVisible = ref(false);
const currentDetail = ref<MessageVO | null>(null);

// 改期对话框
const rescheduleDialogVisible = ref(false);
const currentRescheduleId = ref('');
const newScheduledTime = ref('');

/** 加载消息列表 */
async function loadMessages() {
  loading.value = true;
  try {
    const result = await messageApi.getMessagePage({
      pageParam: {
        pageNumber: pagination.page,
        pageSize: pagination.size
      },
      filter: searchForm
    });

    if (result.success) {
      messageList.value = result.dataList || [];
      pagination.total = result.pageDomain?.pageParam.totalElements || 0;
    } else {
      ElMessage.error(result.message || '加载失败');
    }
  } catch (error) {
    console.error('加载消息列表失败:', error);
    ElMessage.error('加载失败');
  } finally {
    loading.value = false;
  }
}

/** 搜索 */
function handleSearch() {
  pagination.page = 1;
  loadMessages();
}

/** 重置搜索 */
function handleReset() {
  Object.assign(searchForm, {
    title: '',
    messageType: undefined,
    status: undefined,
    priority: undefined
  });
  handleSearch();
}

/** 创建消息 */
function handleCreate() {
  isEdit.value = false;
  currentMessage.value = {
    title: '',
    content: '',
    messageType: 'notice',
    priority: 'normal',
    sendMode: 'immediate',
    scheduledTime: '',
    maxRetryCount: 3,
    sendMethods: ['system'],
    targets: []
  };
  createDialogVisible.value = true;
}

/** 编辑消息 */
async function handleEdit(row: MessageVO) {
  try {
    const result = await messageApi.getMessageDetail(row.messageID!);
    if (result.success && result.data) {
      isEdit.value = true;
      currentMessage.value = {
        messageID: result.data.messageID,
        title: result.data.title ?? '',
        content: result.data.content ?? '',
        messageType: result.data.messageType ?? 'notice',
        priority: result.data.priority ?? 'normal',
        sendMode: result.data.sendMode ?? 'immediate',
        scheduledTime: result.data.scheduledTime,
        maxRetryCount: result.data.maxRetryCount,
        sendMethods: result.data.sendMethods ?? ['system'],
        targets: result.data.targets || []
      };
      createDialogVisible.value = true;
    } else {
      ElMessage.error(result.message || '加载失败');
    }
  } catch (error) {
    console.error('加载消息详情失败:', error);
    ElMessage.error('加载失败');
  }
}

/** 保存草稿 */
async function handleSaveDraft() {
  const valid = await messageAddRef.value?.validate();
  if (!valid) return;

  const formData = messageAddRef.value?.getFormData();
  if (!formData) return;

  const draftData = { ...formData, status: 'draft' };

  try {
    // 如果 currentMessage 有 messageID，说明是编辑模式，需要带上 messageID
    if (isEdit.value && currentMessage.value.messageID) {
      draftData.messageID = currentMessage.value.messageID;
    }

    // 根据是否有 messageID 判断是创建还是更新
    const result = draftData.messageID
      ? await messageApi.updateMessage(draftData)
      : await messageApi.createMessage(draftData);

    if (result.success) {
      ElMessage.success('保存成功');
      createDialogVisible.value = false;
      loadMessages();
    } else {
      ElMessage.error(result.message || '保存失败');
    }
  } catch (error) {
    console.error('保存草稿失败:', error);
    ElMessage.error('保存失败');
  }
}

/** 提交（创建并发送或更新） */
async function handleSubmit() {
  const valid = await messageAddRef.value?.validate();
  if (!valid) return;

  const formData = messageAddRef.value?.getFormData();
  if (!formData) return;

  try {
    // 如果 currentMessage 有 messageID，说明是编辑模式，需要带上 messageID
    if (isEdit.value && currentMessage.value.messageID) {
      formData.messageID = currentMessage.value.messageID;
    }

    // 根据是否有 messageID 判断是创建还是更新
    const result = formData.messageID
      ? await messageApi.updateMessage(formData)
      : await messageApi.createMessage(formData);

    if (result.success) {
      ElMessage.success(formData.messageID ? '更新成功' : '创建成功');
      createDialogVisible.value = false;
      loadMessages();
    } else {
      ElMessage.error(result.message || (formData.messageID ? '更新失败' : '创建失败'));
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('操作失败');
  }
}

/** 查看详情 */
async function handleViewDetail(row: MessageVO) {
  try {
    const result = await messageApi.getMessage(row.messageID!);
    if (result.success && result.data) {
      currentDetail.value = result.data;
      detailDialogVisible.value = true;
    } else {
      ElMessage.error(result.message || '加载失败');
    }
  } catch (error) {
    console.error('加载消息详情失败:', error);
    ElMessage.error('加载失败');
  }
}

/** 立即发送 */
async function handleSend(row: MessageVO) {
  try {
    await ElMessageBox.confirm('确定要立即发送该消息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const result = await messageApi.sendMessage(row.messageID!);
    if (result.success) {
      ElMessage.success('发送成功');
      loadMessages();
    } else {
      ElMessage.error(result.message || '发送失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('发送失败:', error);
      ElMessage.error('发送失败');
    }
  }
}

/** 重试 */
async function handleRetry(row: MessageVO) {
  try {
    await ElMessageBox.confirm('确定要重试发送该消息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const result = await messageApi.retryMessage(row.messageID!);
    if (result.success) {
      ElMessage.success('已提交重试');
      loadMessages();
    } else {
      ElMessage.error(result.message || '重试失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('重试失败:', error);
      ElMessage.error('重试失败');
    }
  }
}

/** 改期 */
function handleReschedule(row: MessageVO) {
  currentRescheduleId.value = row.messageID!;
  newScheduledTime.value = row.scheduledTime || '';
  rescheduleDialogVisible.value = true;
}

/** 确认改期 */
async function confirmReschedule() {
  if (!newScheduledTime.value) {
    ElMessage.warning('请选择新的发送时间');
    return;
  }

  try {
    const result = await messageApi.rescheduleMessage(
      currentRescheduleId.value,
      newScheduledTime.value
    );

    if (result.success) {
      ElMessage.success('改期成功');
      rescheduleDialogVisible.value = false;
      loadMessages();
    } else {
      ElMessage.error(result.message || '改期失败');
    }
  } catch (error) {
    console.error('改期失败:', error);
    ElMessage.error('改期失败');
  }
}

/** 取消 */
async function handleCancel(row: MessageVO) {
  try {
    await ElMessageBox.confirm('确定要取消该消息发送吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const result = await messageApi.cancelMessage(row.messageID!);
    if (result.success) {
      ElMessage.success('已取消');
      loadMessages();
    } else {
      ElMessage.error(result.message || '取消失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('取消失败:', error);
      ElMessage.error('取消失败');
    }
  }
}

/** 删除 */
async function handleDelete(row: MessageVO) {
  try {
    await ElMessageBox.confirm('确定要删除该消息吗？删除后无法恢复！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    });

    const result = await messageApi.deleteMessage(row.messageID!);
    if (result.success) {
      ElMessage.success('删除成功');
      loadMessages();
    } else {
      ElMessage.error(result.message || '删除失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
}

/** 禁用过去日期 */
function disablePastDate(time: Date): boolean {
  return time.getTime() < Date.now();
}

/** 获取消息类型标签 */
function getMessageTypeTag(type: string): string {
  const map: Record<string, string> = {
    notice: '',
    announcement: 'success',
    warning: 'warning',
    system: 'info'
  };
  return map[type] || '';
}

/** 获取消息类型文本 */
function getMessageTypeLabel(type: string): string {
  const map: Record<string, string> = {
    notice: '通知',
    announcement: '公告',
    warning: '警告',
    system: '系统消息'
  };
  return map[type] || type;
}

/** 获取发送方式文本 */
function getSendMethodLabel(method: string): string {
  const map: Record<string, string> = {
    system: '系统消息',
    email: '邮件通知',
    sms: '短信通知'
  };
  return map[method] || method;
}

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

<style lang="scss" scoped>
.message-manage-view {
  padding: 20px;

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

  .detail-content {
    max-height: 600px;
    overflow-y: auto;
  }
}
</style>
