<script setup>
import { ref, onMounted } from 'vue'
import {
  questionQueryService,
  replyQueryService,
  questionSubmitService
} from '@/api/question'
import { typeNameService } from '@/api/type'
import { useUserStore } from '@/stores'
import BaseLayout from '@/components/BaseLayout.vue'
const userStore = useUserStore()
const loading = ref(false)
const list = ref([])
const total = ref(0)
const params = ref({
  current: 1,
  size: 10,
  // 0：未处理；1：已处理；2：全部
  status: 2,
  userId: 1
})
// 用户信息
const userInfo = ref({})
// 场馆列表
const typeList = ref([])
const queryTypes = async () => {
  const {
    data: { data }
  } = await typeNameService()
  typeList.value = data
}
// 获取问题列表
const fetchQuestions = async () => {
  try {
    loading.value = true
    const {
      data: { data }
    } = await questionQueryService(params.value)

    // 获取每个问题的回复（如果状态是已回复）
    const questionsWithReplies = await Promise.all(
      data.list.map(async (question) => {
        if (question.status === 1) {
          try {
            const {
              data: { data }
            } = await replyQueryService(question.id)
            return { ...question, reply: data }
          } catch (error) {
            console.error('获取回复失败:', error)
            return question
          }
        }
        return question
      })
    )

    list.value = questionsWithReplies
    total.value = data.total
  } catch (error) {
    console.error('获取问题列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 状态筛选变化
const handleStatusChange = () => {
  params.value.current = 1 // 重置页码
  fetchQuestions()
}

// 分页变化
const handlePageChange = (page) => {
  params.value.current = page
  fetchQuestions()
}

onMounted(() => {
  fetchQuestions()
  userInfo.value = { ...userStore.user }
  params.value.userId = userInfo.value.id
  queryTypes()
})

// 新增对话框相关代码
const dialogVisible = ref(false)
const questionFormRef = ref()

const questionForm = ref({
  questionType: '',
  type: '',
  description: ''
})

const rules = ref({
  questionType: [
    { required: true, message: '请选择问题类型', trigger: 'change' }
  ],
  type: [{ required: true, message: '请选择相关场地', trigger: 'change' }],
  description: [
    { required: true, message: '请输入问题描述', trigger: 'blur' },
    { min: 5, message: '问题描述不能少于5个字', trigger: 'blur' }
  ]
})

// 显示提问对话框
const showQuestionDialog = () => {
  // 重置表单
  Object.assign(questionForm.value, {
    questionType: '',
    type: '',
    description: ''
  })
  dialogVisible.value = true
}

// 提交提问
const submitQuestion = async () => {
  await questionFormRef.value.validate()

  const loadingInstance = ElLoading.service({
    lock: true,
    text: '提交中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    // 显示加载消息（0表示不自动关闭）

    // await new Promise((resolve) => setTimeout(resolve, 2000))
    // 手动关闭（通常在请求完成后）
    const formData = {
      ...questionForm.value,
      userId: userInfo.value.id,
      username: userInfo.value.username,
      phone: userInfo.value.userPhone
    }
    await questionSubmitService(formData)
    loadingInstance.close()
    ElMessage.success('提问提交成功')
    dialogVisible.value = false
    // 重新加载问题列表
    params.value.current = 1
    fetchQuestions()
  } catch (error) {
    loadingInstance.close()
    if (error !== 'validate') {
      ElMessage.error('提问提交失败: ' + (error.message || error))
    }
  }
}
</script>
<template>
  <BaseLayout>
    <div class="question-page">
      <!-- 标题和筛选区域 -->
      <div class="header">
        <h2>我的提问</h2>
        <div class="filter">
          <el-radio-group v-model="params.status" @change="handleStatusChange">
            <el-radio-button :label="2">全部</el-radio-button>
            <el-radio-button :label="0">未回复</el-radio-button>
            <el-radio-button :label="1">已回复</el-radio-button>
          </el-radio-group>
        </div>
        <el-button type="primary" @click="showQuestionDialog"
          >发起提问</el-button
        >
      </div>
      <!-- 发起提问对话框 -->
      <el-dialog
        v-model="dialogVisible"
        title="发起提问"
        width="600px"
        @closed="questionFormRef.clearValidate()"
      >
        <el-form
          :model="questionForm"
          :rules="rules"
          ref="questionFormRef"
          label-width="100px"
        >
          <el-form-item label="问题类型" prop="questionType">
            <el-select
              v-model="questionForm.questionType"
              placeholder="请选择问题类型"
            >
              <el-option label="疑问" value="疑问"></el-option>
              <el-option label="建议" value="建议"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="相关场地" prop="type">
            <el-select v-model="questionForm.type" placeholder="请选择相关场地">
              <div v-for="(item, index) in typeList" :key="index">
                <el-option :label="item.vname" :value="item.vname"></el-option>
              </div>
            </el-select>
          </el-form-item>
          <el-form-item label="问题描述" prop="description">
            <el-input
              v-model="questionForm.description"
              type="textarea"
              :rows="5"
              placeholder="请详细描述您的问题或建议"
              maxlength="500"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitQuestion">提交</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 问题列表 -->
      <div class="question-list">
        <div v-if="loading" class="loading">加载中...</div>
        <div v-else-if="list.length === 0" class="empty">暂无提问记录</div>

        <div v-else v-for="item in list" :key="item.id" class="question-item">
          <div class="question-header">
            <span class="type">{{ item.questionType }} - {{ item.type }}</span>
            <span class="status" :class="{ answered: item.status === 1 }">
              {{ item.status === 1 ? '已回复' : '未回复' }}
            </span>
          </div>

          <!-- 提问内容 -->
          <div class="question-content">
            <div class="question-title">我的提问：</div>
            <p>{{ item.description }}</p>
            <div class="question-time">提问时间：{{ item.createdTime }}</div>
          </div>

          <!-- 回复内容 -->
          <div class="reply-content" v-if="item.status === 1 && item.reply">
            <div class="reply-title">管理员回复：</div>
            <p>{{ item.reply.content }}</p>
            <div class="reply-time">回复时间：{{ item.reply.updatedTime }}</div>
          </div>

          <div class="no-reply" v-else-if="item.status === 0">
            <p>还未回复消息哦~</p>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="params.current"
          :page-size="params.size"
          :total="total"
          layout="prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </BaseLayout>
</template>
<style scoped>
.question-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

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

.question-list {
  margin-bottom: 20px;
}

.question-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.question-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.type {
  color: #666;
}

.status {
  color: #f56c6c;
  font-weight: bold;
}

.status.answered {
  color: #67c23a;
}

.question-content,
.reply-content {
  margin-bottom: 15px;
  line-height: 1.5;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.question-title,
.reply-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.question-time,
.reply-time {
  font-size: 12px;
  color: #999;
  text-align: right;
  margin-top: 5px;
}

.reply-content {
  background-color: #f0f9eb;
  border-left: 3px solid #67c23a;
}

.no-reply {
  padding: 10px;
  color: #999;
  font-style: italic;
  text-align: center;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.loading,
.empty {
  text-align: center;
  padding: 20px;
  color: #999;
}

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

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.el-select,
.el-textarea {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
