<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { questionnaireApi, customerApi } from '@/api/crm.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新建问卷')
const submitLoading = ref(false)
const detailVisible = ref(false)
const detailData = ref(null)
const customers = ref([])

const searchForm = reactive({ customer_id: '', status: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({ id: null, customer_id: '', title: '', score: 80, status: 'draft' })
const isEdit = ref(false)
const formRules = {
  customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
  title: [{ required: true, message: '请输入问卷标题', trigger: 'blur' }],
  score: [{ required: true, message: '请输入评分', trigger: 'blur' }]
}

const statusMap = { draft: '草稿', sent: '已发送', completed: '已完成' }
const statusType = { draft: 'info', sent: 'warning', completed: 'success' }

async function fetchList() {
  loading.value = true
  try {
    const res = await questionnaireApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } finally { loading.value = false }
}

async function fetchCustomers() {
  try {
    const res = await customerApi.getList({ per_page: 500 })
    customers.value = res.data?.list || res.data?.data || []
  } catch {}
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() { Object.assign(searchForm, { customer_id: '', status: '' }); handleSearch() }

function handleAdd() {
  isEdit.value = false
  dialogTitle.value = '新建问卷'
  Object.assign(form, { id: null, customer_id: '', title: '', score: 80, status: 'draft' })
  dialogVisible.value = true
}

async function handleEdit(row) {
  isEdit.value = true
  dialogTitle.value = '编辑问卷'
  const res = await questionnaireApi.getDetail(row.id)
  const d = res.data
  Object.assign(form, { id: d.id, customer_id: d.customer_id, title: d.title, score: d.score, status: d.status })
  dialogVisible.value = true
}

async function handleDetail(row) {
  const res = await questionnaireApi.getDetail(row.id)
  detailData.value = res.data
  detailVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) { await questionnaireApi.update(form.id, form); ElMessage.success('更新成功') }
      else { await questionnaireApi.create(form); ElMessage.success('创建成功') }
      dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleDelete(row) {
  await ElMessageBox.confirm(`确定删除问卷「${row.title}」吗？`, '删除确认', { type: 'warning' })
  await questionnaireApi.delete(row.id); ElMessage.success('删除成功'); fetchList()
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

onMounted(() => { fetchList(); fetchCustomers() })
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-select v-model="searchForm.customer_id" placeholder="选择客户" clearable filterable style="width:180px">
        <el-option v-for="c in customers" :key="c.id" :label="`${c.name}(${c.phone})`" :value="c.id" />
      </el-select>
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width:120px">
        <el-option v-for="(v, k) in statusMap" :key="k" :label="v" :value="k" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-2">
          <span class="w-1 h-5 bg-rose-500 rounded-full inline-block"></span>
          <span class="font-medium text-gray-700">问卷列表</span>
        </div>
        <el-button type="primary" @click="handleAdd">新建问卷</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column label="客户" min-width="110">
            <template #default="{ row }">{{ row.customer_name || row.customer?.name || '-' }}</template>
          </el-table-column>
          <el-table-column prop="title" label="问卷标题" min-width="180" show-overflow-tooltip />
          <el-table-column label="满意度评分" width="110" align="center">
            <template #default="{ row }">
              <span :class="row.score >= 80 ? 'text-green-600' : row.score >= 60 ? 'text-yellow-500' : 'text-red-500'" class="font-semibold">
                {{ row.score ?? '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="statusType[row.status]" size="small">{{ statusMap[row.status] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" text @click="handleDetail(row)">详情</el-button>
              <el-button size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.per_page"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total,sizes,prev,pager,next,jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- Add / Edit Dialog -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="560px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-form-item label="客户" prop="customer_id">
          <el-select v-model="form.customer_id" filterable placeholder="请选择客户" style="width:100%">
            <el-option v-for="c in customers" :key="c.id" :label="`${c.name}(${c.phone})`" :value="c.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="问卷标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入问卷标题" />
        </el-form-item>
        <el-form-item label="满意度评分" prop="score">
          <el-slider v-model="form.score" :min="0" :max="100" :step="1" show-input style="width:100%" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" style="width:100%">
            <el-option v-for="(v, k) in statusMap" :key="k" :label="v" :value="k" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- Detail Drawer -->
    <el-drawer v-model="detailVisible" title="问卷详情" size="480px">
      <template v-if="detailData">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="客户">{{ detailData.customer_name || detailData.customer?.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="标题" :span="2">{{ detailData.title }}</el-descriptions-item>
          <el-descriptions-item label="评分">
            <span :class="detailData.score >= 80 ? 'text-green-600 font-bold' : 'text-yellow-500 font-bold'">{{ detailData.score }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="statusType[detailData.status]" size="small">{{ statusMap[detailData.status] }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ detailData.created_at }}</el-descriptions-item>
        </el-descriptions>
      </template>
    </el-drawer>
  </div>
</template>
