<template>
  <div class="feedback-container">
    <el-row :gutter="20">
      <el-col :span="16">
        <vab-card title="意见反馈处理">
          <vab-query-form>
            <vab-query-form-left-panel>
            <el-form :inline="true" :model="queryForm" @submit.prevent>
              <el-form-item label="类型">
                <el-select v-model="queryForm.type" placeholder="全部" clearable style="width: 120px">
                  <el-option label="投诉" value="complaint" />
                  <el-option label="建议" value="suggestion" />
                  <el-option label="咨询" value="consult" />
                </el-select>
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="queryForm.status" placeholder="全部" clearable style="width: 120px">
                  <el-option label="待处理" value="pending" />
                  <el-option label="已回复" value="replied" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleQuery"> <vab-icon icon="search-line" /> 查询</el-button>
              </el-form-item>
            </el-form>
          </vab-query-form-left-panel>
          <vab-query-form-right-panel>
            <el-button type="warning" @click="handleConfig"> <vab-icon icon="settings-3-line" /> 配置管理</el-button>
            <el-button type="success" @click="handlePublicity"> <vab-icon icon="notification-3-line" /> 信息发布</el-button>
            <el-button type="info" @click="handleExport"> <vab-icon icon="download-line" /> 导出报表</el-button>
          </vab-query-form-right-panel>
        </vab-query-form>

      <el-table v-loading="loading" :data="tableData" border stripe height="400">
            <el-table-column prop="type" label="类型" width="80">
              <template #default="{ row }">
                <el-tag :type="getTypeTag(row.type)">{{ getTypeLabel(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="content" label="反馈内容" min-width="200" show-overflow-tooltip />
            <el-table-column prop="studentName" label="反馈人" width="100" />
            <el-table-column prop="createTime" label="提交时间" width="160" sortable />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'pending' ? 'danger' : 'success'">
                  {{ row.status === 'pending' ? '待处理' : '已回复' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button v-if="row.status === 'pending'" type="primary" size="small" @click="handleDetail(row)"> <vab-icon icon="edit-line" /> 处理</el-button>
                <el-button v-else size="small" @click="handleDetail(row)"> <vab-icon icon="eye-line" /> 查看</el-button>
              </template>
            </el-table-column>
          </el-table>

          <vab-pagination
            :current-page="queryForm.pageNo"
            :page-size="queryForm.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </vab-card>
      </el-col>

      <el-col :span="8">
        <vab-card title="AI智能管家" class="ai-card">
          <div class="chat-window">
            <div class="chat-messages" ref="chatRef">
              <div v-for="(msg, index) in chatMessages" :key="index" class="message" :class="msg.role">
                <el-avatar v-if="msg.role === 'ai'" :size="30" src="https://api.dicebear.com/7.x/bottts/svg?seed=AI" class="avatar" />
                <div class="content">
                  <div class="bubble">{{ msg.content }}</div>
                  <div class="time">{{ msg.time }}</div>
                </div>
                <el-avatar v-if="msg.role === 'user'" :size="30" src="https://api.dicebear.com/7.x/avataaars/svg?seed=User" class="avatar" />
              </div>
            </div>
            <div class="chat-input">
              <el-input v-model="userInput" placeholder="输入问题，AI自动回复..." @keyup.enter="handleSend">
                <template #append>
                  <el-button icon="send-plane-fill" @click="handleSend" />
                </template>
              </el-input>
            </div>
          </div>
        </vab-card>
      </el-col>
    </el-row>

    <!-- 详情/处理弹窗 -->
    <feedback-detail-dialog ref="detailDialogRef" @success="handleReplySuccess" />
    
    <!-- 配置弹窗 -->
    <feedback-config-dialog ref="configDialogRef" />

    <!-- 公示弹窗 -->
    <publicity-dialog ref="publicityDialogRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import FeedbackDetailDialog from './components/FeedbackDetailDialog.vue'
import FeedbackConfigDialog from './components/FeedbackConfigDialog.vue'
import PublicityDialog from './components/PublicityDialog.vue'

defineOptions({
  name: 'Feedback',
})

// --- Data ---
const queryForm = reactive({
  type: '',
  status: '',
  pageNo: 1,
  pageSize: 10,
})

const loading = ref(false)
const total = ref(100)
const tableData = ref<Record<string, any>[]>([])
const detailDialogRef = ref()
const configDialogRef = ref()
const publicityDialogRef = ref()

// AI Chat
const chatRef = ref()
const userInput = ref('')
const chatMessages = ref([
  { role: 'ai', content: '您好，我是智慧公寓AI管家，有什么可以帮您？', time: '10:00' }
])

// --- Helpers ---
const getTypeLabel = (type: string) => {
  const map: Record<string, string> = { complaint: '投诉', suggestion: '建议', consult: '咨询' }
  return map[type] || type
}
const getTypeTag = (type: string) => {
  const map: Record<string, string> = { complaint: 'danger', suggestion: 'primary', consult: 'info' }
  return map[type]
}

// --- Methods ---
const generateMockData = () => {
  return [
    {
      id: 1,
      type: 'complaint',
      content: '北区食堂晚间噪音太大，影响休息',
      studentName: '梁健',
      createTime: '2026-01-24 09:30:00',
      status: 'pending'
    },
    {
      id: 2,
      type: 'suggestion',
      content: '建议增加自习室的插座数量',
      studentName: '鲁永波',
      createTime: '2026-01-23 14:20:00',
      status: 'replied',
      reply: '感谢您的建议，我们将尽快安排电工进行增设。'
    },
    {
      id: 3,
      type: 'consult',
      content: '请问寒假留校申请截止时间是什么时候？',
      studentName: '王应哲',
      createTime: '2026-01-22 10:00:00',
      status: 'replied',
      reply: '同学你好，截止时间为1月30日。'
    }
  ]
}

const handleQuery = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = generateMockData()
    loading.value = false
  }, 500)
}

const handleReplySuccess = (updatedFeedback: Record<string, any>) => {
  const item = tableData.value.find(i => i.id === updatedFeedback.id)
  if (item) {
    if (updatedFeedback.status === 'replied') {
      item.status = 'replied'
      item.reply = updatedFeedback.reply
    } else if (updatedFeedback.status === 'transferred') {
      // For transfer, we might just remove it or keep as pending but with note
      // Here just mock keep pending
      ElMessage.info('流转操作已记录')
    }
  }
}

const handleDetail = (row: Record<string, any>) => {
  detailDialogRef.value.open(row)
}

const handleConfig = () => {
  configDialogRef.value.open()
}

const handlePublicity = () => {
  publicityDialogRef.value.open()
}

const handleExport = () => {
  ElMessage.success('报表导出中...')
}

// AI Chat Logic
const handleSend = () => {
  if (!userInput.value.trim()) return
  
  // User msg
  chatMessages.value.push({
    role: 'user',
    content: userInput.value,
    time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
  })
  
  const question = userInput.value
  userInput.value = ''
  
  // Scroll to bottom
  nextTick(() => {
    if (chatRef.value) chatRef.value.scrollTop = chatRef.value.scrollHeight
  })

  // AI Response Mock
  setTimeout(() => {
    let answer = '这个问题我还在学习中，建议您咨询人工客服。'
    if (question.includes('水电')) answer = '您可以在“智能设备管理-电表管理”中查看余额和充值。'
    else if (question.includes('报修')) answer = '请前往“运维服务中心-在线报修”提交工单。'
    else if (question.includes('门禁')) answer = '门禁权限通常在入住办理完成后自动下发，如有问题请联系宿管。'
    else if (question.includes('退宿')) answer = '退宿请在“住宿管理-退宿审批”中发起申请，需完成物品核验和费用结算。'

    chatMessages.value.push({
      role: 'ai',
      content: answer,
      time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    })
    
    nextTick(() => {
      if (chatRef.value) chatRef.value.scrollTop = chatRef.value.scrollHeight
    })
  }, 1000)
}

const handleCurrentChange = (val: number) => {
  queryForm.pageNo = val
  handleQuery()
}
const handleSizeChange = (val: number) => {
  queryForm.pageSize = val
  handleQuery()
}

handleQuery()
</script>

<style lang="scss" scoped>
.feedback-container {
  .mb-20 { margin-bottom: 20px; }

  .ai-card {
    height: 600px;
    :deep(.el-card__body) { padding: 0; height: 100%; }

    .chat-window {
      display: flex;
      flex-direction: column;
      height: 100%;

      .chat-messages {
        flex: 1;
        padding: 20px;
        overflow-y: auto;
        background: #f5f7fa;

        .message {
          display: flex;
          margin-bottom: 15px;
          
          &.ai { justify-content: flex-start; }
          &.user { justify-content: flex-end; }

          .avatar { margin: 0 10px; flex-shrink: 0; }
          
          .content {
            max-width: 70%;
            .bubble {
              padding: 10px 15px;
              border-radius: 8px;
              font-size: 14px;
              line-height: 1.4;
              position: relative;
            }
            .time { font-size: 12px; color: #999; margin-top: 5px; text-align: center; }
          }

          &.ai .bubble { background: #fff; color: #333; border-top-left-radius: 0; }
          &.user .bubble { background: #95d475; color: #333; border-top-right-radius: 0; }
        }
      }

      .chat-input {
        padding: 15px;
        background: #fff;
        border-top: 1px solid #eee;
      }
    }
  }
}
</style>
