<template>
  <div class="after-sale-container">
    <div class="page-title">
      <i class="title-bar"></i>
      <span>售后服务</span>
    </div>

    <div class="main-tabs">
      <div v-for="tab in mainTabs" :key="tab.key" :class="['tab-item', { active: activeMainTab === tab.key }]" @click="handleMainTabChange(tab.key)">
        <el-icon><component :is="tab.icon" /></el-icon>
        <span>{{ tab.label }}</span>
      </div>
    </div>

    <template v-if="activeMainTab !== 'complaint'">
      <div class="status-tabs">
        <div v-for="tab in statusTabs" :key="tab.key" :class="['status-tab', { active: activeStatusTab === tab.key }]" @click="activeStatusTab = tab.key">
          {{ tab.label }}
        </div>
      </div>

      <div class="search-bar">
        <el-input v-model="queryParams.keyword" placeholder="搜索" style="width: 150px" clearable>
          <template #prefix><el-icon><Search /></el-icon></template>
        </el-input>
        <el-date-picker v-model="queryParams.dateRange" type="daterange" range-separator="—" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px" />
      </div>

      <div class="filter-bar">
        <span class="filter-label">状态</span>
        <el-select v-model="queryParams.status" placeholder="请选择" style="width: 100px" clearable>
          <el-option label="申请中" value="applying" />
          <el-option label="已退货" value="returned" />
          <el-option label="已拒绝" value="rejected" />
          <el-option label="已完成" value="completed" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
      </div>

      <div class="table-header">
        <div class="col-product">商品信息</div>
        <div class="col-time">申请时间</div>
        <div class="col-type">服务类型</div>
        <div class="col-status">服务状态</div>
        <div class="col-action">操作</div>
      </div>

      <div class="after-sale-list">
        <div v-for="(item, index) in afterSaleList" :key="index" class="after-sale-card">
          <div class="card-header">
            <span class="service-no">服务单号：{{ item.serviceNo }}</span>
            <span class="order-no">订单号：{{ item.orderNo }}</span>
          </div>
          <div class="card-content">
            <div class="col-product">
              <div class="product-image">
                <el-image :src="item.productImage" fit="contain">
                  <template #error><div class="image-placeholder"><el-icon :size="30" color="#ccc"><Picture /></el-icon></div></template>
                </el-image>
              </div>
              <div class="product-info">
                <div class="product-name">{{ item.productName }}</div>
                <div class="product-quantity">x{{ item.quantity }}</div>
              </div>
            </div>
            <div class="col-time">{{ item.applyTime }}</div>
            <div class="col-type">{{ item.serviceType }}</div>
            <div class="col-status"><span :class="['status-text', getStatusClass(item.status)]">{{ item.statusText }}</span></div>
            <div class="col-action"><el-button type="primary" link size="small" @click="handleViewDetail(item)">查看详情</el-button></div>
          </div>
        </div>
        <el-empty v-if="afterSaleList.length === 0" description="暂无售后记录" />
      </div>
    </template>

    <template v-else>
      <div class="status-tabs">
        <div v-for="tab in complaintStatusTabs" :key="tab.key" :class="['status-tab', { active: activeStatusTab === tab.key }]" @click="activeStatusTab = tab.key">
          {{ tab.label }}
        </div>
      </div>

      <div class="search-filter-bar">
        <div class="left">
          <el-input v-model="queryParams.keyword" placeholder="搜索" style="width: 150px" clearable>
            <template #prefix><el-icon><Search /></el-icon></template>
          </el-input>
          <span class="filter-label">处理结果</span>
          <el-select v-model="queryParams.handleResult" placeholder="请选择" style="width: 100px" clearable>
            <el-option label="已处理" value="handled" />
            <el-option label="未处理" value="unhandled" />
          </el-select>
          <span class="filter-label">反馈类型</span>
          <el-select v-model="queryParams.feedbackType" placeholder="请选择" style="width: 100px" clearable>
            <el-option label="投诉" value="complaint" />
            <el-option label="建议" value="suggestion" />
          </el-select>
        </div>
        <div class="right">
          <el-button type="danger" @click="handleAddComplaint">新增投诉与建议</el-button>
        </div>
      </div>

      <el-table :data="complaintList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="submitTime" label="提交时间" min-width="150" align="center" />
        <el-table-column prop="submitter" label="提交人" min-width="100" align="center" />
        <el-table-column prop="feedbackType" label="反馈类型" min-width="100" align="center">
          <template #default="{ row }"><span>{{ row.feedbackType || '-' }}</span></template>
        </el-table-column>
        <el-table-column prop="handleTime" label="处理时间" min-width="150" align="center" />
        <el-table-column prop="handler" label="处理人员" min-width="100" align="center" />
        <el-table-column prop="handleResult" label="处理结果" min-width="100" align="center">
          <template #default="{ row }"><span :style="{ color: row.handleResult === '未处理' ? '#e60012' : '#333' }">{{ row.handleResult }}</span></template>
        </el-table-column>
        <el-table-column label="操作" min-width="120" align="center">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleEditComplaint(row)">修改</el-button>
            <el-button type="danger" link size="small" @click="handleDeleteComplaint(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="complaintList.length === 0" description="暂无投诉与建议" />
    </template>

    <el-dialog v-model="complaintDialogVisible" :title="complaintDialogTitle" width="500px">
      <el-form ref="complaintFormRef" :model="complaintForm" :rules="complaintRules" label-width="80px">
        <el-form-item label="反馈类型" prop="feedbackType">
          <el-select v-model="complaintForm.feedbackType" placeholder="请选择" style="width: 100%">
            <el-option label="投诉" value="投诉" />
            <el-option label="建议" value="建议" />
          </el-select>
        </el-form-item>
        <el-form-item label="反馈内容" prop="content">
          <el-input v-model="complaintForm.content" type="textarea" :rows="4" placeholder="请输入反馈内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="complaintDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleSubmitComplaint">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Search, RefreshRight, Tools, ChatLineSquare, Picture } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const activeMainTab = ref('return')
