<template>
  <MyLayout>
    <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
      <el-form :inline="true" label-width="auto" @submit.stop.prevent>
        <el-form-item label="关键词">
          <el-input v-model="state.queryForm.keyWord" placeholder="设备编号、资产编号" @keyup.enter="Query" />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="state.queryForm.stDate"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="state.queryForm.edDate"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item>
          <el-button v-if="auth('api:admin:equ-airpump:get-page')" @click="Query" type="primary">
            <SvgIcon name="ele-Search" />查询
          </el-button>
          <el-button v-auth="'api:admin:equ-airpump:add'" type="primary" icon="ele-Plus" @click="onAdd"> 新增 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="my-fill mt8" shadow="never">
      <el-table
        v-loading="state.loading"
        :data="state.tableData"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="deviceNo" label="设备编号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="assetNo" label="资产编号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="model" label="设备型号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="specification" label="规格" min-width="120" show-overflow-tooltip />
        <el-table-column prop="workingSpeed" label="工作泵速(g/min)" width="110" align="center" />
        <el-table-column prop="principalId" label="负责人" width="120" align="center">
          <template #default="{ row }">
            <span>{{ getPrincipalName(row.principalId) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="maintenanceFlag" label="维护状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getMaintenanceStatusType(row.maintenanceFlag)">
              {{ getMaintenanceStatusText(row.maintenanceFlag) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="onEdit(row)"
              v-auth="'api:admin:equ-airpump:update'"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="onDelete(row)"
              v-auth="'api:admin:equ-airpump:soft-delete'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="my-flex my-flex-end" style="margin-top: 10px">
        <el-pagination
          v-model:currentPage="state.queryForm.currentPage"
          v-model:page-size="state.queryForm.pageSize"
          :total="state.total"
          :page-sizes="[10, 20, 50, 100]"
          size="small"
          background
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <pump-form ref="pumpFormRef" :title="state.title" @refresh="Query"></pump-form>
  </MyLayout>
</template>

<script lang="ts" setup name="admin/airpump">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent } from 'vue'
import { ElMessageBox } from 'element-plus'
import { PumpApi } from '/@/api/admin/PumpApi'
import { UserApi } from '/@/api/admin/User'
import { PumpGetPageOutput, PageInputPumpGetPageInput, UserGetPageOutput, PageInputUserGetPageInput } from '/@/api/admin/data-contracts'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'

// 引入组件
const PumpForm = defineAsyncComponent(() => import('./components/pump-form.vue'))

// 定义变量内容
const pumpFormRef = ref()
const { proxy } = getCurrentInstance() as any

const state = reactive({
  loading: false,
  title: '',
  filter: {
    keyWord: '',
    stDate: '',
    edDate: '',
  },
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
  } as PageInputPumpGetPageInput,
  queryForm: {
    keyWord: '',
    stDate: '',
    edDate: '',
    currentPage: 1,
    pageSize: 20,
  },
  tableData: [] as Array<PumpGetPageOutput>,
  userOptions: [] as Array<UserGetPageOutput>,
  showQuery: true,
  showPumpList: true,
})

onMounted(() => {
  getUserOptions()
  Query()
  eventBus.off('refreshAirPump' as keyof MittType<any>)
  eventBus.on('refreshAirPump' as keyof MittType<any>, () => {
    Query()
  })
})
onBeforeMount(() => {
  eventBus.off('refreshAirPump' as keyof MittType<any>)
})

// 获取用户选项
const getUserOptions = async () => {
  try {
    const userPageInput = {
      currentPage: 1,
      pageSize: 1000,
      filter: {
        orgId: null,
      }
    } as PageInputUserGetPageInput

    const res = await new UserApi().getPage(userPageInput)
    if (res?.success) {
      state.userOptions = res.data?.list ?? []
    }
  } catch (error) {
    // 静默处理错误
  }
}

// 获取负责人姓名
const getPrincipalName = (principalId?: number) => {
  if (!principalId) return '-'
  const user = state.userOptions.find(u => u.id === principalId)
  return user ? `${user.name} (${user.userName})` : '-'
}

// 获取维护状态文本
const getMaintenanceStatusText = (status?: number) => {
  switch (status) {
    case 0:
      return 'Offline'
    case 1:
      return 'Idle'
    case 2:
      return 'Busy'
    case 3:
      return 'Error'
    default:
      return '未知'
  }
}

// 获取维护状态标签类型
const getMaintenanceStatusType = (status?: number) => {
  switch (status) {
    case 0:
      return 'info'
    case 1:
      return 'success'
    case 2:
      return 'warning'
    case 3:
      return 'danger'
    default:
      return ''
  }
}

// 查询
const Query = async () => {
  state.loading = true
  try {
    const queryParams = {
      currentPage: state.queryForm.currentPage,
      pageSize: state.queryForm.pageSize,
      filter: {
        keyWord: state.queryForm.keyWord || null,
        stDate: state.queryForm.stDate || null,
        edDate: state.queryForm.edDate || null,
        isAirPump: true, // 固定为false，只查询空气泵
      }
    } as PageInputPumpGetPageInput

    const res = await new PumpApi().getPage(queryParams)
    if (res?.success) {
      state.tableData = res.data?.list ?? []
      state.total = res.data?.total ?? 0
    }
  } catch (error: any) {
    proxy.$modal.msgError(`查询失败: ${error.response?.data?.msg || error.message}`)
  } finally {
    state.loading = false
  }
}

// 重置查询
const onReset = () => {
  state.queryForm = {
    keyWord: '',
    stDate: '',
    edDate: '',
    currentPage: 1,
    pageSize: 20,
  }
  Query()
}

// 分页大小变化
const onSizeChange = (size: number) => {
  state.queryForm.pageSize = size
  Query()
}

// 当前页变化
const onCurrentChange = (page: number) => {
  state.queryForm.currentPage = page
  Query()
}

// 新增
const onAdd = () => {
  state.title = '新增空气泵'
  pumpFormRef.value.openDialog()
}

// 编辑
const onEdit = (row: PumpGetPageOutput) => {
  state.title = '编辑空气泵'
  pumpFormRef.value.openDialog(row)
}

// 删除
const onDelete = (row: PumpGetPageOutput) => {
  ElMessageBox.confirm(`确定要删除空气泵【${row.deviceNo}】吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await new PumpApi().softDelete({ id: row.id! })
        if (res?.success) {
          proxy.$modal.msgSuccess('删除成功')
          Query()
        }
      } catch (error: any) {
        proxy.$modal.msgError(`删除失败: ${error.response?.data?.msg || error.message}`)
      }
    })
    .catch(() => {})
}
</script>


