<template>
  <div class="maintenance-management">
    <el-page-header @back="$router.back()" title="返回" content="维修管理" />

    <el-card style="margin-top: 20px">
      <!-- 操作栏 -->
      <div class="toolbar">
        <div class="toolbar-actions">
          <el-button type="primary" :icon="Plus" @click="handleCreate">
            新建维修记录
          </el-button>
        </div>

        <div class="filter-section">
          <el-select
            v-model="filters.status"
            placeholder="状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待维修" value="pending" />
            <el-option label="维修中" value="repairing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>

          <el-select
            v-model="filters.priority"
            placeholder="优先级"
            clearable
            style="width: 150px"
          >
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
          </el-select>

          <el-input
            v-model="filters.keyword"
            placeholder="搜索资产名称/编码"
            clearable
            style="width: 250px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-button type="primary" @click="handleSearch">
            搜索
          </el-button>
          <el-button @click="handleReset">
            重置
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="margin-top: 16px"
      >
        <el-table-column prop="recordCode" label="记录编号" width="150" />
        <el-table-column prop="asset.assetCode" label="资产编码" width="150" />
        <el-table-column prop="asset.assetName" label="资产名称" min-width="150" />
        <el-table-column prop="faultType" label="故障类型" width="100">
          <template #default="{ row }">
            {{ getFaultTypeName(row.faultType) }}
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)">
              {{ getPriorityName(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="faultDescription" label="故障描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">
              查看
            </el-button>
            <el-button
              v-if="row.status === 'pending'"
              link
              type="primary"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.status === 'pending'"
              link
              type="success"
              @click="handleStart(row)"
            >
              开始维修
            </el-button>
            <el-button
              v-if="row.status === 'repairing'"
              link
              type="success"
              @click="handleComplete(row)"
            >
              完成维修
            </el-button>
            <el-button
              v-if="['pending', 'repairing'].includes(row.status)"
              link
              type="danger"
              @click="handleCancel(row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 维修记录对话框 -->
    <MaintenanceDialog
      v-model="dialogVisible"
      :record-id="selectedRecordId"
      @success="handleSaveSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { getMaintenanceRecords } from '@/api'
import { usePagination } from '@/composables/usePagination'
import { FAULT_TYPE, MAINTENANCE_PRIORITY } from '@/utils/constants'
import MaintenanceDialog from './components/MaintenanceDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const { pagination, resetPage, setTotal } = usePagination()

const filters = reactive({
  status: undefined,
  priority: undefined,
  keyword: ''
})

const loading = ref(false)
const tableData = ref<any[]>([])
const dialogVisible = ref(false)
const selectedRecordId = ref<number | null>(null)

// 获取维修记录列表
const fetchMaintenanceList = async () => {
  loading.value = true
  try {
    const data = await getMaintenanceRecords({
      page: pagination.page,
      page_size: pagination.pageSize,
      ...filters
    })
    tableData.value = data.items
    setTotal(data.total)
  } catch (error) {
    ElMessage.error('获取维修记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  resetPage()
  fetchMaintenanceList()
}

// 重置
const handleReset = () => {
  Object.assign(filters, {
    status: undefined,
    priority: undefined,
    keyword: ''
  })
  handleSearch()
}

// 分页变化
const handlePageChange = () => {
  fetchMaintenanceList()
}

// 新建
const handleCreate = () => {
  selectedRecordId.value = null
  dialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  selectedRecordId.value = row.id
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  selectedRecordId.value = row.id
  dialogVisible.value = true
}

// 开始维修
const handleStart = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定开始维修吗？', '提示', {
      type: 'warning'
    })

    // TODO: 调用API
    ElMessage.success('已开始维修')
    fetchMaintenanceList()
  } catch (error) {
    // 用户取消
  }
}

// 完成维修
const handleComplete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定完成维修吗？', '提示', {
      type: 'success'
    })

    // TODO: 调用API
    ElMessage.success('维修已完成')
    fetchMaintenanceList()
  } catch (error) {
    // 用户取消
  }
}

// 取消
const handleCancel = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定取消维修吗？', '提示', {
      type: 'warning'
    })

    // TODO: 调用API
    ElMessage.success('已取消维修')
    fetchMaintenanceList()
  } catch (error) {
    // 用户取消
  }
}

// 保存成功
const handleSaveSuccess = () => {
  fetchMaintenanceList()
}

// 获取故障类型名称
const getFaultTypeName = (type: string) => {
  const item = Object.values(FAULT_TYPE).find(item => item.value === type)
  return item?.label || type
}

// 获取优先级标签类型
const getPriorityType = (priority: string) => {
  const item = Object.values(MAINTENANCE_PRIORITY).find(item => item.value === priority)
  return item?.type || ''
}

// 获取优先级名称
const getPriorityName = (priority: string) => {
  const item = Object.values(MAINTENANCE_PRIORITY).find(item => item.value === priority)
  return item?.label || priority
}

// 获取状态标签类型
const getStatusType = (status: string) => {
  const map: Record<string, string> = {
    pending: 'info',
    repairing: 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return map[status] || ''
}

// 获取状态名称
const getStatusName = (status: string) => {
  const map: Record<string, string> = {
    pending: '待维修',
    repairing: '维修中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}

onMounted(() => {
  fetchMaintenanceList()
})
</script>

<style scoped lang="scss">
.maintenance-management {
  .toolbar {
    .toolbar-actions {
      margin-bottom: 16px;
    }

    .filter-section {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }
}
</style>
