<template>
  <div class="repair-list-container">
    <!-- 顶部状态统计 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :span="6" v-for="(stat, index) in statusStats" :key="index">
        <vab-card shadow="hover" class="stat-card" :class="{ active: currentTab === stat.key }" @click="currentTab = stat.key">
          <div class="stat-content">
            <div class="stat-value" :class="stat.color">{{ stat.count }}</div>
            <div class="stat-label">{{ stat.label }}</div>
          </div>
          <div class="stat-icon" :class="`bg-${stat.type}`">
            <vab-icon :icon="stat.icon" />
          </div>
        </vab-card>
      </el-col>
    </el-row>

    <vab-card>
      <vab-query-form>
        <vab-query-form-left-panel>
          <el-form :inline="true" :model="queryForm" @submit.prevent>
            <el-form-item label="报修单号">
              <el-input v-model="queryForm.keyword" placeholder="单号/报修人" clearable />
            </el-form-item>
            <el-form-item label="报修类型">
              <el-select v-model="queryForm.type" placeholder="全部" clearable style="width: 150px">
                <el-option label="水电维修" value="water_electric" />
                <el-option label="家具维修" value="furniture" />
                <el-option label="门窗维修" value="door_window" />
                <el-option label="空调维修" value="ac" />
                <el-option label="网络故障" value="network" />
              </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="primary" @click="handleAdd"> <vab-icon icon="add-line" /> 代客报修</el-button>
          <el-button @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>
        <el-table-column prop="orderNo" label="报修单号" width="180" fixed />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getRepairType(row.type).tag">{{ getRepairType(row.type).label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="报修内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="location" label="报修地点" width="180" />
        <el-table-column prop="reporter" label="报修人" width="150">
          <template #default="{ row }">
            <div>{{ row.reporter }}</div>
            <div class="text-xs text-gray">{{ row.phone }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="提交时间" width="160" sortable />
        <el-table-column prop="status" label="当前状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.status === 'pending'" type="primary" size="small" @click="handleDispatch(row)"> <vab-icon icon="time-line" /> 派单</el-button>
            <el-button v-if="row.status === 'processing'" type="success" size="small" @click="handleComplete(row)"> <vab-icon icon="checkbox-circle-line" /> 完工</el-button>
            <el-button size="small" @click="handleDetail(row)"> <vab-icon icon="info-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>

    <!-- 派单弹窗 -->
    <repair-dispatch-dialog ref="repairDispatchDialogRef" @success="handleDispatchSuccess" />

    <!-- 详情弹窗 -->
    <repair-detail-drawer ref="repairDetailDrawerRef" />
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import RepairDispatchDialog from './components/RepairDispatchDialog.vue'
import RepairDetailDrawer from './components/RepairDetailDrawer.vue'

defineOptions({
  name: 'RepairList',
})

// --- Data ---
const currentTab = ref('all')
const queryForm = reactive({
  keyword: '',
  type: '',
  pageNo: 1,
  pageSize: 10,
})

const statusStats = [
  { key: 'all', label: '全部工单', count: 156, color: 'text-primary', type: 'primary', icon: 'file-list-line' },
  { key: 'pending', label: '待派单', count: 12, color: 'text-danger', type: 'danger', icon: 'time-line' },
  { key: 'processing', label: '维修中', count: 8, color: 'text-warning', type: 'warning', icon: 'hammer-line' },
  { key: 'completed', label: '已完工', count: 136, color: 'text-success', type: 'success', icon: 'checkbox-circle-line' },
]

const loading = ref(false)
const total = ref(100)
const tableData = ref([])
const repairDispatchDialogRef = ref()
const repairDetailDrawerRef = ref()

// --- Mock Data ---
const generateMockData = () => {
  return [
    {
      orderNo: 'RX20260123001',
      type: 'water_electric',
      content: '洗手台水龙头漏水严重，无法拧紧',
      location: '一号书院 302-1',
      reporter: '梁健',
      phone: '13800138001',
      createTime: '2026-01-23 09:30:00',
      status: 'pending',
      images: ['https://picsum.photos/200/200?random=1', 'https://picsum.photos/200/200?random=2']
    },
    {
      orderNo: 'RX20260123002',
      type: 'ac',
      content: '空调制热效果差，有异响',
      location: '三号书院 501-2',
      reporter: '鲁永波',
      phone: '13800138002',
      createTime: '2026-01-23 08:15:00',
      status: 'processing',
      dispatchTime: '2026-01-23 08:30:00',
      worker: { name: '王师傅', role: '综合维修工', phone: '15011112222' },
      images: ['https://picsum.photos/200/200?random=3']
    },
    {
      orderNo: 'RX20260122005',
      type: 'door_window',
      content: '阳台门锁坏了，打不开',
      location: '二号书院 105-1',
      reporter: '王应哲',
      phone: '13800138003',
      createTime: '2026-01-22 14:00:00',
      status: 'completed',
      dispatchTime: '2026-01-22 14:10:00',
      completeTime: '2026-01-22 15:30:00',
      worker: { name: '李师傅', role: '木工', phone: '15033334444' },
      images: ['https://picsum.photos/200/200?random=4'],
      evaluate: { score: 5, comment: '师傅上门很快，维修技术好，态度也很好！' }
    }
  ]
}

// --- Helpers ---
const getRepairType = (type) => {
  const map = {
    water_electric: { label: '水电维修', tag: '' },
    furniture: { label: '家具维修', tag: 'info' },
    door_window: { label: '门窗维修', tag: 'warning' },
    ac: { label: '空调维修', tag: 'danger' },
    network: { label: '网络故障', tag: 'success' },
  }
  return map[type] || { label: '其他', tag: 'info' }
}

const getStatusType = (status) => {
  const map = { pending: 'danger', processing: 'warning', completed: 'success', cancelled: 'info' }
  return map[status]
}

const getStatusLabel = (status) => {
  const map = { pending: '待派单', processing: '维修中', completed: '已完工', cancelled: '已取消' }
  return map[status]
}

const getStepActive = (status) => {
  const map = { pending: 1, processing: 2, completed: 5 } // 简化步骤映射
  return map[status] || 0
}

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

const handleAdd = () => {
  ElMessage.info('代客报修功能待开发')
}

const handleDispatch = (row) => {
  repairDispatchDialogRef.value.open({ ...row, typeLabel: getRepairType(row.type).label })
}

const handleDispatchSuccess = (updatedOrder) => {
  const item = tableData.value.find(i => i.orderNo === updatedOrder.orderNo)
  if (item) {
    item.status = 'processing'
    item.worker = { name: '张师傅', role: '水电工', phone: '13812345678' } // Mock update
  }
}

const handleComplete = (row) => {
  ElMessage.confirm('确认该工单已完成维修吗？', '完工确认').then(() => {
    row.status = 'completed'
    row.completeTime = new Date().toLocaleString()
    ElMessage.success('工单已完工')
  })
}

const handleDetail = (row) => {
  repairDetailDrawerRef.value.open(row)
}

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

// Lifecycle
handleQuery()
</script>

<style lang="scss" scoped>
.repair-list-container {
  .mb-20 { margin-bottom: 20px; }
  .text-xs { font-size: 12px; }
  .text-gray { color: #909399; }
  .text-danger { color: var(--el-color-danger); }
  .text-primary { color: var(--el-color-primary); }
  .text-success { color: var(--el-color-success); }
  .text-warning { color: var(--el-color-warning); }

  .stat-card {
    cursor: pointer;
    transition: all 0.3s;
    
    :deep(.el-card__body) {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
    }

    &.active {
      border-color: var(--el-color-primary);
      background-color: var(--el-color-primary-light-9);
    }

    .stat-content {
      .stat-value { font-size: 28px; font-weight: bold; line-height: 1.2; }
      .stat-label { font-size: 14px; color: #606266; margin-top: 5px; }
    }

    .stat-icon {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      color: #fff;
      
      &.bg-primary { background: var(--el-color-primary); }
      &.bg-danger { background: var(--el-color-danger); }
      &.bg-warning { background: var(--el-color-warning); }
      &.bg-success { background: var(--el-color-success); }
    }
  }

  .detail-content {
    padding: 20px;

    .section-title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 15px;
      border-left: 4px solid var(--el-color-primary);
      padding-left: 10px;
    }

    .image-list {
      display: flex;
      gap: 10px;
      .repair-image {
        width: 100px;
        height: 100px;
        border-radius: 4px;
        cursor: pointer;
      }
    }

    .worker-card {
      display: flex;
      align-items: center;
      background: #f5f7fa;
      padding: 15px;
      border-radius: 8px;

      .worker-icon {
        font-size: 40px;
        color: #909399;
        margin-right: 15px;
      }

      .info {
        flex: 1;
        .name { font-size: 16px; font-weight: bold; }
        .role { font-size: 12px; color: #909399; }
      }

      .phone {
        font-size: 16px;
        color: var(--el-color-primary);
        font-weight: bold;
        display: flex;
        align-items: center;
        gap: 5px;
      }
    }

    .evaluate-info {
      background: #fffbf0;
      padding: 15px;
      border-radius: 8px;
      border: 1px dashed #e6a23c;
      
      .comment {
        color: #606266;
        font-style: italic;
      }
    }
  }
}
</style>