<template>
  <div class="device-maintain-record">
    <section class="library-workbench">
      <el-form
        ref="queryFormRef"
        :model="queryParams"
        inline
        size="default"
        class="library-search-form">
        <div class="library-workbench__header">
          <div class="library-header-main">
            <div class="workbench-title">
              <span class="workbench-title__icon">
                <Icon icon="ep:tools" />
              </span>
              <div>
                <h3>维修记录</h3>
              </div>
            </div>

            <el-form-item label="故障编码" prop="failureCode">
              <el-input
                v-model="queryParams.failureCode"
                class="library-search-input"
                clearable
                placeholder="请输入故障编码"
                @keyup.enter="handleQuery">
                <template #prefix>
                  <Icon icon="ep:search" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="故障名称" prop="failureName">
              <el-input
                v-model="queryParams.failureName"
                class="library-search-input"
                clearable
                placeholder="请输入故障名称"
                @keyup.enter="handleQuery">
                <template #prefix>
                  <Icon icon="ep:search" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                class="library-search-input"
                clearable
                placeholder="请选择状态">
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.PMS_MAIN_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </div>

          <el-form-item class="library-actions">
            <el-button
              :type="showAdvancedSearch ? 'warning' : 'primary'"
              plain
              @click="toggleAdvancedSearch">
              <Icon :icon="showAdvancedSearch ? 'ep:arrow-up' : 'ep:arrow-down'" />
              {{ showAdvancedSearch ? '收起查询' : '更多查询' }}
            </el-button>
            <el-button type="primary" @click="handleQuery">
              <Icon icon="ep:search" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" />
              重置
            </el-button>
          </el-form-item>
        </div>

        <el-collapse-transition>
          <div v-show="showAdvancedSearch" class="advanced-search-panel">
            <el-form-item label="是否停机" prop="ifStop">
              <el-select
                v-model="queryParams.ifStop"
                class="library-search-input"
                clearable
                placeholder="请选择">
                <el-option
                  v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="故障时间" prop="failureTime">
              <el-date-picker
                v-model="queryParams.failureTime"
                class="library-date-range"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />
            </el-form-item>
            <el-form-item label="维修开始" prop="maintainStartTime">
              <el-date-picker
                v-model="queryParams.maintainStartTime"
                class="library-date-range"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />
            </el-form-item>
            <el-form-item label="维修结束" prop="maintainEndTime">
              <el-date-picker
                v-model="queryParams.maintainEndTime"
                class="library-date-range"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="queryParams.createTime"
                class="library-date-range"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />
            </el-form-item>
            <el-form-item label="故障系统" prop="failureSystem">
              <el-input
                v-model="queryParams.failureSystem"
                class="library-search-input"
                clearable
                placeholder="请输入故障系统"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="故障影响" prop="failureInfluence">
              <el-input
                v-model="queryParams.failureInfluence"
                class="library-search-input"
                clearable
                placeholder="请输入故障影响"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input
                v-model="queryParams.description"
                class="library-search-input"
                clearable
                placeholder="请输入描述"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </div>
        </el-collapse-transition>
      </el-form>

      <div class="library-table-wrap">
        <el-auto-resizer>
          <template #default="{ width, height }">
            <ZmTable
              :data="list"
              class="library-table"
              :loading="loading"
              :width="width"
              :height="height"
              :max-height="height"
              :column-max-width="420"
              row-key="id"
              empty-text="暂无数据"
              show-border>
              <ZmTableColumn
                label="故障编码"
                prop="failureCode"
                min-width="150"
                align="left"
                fixed="left">
                <template #default="{ row }">
                  <span class="maintain-code">{{ row.failureCode || '-' }}</span>
                </template>
              </ZmTableColumn>
              <ZmTableColumn label="故障名称" prop="failureName" min-width="180" align="left">
                <template #default="{ row }">
                  {{ row.failureName || '-' }}
                </template>
              </ZmTableColumn>
              <ZmTableColumn label="设备" prop="deviceName" min-width="160">
                <template #default="{ row }">
                  {{ row.deviceName || '-' }}
                </template>
              </ZmTableColumn>
              <ZmTableColumn label="状态" prop="status" min-width="120">
                <template #default="{ row }">
                  <dict-tag :type="DICT_TYPE.PMS_MAIN_STATUS" :value="row.status" />
                </template>
              </ZmTableColumn>
              <ZmTableColumn label="审核状态" prop="auditStatus" min-width="120">
                <template #default="{ row }">
                  <dict-tag :type="DICT_TYPE.CRM_AUDIT_STATUS" :value="row.auditStatus" />
                </template>
              </ZmTableColumn>
              <ZmTableColumn label="是否停机" prop="ifStop" min-width="120">
                <template #default="{ row }">
                  <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="row.ifStop" />
                </template>
              </ZmTableColumn>
              <ZmTableColumn label="维修开始时间" prop="maintainStartTime" min-width="180">
                <template #default="{ row }">
                  {{ formatRecordTime(row.maintainStartTime) }}
                </template>
              </ZmTableColumn>
              <ZmTableColumn label="故障时间" prop="failureTime" min-width="180">
                <template #default="{ row }">
                  {{ formatRecordTime(row.failureTime) }}
                </template>
              </ZmTableColumn>
              <ZmTableColumn label="创建时间" prop="createTime" min-width="180">
                <template #default="{ row }">
                  {{ formatRecordTime(row.createTime) }}
                </template>
              </ZmTableColumn>

              <ZmTableColumn label="操作" min-width="90" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" link @click="view(row)"> 查看 </el-button>
                </template>
              </ZmTableColumn>
            </ZmTable>
          </template>
        </el-auto-resizer>
      </div>

      <div class="library-pagination">
        <Pagination
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @pagination="getList" />
      </div>
    </section>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from 'vue'
