<template>
  <ContentWrap>
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="90px">
      <el-form-item label="报修单号" prop="repairNo">
        <el-input v-model="queryParams.repairNo" placeholder="请输入报修单号" clearable @keyup.enter="handleQuery" class="!w-200px" />
      </el-form-item>
      <el-form-item label="报修人" prop="reporter">
        <el-input v-model="queryParams.reporter" placeholder="请输入报修人" clearable class="!w-160px" />
      </el-form-item>
      <el-form-item label="设备编码" prop="deviceCode">
        <el-input v-model="queryParams.deviceCode" placeholder="请输入设备编码" clearable class="!w-160px" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-140px">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 查询</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="primary" plain @click="openForm('create')">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="报修单号" align="center" prop="repairNo" />
      <el-table-column label="报修日期" align="center" prop="reportTime">
        <template #default="scope">
          {{ formatDate(scope.row.reportTime) }}
        </template>
      </el-table-column>
      <el-table-column label="报修人" align="center" prop="reporter" />
      <el-table-column label="联系方式" align="center" prop="contact" />
      <el-table-column label="设备编码" align="center" prop="deviceCode" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="故障现象" align="center" prop="faultDesc" />
      <el-table-column label="故障发生日期" align="center" prop="faultTime">
        <template #default="scope">
          {{ formatDate(scope.row.faultTime) }}
        </template>
      </el-table-column>
      <el-table-column label="故障严重程度" align="center" prop="faultLevel">
        <template #default="scope">
          {{ faultLevelLabel(scope.row.faultLevel) }}
        </template>
      </el-table-column>
      <el-table-column label="是否影响安全" align="center" prop="affectSafety">
        <template #default="scope">
          <el-tag v-if="scope.row.affectSafety === true || scope.row.affectSafety === '是'" type="danger">是</el-tag>
          <el-tag v-else type="success">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="当前状态" align="center" prop="status">
        <template #default="scope">
          <el-tag>{{ statusLabel(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="200px">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)" style="margin-right: 8px;">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" style="margin-right: 8px;">
            删除
          </el-button>
          <el-dropdown trigger="click">
            <el-button link type="info" style="padding: 0 8px;">
              状态 <el-icon style="margin-left: 2px;"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-for="s in statusOptions"
                  :key="s.value"
                  @click="changeStatus(scope.row, s.value)"
                >
                  <el-tag :type="scope.row.status === s.value ? 'primary' : 'info'" effect="plain" style="margin-right: 8px;">
                    {{ s.label }}
                  </el-tag>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <RepairOrder ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, Ref } from 'vue'
import RepairOrder from './RepairOrder.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { RepairOrderApi } from '@/api/iot/maintain/repairOrder'
import { ArrowDown } from '@element-plus/icons-vue'

const loading = ref(false)
const list: Ref<any[]> = ref([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  repairNo: '',
  reporter: '',
  deviceCode: '',
  status: ''
})
const queryFormRef = ref()
const statusOptions = [
  { label: '待受理', value: 'pending' },
  { label: '已派工', value: 'assigned' },
  { label: '维修中', value: 'repairing' },
  { label: '待验收', value: 'to_accept' },
  { label: '已完成', value: 'finished' },
  { label: '已关闭', value: 'closed' }
]
function statusLabel(val: string) {
  const found = statusOptions.find(s => s.value === val)
  return found ? found.label : val
}

const formRef = ref()

const faultLevelMap = {
  urgent: '紧急',
  high: '高',
  medium: '中',
  low: '低'
}
function faultLevelLabel(val: string) {
  return faultLevelMap[val] || val
}

const getList = async () => {
  loading.value = true
  try {
    const res = await RepairOrderApi.getRepairOrderList(queryParams as any)
    list.value = res.list || []
    console.log(list)
    total.value = res.total || 0
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
const handleDelete = async (id: number) => {
  await ElMessageBox.confirm('确定删除该报修单吗？')
  await RepairOrderApi.deleteRepairOrder(id)
  ElMessage.success('删除成功')
  getList()
}
const changeStatus = async (row: any, status: string) => {
  await RepairOrderApi.updateRepairOrder({ ...row, status })
  ElMessage.success('状态已更新')
  getList()
}

function formatDate(ts: number) {
  if (!ts) return ''
  const date = new Date(ts)
  return date.toLocaleString()
}

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