const activeStatusTab = ref('all')
const complaintDialogVisible = ref(false)
const complaintDialogTitle = ref('新增投诉与建议')
const complaintFormRef = ref()
const currentComplaint = ref<any>(null)

const mainTabs = [
  { key: 'return', label: '退换货', icon: RefreshRight },
  { key: 'repair', label: '返修/维修', icon: Tools },
  { key: 'complaint', label: '投诉与建议', icon: ChatLineSquare }
]

const statusTabs = [
  { key: 'all', label: '全部订单' },
  { key: 'applying', label: '申请中' },
  { key: 'returned', label: '已退货' },
  { key: 'rejected', label: '已拒绝' },
  { key: 'completed', label: '已完成' },
  { key: 'cancelled', label: '已取消' }
]

const complaintStatusTabs = [
  { key: 'all', label: '全部订单' },
  { key: 'applying', label: '申请中' },
  { key: 'returned', label: '已退货' },
  { key: 'rejected', label: '已拒绝' },
  { key: 'completed', label: '已完成' },
  { key: 'cancelled', label: '已取消' }
]

const queryParams = reactive({ keyword: '', dateRange: null, status: '', handleResult: '', feedbackType: '' })
const complaintForm = reactive({ feedbackType: '', content: '' })
const complaintRules = {
  feedbackType: [{ required: true, message: '请选择反馈类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入反馈内容', trigger: 'blur' }]
}

const allAfterSaleData = ref([
  { serviceNo: '2232323', orderNo: '489283929283298392', productImage: '', productName: '清华同方超越E500台式机电脑(i3-6100/4G/1T/19.5寸)', quantity: 1, applyTime: '2021-10-23 10:00:34', serviceType: '退货', status: 'completed', statusText: '已完成', type: 'return' },
  { serviceNo: '2232324', orderNo: '489283929283298393', productImage: '', productName: '清华同方超越E500台式机电脑(i3-6100/4G/1T/19.5寸)', quantity: 1, applyTime: '2021-10-23 10:00:34', serviceType: '退货', status: 'cancelled', statusText: '已取消', type: 'return' },
  { serviceNo: '2232325', orderNo: '489283929283298394', productImage: '', productName: '清华同方超越E500台式机电脑(i3-6100/4G/1T/19.5寸)', quantity: 1, applyTime: '2021-10-23 10:00:34', serviceType: '返修/维修', status: 'completed', statusText: '已完成', type: 'repair' },
  { serviceNo: '2232326', orderNo: '489283929283298395', productImage: '', productName: '清华同方超越E500台式机电脑(i3-6100/4G/1T/19.5寸)', quantity: 1, applyTime: '2021-10-23 10:00:34', serviceType: '返修/维修', status: 'completed', statusText: '已完成', type: 'repair' }
])

const allComplaintData = ref([
  { id: 1, submitTime: '2025-11-30 22:16', submitter: '李豫卓', feedbackType: '', handleTime: '2025-12-10 23:04', handler: '李豫卓', handleResult: '已处理' },
  { id: 2, submitTime: '2025-11-17 13:22', submitter: '冯启彬', feedbackType: '', handleTime: '2025-11-22 09:29', handler: '孙婉茹', handleResult: '未处理' },
  { id: 3, submitTime: '2025-11-30 12:23', submitter: '冯云', feedbackType: '', handleTime: '2025-11-27 07:40', handler: '冯思玖', handleResult: '已处理' },
  { id: 4, submitTime: '2025-12-07 04:15', submitter: '李世海', feedbackType: '', handleTime: '2025-11-24 13:43', handler: '郑文锦', handleResult: '已处理' },
  { id: 5, submitTime: '2025-12-10 07:02', submitter: '孙思达', feedbackType: '', handleTime: '2025-11-13 01:24', handler: '周璟', handleResult: '已处理' }
])

const afterSaleList = computed(() => {
  let list = allAfterSaleData.value.filter(item => item.type === activeMainTab.value)
  if (activeStatusTab.value !== 'all') list = list.filter(item => item.status === activeStatusTab.value)
  return list
})

