<template>
  <div class="app-container ticket-detail-page">
    <div class="bg-white rounded h-full flex flex-col">
      <!-- 顶部导航 -->
      <div class="detail-header p-4 border-b flex items-center justify-between">
        <div class="flex items-center">
          <el-button link @click="handleBack">
            <el-icon><i-ep-arrow-left /></el-icon>
            返回
          </el-button>
          <span class="mx-4 text-gray-300">|</span>
          <span class="font-bold text-lg">{{ ticketInfo.userName || '南风未起' }}</span>
        </div>
        <div class="flex gap-2">
          <el-button type="success" plain @click="handleComplete">标记完成</el-button>
          <el-button type="info" plain @click="handleAbandon">废弃工单</el-button>
        </div>
      </div>

      <!-- 聊天区域 -->
      <div class="chat-container flex-1 overflow-y-auto p-6 bg-gray-50">
        <div v-for="(msg, index) in messageList" :key="index" :class="['message-row', msg.type === 'mine' ? 'mine' : 'user']">
          <div class="avatar shrink-0">
            <el-avatar :size="40" :src="msg.type === 'mine' ? myAvatar : userAvatar" />
          </div>
          <div class="message-content">
            <div class="bubble">
              {{ msg.content }}
            </div>
            <div class="time text-xs text-gray-400 mt-1">
              {{ msg.time }}
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area p-4 border-t bg-white">
        <div class="toolbar mb-2 flex gap-4">
          <el-icon class="cursor-pointer text-xl text-gray-500"><i-ep-picture /></el-icon>
          <el-icon class="cursor-pointer text-xl text-gray-500"><i-ep-folder-opened /></el-icon>
          <el-icon class="cursor-pointer text-xl text-gray-500"><i-ep-chat-dot-round /></el-icon>
        </div>
        <el-input
          v-model="inputMsg"
          type="textarea"
          :rows="4"
          placeholder="请输入回复内容..."
          resize="none"
          class="reply-input"
          @keyup.ctrl.enter="handleSend"
        />
        <div class="flex justify-end mt-2">
          <span class="text-xs text-gray-400 mr-4 self-center">Ctrl + Enter 发送</span>
          <el-button type="primary" @click="handleSend">发送</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getTicket, processTicket } from '@/api/chat/ticket';
import { parseTime } from '@/utils/ruoyi';

const route = useRoute();
const router = useRouter();

const userAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
const myAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

const ticketInfo = ref<any>({});

const inputMsg = ref('');
const messageList = ref<any>([]);

const getList = () => {
  if (!route.query.id) return;
  getTicket(route.query.id as string).then(response => {
    ticketInfo.value = response.data;
    // 构建初始消息列表（反馈内容作为第一条用户消息）
    messageList.value = [
      {
        type: 'user',
        content: response.data.content,
        time: parseTime(response.data.createTime),
      }
    ];
    // 如果已有回复，则添加回复
    if (response.data.handlerReply) {
      messageList.value.push({
        type: 'mine',
        content: response.data.handlerReply,
        time: parseTime(response.data.updateTime),
      });
    }
    scrollToBottom();
  });
};

onMounted(() => {
  getList();
});

const handleBack = () => {
  router.back();
};

const handleSend = () => {
  if (!inputMsg.value.trim()) return;
  
  const data = {
    id: ticketInfo.value.id,
    handlerReply: inputMsg.value,
    status: 'processing'
  };

  processTicket(data).then(() => {
    ElMessage.success('回复成功');
    messageList.value.push({
      type: 'mine',
      content: inputMsg.value,
      time: parseTime(new Date()),
    });
    inputMsg.value = '';
    scrollToBottom();
  });
};

const handleComplete = () => {
  ElMessageBox.confirm('确定要将该工单标记为已完成吗？', '提示').then(() => {
    processTicket({
      id: ticketInfo.value.id,
      status: 'completed'
    }).then(() => {
      ElMessage.success('工单已标记为完成');
      handleBack();
    });
  });
};

const handleAbandon = () => {
  ElMessageBox.confirm('确定要废弃该工单吗？', '提示').then(() => {
    processTicket({
      id: ticketInfo.value.id,
      status: 'abandoned'
    }).then(() => {
      ElMessage.info('工单已废弃');
      handleBack();
    });
  });
};

const scrollToBottom = () => {
  nextTick(() => {
    const container = document.querySelector('.chat-container');
    if (container) {
      container.scrollTop = container.scrollHeight;
    }
  });
};
</script>

<style scoped lang="scss">
.ticket-detail-page {
  padding: 20px;
  background-color: #f0f2f5;
  height: calc(100vh - 84px);

  .message-row {
    display: flex;
    gap: 12px;
    margin-bottom: 24px;
    max-width: 80%;

    &.user {
      .bubble {
        background-color: #fff;
        color: #333;
        border-top-left-radius: 2px;
      }
    }

    &.mine {
      margin-left: auto;
      flex-direction: row-reverse;
      .bubble {
        background-color: #e6f7ff;
        color: #1890ff;
        border-top-right-radius: 2px;
      }
      .time {
        text-align: right;
      }
    }

    .bubble {
      padding: 10px 16px;
      border-radius: 8px;
      font-size: 14px;
      line-height: 1.6;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
      word-break: break-all;
    }
  }

  .reply-input {
    :deep(.el-textarea__inner) {
      border: none;
      padding: 0;
      &:focus {
        box-shadow: none;
      }
    }
  }
}
</style>
