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

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const handleVisible = ref(false)
const currentComplaint = ref(null)
const customers = ref([])

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

const formRef = ref(null)
const form = reactive({ id: null, customer_id: '', type: 1, content: '', images: [] })
const isEdit = ref(false)
const handleForm = reactive({ handle_result: '', status: 2 })

const typeMap = { 1: '服务', 2: '膳食', 3: '环境', 4: '其他' }
const statusMap = { 0: '待处理', 1: '处理中', 2: '已解决', 3: '已关闭' }
const statusType = { 0: 'danger', 1: 'warning', 2: 'success', 3: 'info' }

async function fetchList() {
  loading.value = true
  try {
    const res = await complaintApi.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: '', type: '', status: '' }); handleSearch() }
function handleAdd() { isEdit.value = false; Object.assign(form, { id: null, customer_id: '', type: 1, content: '', images: [] }); dialogVisible.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 complaintApi.update(form.id, form) } else { await complaintApi.create(form) }
      ElMessage.success('提交成功'); dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

function openHandle(row) { currentComplaint.value = row; Object.assign(handleForm, { handle_result: '', status: 2 }); handleVisible.value = true }
async function submitHandle() {
  if (!handleForm.handle_result) { ElMessage.warning('请输入处理结果'); return }
  await complaintApi.handle(currentComplaint.value.id, handleForm)
  ElMessage.success('处理完成'); handleVisible.value = false; fetchList()
}

async function handleDelete(row) {
  await ElMessageBox.confirm('确定删除该投诉吗？', '删除确认', { type: 'warning' })
  await complaintApi.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" :value="c.id" /></el-select>
      <el-select v-model="searchForm.type" placeholder="类型" clearable style="width:120px"><el-option v-for="(v,k) in typeMap" :key="k" :label="v" :value="Number(k)" /></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="Number(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-3">
          <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="100"><template #default="{ row }">{{ row.customer?.name || '-' }}</template></el-table-column>
          <el-table-column label="类型" width="80" align="center"><template #default="{ row }">{{ typeMap[row.type] }}</template></el-table-column>
          <el-table-column prop="content" label="内容" min-width="200" show-overflow-tooltip />
          <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 label="处理人" min-width="100"><template #default="{ row }">{{ row.handler?.name || '-' }}</template></el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
          <el-table-column label="操作" width="160" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.status<2" size="small" type="success" text @click="openHandle(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>
    <el-dialog v-model="dialogVisible" :title="isEdit?'编辑投诉':'新增投诉'" width="550px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="{ customer_id:[{required:true,message:'请选择客户'}], content:[{required:true,message:'请输入内容'}] }" label-width="80px">
        <el-form-item label="客户" prop="customer_id"><el-select v-model="form.customer_id" filterable style="width:100%"><el-option v-for="c in customers" :key="c.id" :label="c.name" :value="c.id" /></el-select></el-form-item>
        <el-form-item label="类型"><el-select v-model="form.type" style="width:100%"><el-option v-for="(v,k) in typeMap" :key="k" :label="v" :value="Number(k)" /></el-select></el-form-item>
        <el-form-item label="内容" prop="content"><el-input v-model="form.content" type="textarea" :rows="4" /></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>
    <el-dialog v-model="handleVisible" title="处理投诉" width="500px" destroy-on-close>
      <el-form label-width="80px">
        <el-form-item label="处理结果"><el-input v-model="handleForm.handle_result" type="textarea" :rows="4" /></el-form-item>
        <el-form-item label="状态"><el-radio-group v-model="handleForm.status"><el-radio :value="2">已解决</el-radio><el-radio :value="3">已关闭</el-radio></el-radio-group></el-form-item>
      </el-form>
      <template #footer><el-button @click="handleVisible=false">取消</el-button><el-button type="primary" @click="submitHandle">确定</el-button></template>
    </el-dialog>
  </div>
</template>