const complaintList = computed(() => allComplaintData.value)

const handleMainTabChange = (key: string) => { activeMainTab.value = key; activeStatusTab.value = 'all' }
const getStatusClass = (status: string) => {
  const map: Record<string, string> = { applying: 'warning', returned: 'success', rejected: 'danger', completed: 'success', cancelled: 'info' }
  return map[status] || 'info'
}
const handleViewDetail = (item: any) => { console.log('查看详情', item) }
const handleAddComplaint = () => { currentComplaint.value = null; complaintDialogTitle.value = '新增投诉与建议'; complaintForm.feedbackType = ''; complaintForm.content = ''; complaintDialogVisible.value = true }
const handleEditComplaint = (row: any) => { currentComplaint.value = row; complaintDialogTitle.value = '修改投诉与建议'; complaintForm.feedbackType = row.feedbackType; complaintForm.content = row.content || ''; complaintDialogVisible.value = true }
const handleDeleteComplaint = (row: any) => {
  ElMessageBox.confirm('确定要删除该记录吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
    const index = allComplaintData.value.findIndex(item => item.id === row.id)
    if (index > -1) allComplaintData.value.splice(index, 1)
    ElMessage.success('删除成功')
  }).catch(() => {})
}
const handleSubmitComplaint = async () => {
  const valid = await complaintFormRef.value?.validate()
  if (!valid) return
  if (currentComplaint.value) { currentComplaint.value.feedbackType = complaintForm.feedbackType; currentComplaint.value.content = complaintForm.content; ElMessage.success('修改成功') }
  else { allComplaintData.value.unshift({ id: Date.now(), submitTime: new Date().toLocaleString(), submitter: '当前用户', feedbackType: complaintForm.feedbackType, handleTime: '', handler: '', handleResult: '未处理' }); ElMessage.success('提交成功') }
  complaintDialogVisible.value = false
}
</script>

<style scoped lang="scss">
.after-sale-container { padding: 20px; background: #fff; min-height: 100%; }
.page-title { font-size: 16px; font-weight: bold; display: flex; align-items: center; gap: 8px; margin-bottom: 20px; }
.title-bar { display: inline-block; width: 3px; height: 16px; background: #e60012; border-radius: 2px; }
.main-tabs { display: flex; gap: 30px; border-bottom: 1px solid #eee; margin-bottom: 15px;
  .tab-item { display: flex; align-items: center; gap: 5px; padding: 12px 0; cursor: pointer; color: #666; font-size: 14px; border-bottom: 2px solid transparent; margin-bottom: -1px;
    &:hover, &.active { color: #333; } &.active { border-bottom-color: #e60012; }
  }
}
.status-tabs { display: flex; gap: 10px; margin-bottom: 15px;
  .status-tab { padding: 6px 18px; border-radius: 4px; cursor: pointer; font-size: 13px; color: #666; background: #f5f5f5; transition: all 0.2s;
    &:hover { color: #e60012; } &.active { background: #e60012; color: #fff; }
  }
}
.search-bar { display: flex; align-items: center; gap: 15px; margin-bottom: 15px; }
.filter-bar { display: flex; align-items: center; gap: 10px; margin-bottom: 20px; .filter-label { font-size: 14px; color: #666; } }
.search-filter-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;
  .left { display: flex; align-items: center; gap: 10px; .filter-label { font-size: 14px; color: #666; margin-left: 10px; } }
}
.table-header { display: flex; align-items: center; padding: 12px 15px; background: #f9f9f9; border: 1px solid #eee; border-bottom: none; font-size: 13px; color: #666;
  .col-product { flex: 1; } .col-time { width: 150px; text-align: center; } .col-type { width: 100px; text-align: center; } .col-status { width: 100px; text-align: center; } .col-action { width: 100px; text-align: center; }
}
.after-sale-list {
  .after-sale-card { border: 1px solid #eee; margin-bottom: -1px;
    .card-header { display: flex; align-items: center; gap: 20px; padding: 10px 15px; background: #fafafa; border-bottom: 1px solid #eee; font-size: 13px; color: #333; }
    .card-content { display: flex; align-items: center; padding: 15px;
      .col-product { flex: 1; display: flex; align-items: center; gap: 12px;
        .product-image { width: 70px; height: 70px; background: #f5f5f5; border-radius: 4px; overflow: hidden; flex-shrink: 0;
          .el-image { width: 100%; height: 100%; } .image-placeholder { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; }
        }
        .product-info { .product-name { font-size: 13px; color: #333; line-height: 1.4; margin-bottom: 5px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } .product-quantity { font-size: 12px; color: #666; } }
      }
      .col-time { width: 150px; text-align: center; font-size: 13px; color: #666; }
      .col-type { width: 100px; text-align: center; font-size: 13px; color: #666; }
      .col-status { width: 100px; text-align: center; .status-text { font-size: 13px; &.success { color: #e60012; } &.warning { color: #e6a23c; } &.danger { color: #f56c6c; } &.info { color: #909399; } } }
      .col-action { width: 100px; text-align: center; }
    }
  }
}
</style>