import { IotMaintainApi, IotMaintainVO } from '@/api/pms/maintain'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import { DICT_TYPE, getBoolDictOptions, getStrDictOptions } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'

defineOptions({ name: 'DeviceMaintainRecord' })

const props = defineProps<{
  deviceId?: number
}>()

type MaintainRecordRow = IotMaintainVO & {
  createTime?: Date | string | number
}

const { ZmTable, ZmTableColumn } = useTableComponents<MaintainRecordRow>()
const { push } = useRouter()
const loading = ref(false)
const list = ref<MaintainRecordRow[]>([])
const total = ref(0)
const queryFormRef = ref()
const showAdvancedSearch = ref(false)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  failureCode: undefined as string | undefined,
  failureName: undefined as string | undefined,
  deviceId: undefined as number | undefined,
  status: undefined as string | undefined,
  ifStop: undefined as string | boolean | undefined,
  failureTime: [] as string[],
  failureInfluence: undefined as string | undefined,
  failureSystem: undefined as string | undefined,
  description: undefined as string | undefined,
  maintainStartTime: [] as string[],
  maintainEndTime: [] as string[],
  createTime: [] as string[]
})

const getList = async () => {
  if (!props.deviceId) return

  loading.value = true
  queryParams.deviceId = props.deviceId
  try {
    const data = await IotMaintainApi.getIotMaintainPage(queryParams)
    list.value = data?.list || []
    total.value = data?.total || 0
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value
}

const formatRecordTime = (value?: Date | string | number) => {
  return value ? formatDate(value as Date) : '-'
}

const view = (row: MaintainRecordRow) => {
  if (!row?.id) return

  push({
    name: 'MaintainDetail',
    params: { id: row.id }
  })
}

watch(
  () => props.deviceId,
  () => {
    getList()
  },
  { immediate: true }
)
</script>

<style scoped lang="scss">
.device-maintain-record {
  display: grid;
  gap: 14px;
}

.library-workbench {
  padding: 14px;
  overflow: hidden;
  background: linear-gradient(180deg, #f8fbff 0, var(--el-bg-color) 96px), var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
}

.library-search-form {
  :deep(.el-form-item) {
    margin-right: 10px;
    margin-bottom: 0;
  }

  :deep(.el-form-item:last-child) {
    margin-right: 0;
  }

  :deep(.el-button .app-iconify) {
    margin-right: 4px;
  }
}

.library-workbench__header {
  display: flex;
  gap: 16px;
  min-height: 56px;
  margin-bottom: 14px;
  align-items: center;
  justify-content: space-between;
}

.library-header-main {
  display: flex;
  gap: 10px;
  min-width: 0;
  align-items: center;
  flex: 1;
  flex-wrap: wrap;
}

.workbench-title {
  display: flex;
  gap: 12px;
  min-width: 0;
  align-items: center;

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 700;
    line-height: 24px;
    color: var(--el-text-color-primary);
  }
}

.workbench-title__icon {
  display: flex;
  width: 38px;
  height: 38px;
  font-size: 18px;
  color: #3478f6;
  background: #eaf2ff;
  border-radius: 10px;
  flex: none;
  align-items: center;
  justify-content: center;
}

.library-search-input {
  width: 220px;
}

.library-date-range {
  width: 300px;
}

.library-actions {
  flex: none;
}

.advanced-search-panel {
  display: flex;
  padding: 12px 14px;
  margin-bottom: 14px;
  background: rgb(255 255 255 / 68%);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  gap: 12px 4px;
  flex-wrap: wrap;
}

.library-table-wrap {
  height: 560px;
  min-width: 0;
}

.library-table {
  --el-table-header-bg-color: var(--el-fill-color-lighter);
  --el-table-row-hover-bg-color: #f6faff;

  overflow: hidden;
  border-radius: 8px;

  :deep(.el-table__cell) {
    padding: 9px 0;
  }
}

.maintain-code {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  font-weight: 500;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.library-pagination {
  display: flex;
  height: 40px;
  margin-top: 8px;
  align-items: center;
  justify-content: flex-end;
}

@media (width <= 767px) {
  .library-workbench__header {
    align-items: stretch;
    flex-direction: column;
  }

  .library-header-main {
    align-items: stretch;
    flex-direction: column;
  }

  .library-search-input {
    width: 100%;
  }
}
</style>
