<script setup lang="ts">
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import { IotMaintenancePlanApi, IotMaintenancePlanVO } from '@/api/pms/maintenance'
import { useUserStore } from '@/store/modules/user'
import { CommonStatusEnum } from '@/utils/constants'
import download from '@/utils/download'
import { dateFormatter2 } from '@/utils/formatTime'

defineOptions({ name: 'IotMaintenancePlan' })

type MaintenancePlanRow = Omit<IotMaintenancePlanVO, 'status'> & {
  status?: number
  createTime?: string
}

interface QueryParams extends PageParam {
  deptId?: number
  serialNumber?: string
  name?: string
  responsiblePerson?: string
  responsiblePersonName?: string
  remark?: string
  status?: number
  createTime?: string[]
}

const message = useMessage()
const { t } = useI18n()
const { push } = useRouter()
const { ZmTable, ZmTableColumn } = useTableComponents<MaintenancePlanRow>()

const rootDeptId = 156
const deptId = useUserStore().getUser.deptId || rootDeptId

const initQuery: QueryParams = {
  pageNo: 1,
  pageSize: 10,
  deptId: undefined,
  serialNumber: undefined,
  name: undefined,
  responsiblePerson: undefined,
  responsiblePersonName: undefined,
  remark: undefined,
  status: undefined,
  createTime: []
}

const queryParams = reactive<QueryParams>({ ...initQuery })
const queryFormRef = ref()
const loading = ref(false)
const exportLoading = ref(false)
const list = ref<MaintenancePlanRow[]>([])
const total = ref(0)
const selectedDept = ref<{ id: number; name: string }>()

const isValidStatus = (status: unknown): status is number =>
  status === CommonStatusEnum.ENABLE || status === CommonStatusEnum.DISABLE

const normalizeStatus = (status: unknown) => {
  const value = typeof status === 'string' ? Number(status) : status
  return isValidStatus(value) ? value : undefined
}

const getStatusText = (status?: number) =>
  status === CommonStatusEnum.ENABLE ? '启用' : status === CommonStatusEnum.DISABLE ? '停用' : ''

const getPlanName = (row: MaintenancePlanRow) => row.name || row.serialNumber || '该'

const getList = async () => {
  loading.value = true
  try {
    const data = await IotMaintenancePlanApi.getIotMaintenancePlanPage(queryParams)
    list.value = data.list.map((item: MaintenancePlanRow) => ({
      ...item,
      status: normalizeStatus(item.status)
    }))
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

const resetQuery = () => {
  Object.assign(queryParams, { ...initQuery })
  selectedDept.value = undefined
  queryFormRef.value?.resetFields()
  handleQuery()
}

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  handleQuery()
}

const handleCurrentChange = (val: number) => {
  queryParams.pageNo = val
  getList()
}

const handleDeptNodeClick = async (row: Tree) => {
  selectedDept.value = { id: row.id, name: row.name }
  queryParams.deptId = row.id
  queryParams.pageNo = 1
  await getList()
}

const detail = (id?: number) => {
  push({ name: 'IotMaintenancePlanDetail', params: { id } })
}

const openForm = (type: 'create' | 'update', id?: number) => {
  if (type === 'update' && typeof id === 'number') {
    push({ name: 'IotMainPlanEdit', params: { id } })
    return
  }

  push({
    name: 'IotAddMainPlan',
    query: {
      deptId: selectedDept.value?.id,
      deptName: selectedDept.value?.name
    }
  })
}

const handleStatusChange = async (row: MaintenancePlanRow, value: number | string | boolean) => {
  const status = normalizeStatus(value)
  const currentStatus = normalizeStatus(row.status)
  if (!row.id || status === undefined || currentStatus === undefined || status === currentStatus) {
    return
  }

  try {
    const text = getStatusText(status)
    await message.confirm(`确认要${text}"${getPlanName(row)}"保养计划吗?`)
    await IotMaintenancePlanApi.updatePlanStatus(row.id, status)
    row.status = status
    await getList()
  } catch {
    row.status = currentStatus
  }
}

const handleExport = async () => {
  exportLoading.value = true
  try {
    const data = await IotMaintenancePlanApi.exportIotMaintenancePlan(queryParams)
    download.excel(data, '保养计划.xls')
  } finally {
    exportLoading.value = false
  }
}

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

<template>
  <div
    class="maintenance-page grid grid-cols-[auto_1fr] grid-rows-[auto_1fr] gap-4 h-[calc(100vh-20px-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height))]"
  >
    <DeptTreeSelect
      :top-id="rootDeptId"
      :deptId="deptId"
      v-model="queryParams.deptId"
      :init-select="false"
      :show-title="false"
      request-api="getSimpleDeptList"
      class="maintenance-tree row-span-2"
      @node-click="handleDeptNodeClick"
    />

    <el-form
      ref="queryFormRef"
      :model="queryParams"
      size="default"
      label-width="80px"
      class="maintenance-query bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-6 py-3 min-w-0"
    >
      <div class="query-row">
        <el-form-item :label="t('main.planCode')" prop="serialNumber">
          <el-input
            v-model="queryParams.serialNumber"
            :placeholder="t('main.codeHolder')"
            clearable
            class="query-control"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('operationFill.name')" prop="name">
          <el-input
            v-model="queryParams.name"
            :placeholder="t('devicePerson.filterDevicePlaceholder')"
            clearable
            class="query-control"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('operationFill.createTime')" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            :start-placeholder="t('operationFill.start')"
            :end-placeholder="t('operationFill.end')"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="query-control query-control--date"
          />
        </el-form-item>
      </div>

      <el-form-item class="query-actions">
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />{{ t('operationFill.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />{{ t('operationFill.reset') }}
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['rq:iot-maintenance-plan:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />{{ t('operationFill.add') }}
        </el-button>
        <el-button
          type="success"
          plain
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['rq:iot-maintenance-plan:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />导出
        </el-button>
      </el-form-item>
    </el-form>

    <div class="bg-white dark:bg-[#1d1e1f] shadow rounded-lg flex flex-col p-4 min-w-0 min-h-0">
      <div class="flex-1 relative min-h-0">
        <el-auto-resizer class="absolute">
          <template #default="{ width, height }">
            <ZmTable
              :data="list"
              :loading="loading"
              :width="width"
              :height="height"
              :max-height="height"
              show-border
            >
              <ZmTableColumn
                type="index"
                :label="t('iotDevice.serial')"
                :width="70"
                fixed="left"
                hide-in-column-settings
              />
              <ZmTableColumn prop="serialNumber" :label="t('main.planCode')" fixed="left" />
              <ZmTableColumn prop="name" :label="t('main.planName')" fixed="left" />
              <ZmTableColumn
                prop="responsiblePersonName"
                :label="t('iotMaintain.PersonInCharge')"
              />
              <ZmTableColumn prop="status" :label="t('maintain.status')" width="100">
                <template #default="{ row }">
                  <el-switch
                    v-if="normalizeStatus(row.status) !== undefined"
                    :model-value="row.status"
                    :active-value="CommonStatusEnum.ENABLE"
                    :inactive-value="CommonStatusEnum.DISABLE"
                    @change="(status) => handleStatusChange(row, status)"
                  />
                  <span v-else>-</span>
                </template>
              </ZmTableColumn>
              <ZmTableColumn
                prop="createTime"
                :label="t('operationFill.createTime')"
                :formatter="dateFormatter2"
                width="180"
              />
              <ZmTableColumn :label="t('maintain.operation')" width="92" fixed="right" action>
                <template #default="{ row }">
                  <el-button
                    link
                    type="primary"
                    @click="openForm('update', row.id)"
                    v-hasPermi="['rq:iot-maintenance-plan:update']"
                  >
                    {{ t('info.edit') }}
                  </el-button>
                  <el-button
                    link
                    type="primary"
                    @click="detail(row.id)"
                    v-hasPermi="['rq:iot-maintenance-plan:query']"
                  >
                    {{ t('maintain.view') }}
                  </el-button>
                </template>
              </ZmTableColumn>
            </ZmTable>
          </template>
        </el-auto-resizer>
      </div>

      <div class="h-8 mt-2 flex items-center justify-end">
        <el-pagination
          v-show="total > 0"
          size="default"
          :current-page="queryParams.pageNo"
          :page-size="queryParams.pageSize"
          :background="true"
          :page-sizes="[10, 20, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.maintenance-query {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 12px 24px;
}

.query-row {
  display: flex;
  flex: 1 1 auto;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px 24px;
  min-width: 0;
}

.query-actions {
  flex: 0 0 auto;
}

.query-actions :deep(.el-form-item__content) {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 10px;
}

.query-actions :deep(.el-button) {
  margin-left: 0;
}

.query-control {
  width: 220px;
}

.query-control--date {
  width: 240px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

@media (width >= 2200px) {
  .maintenance-query,
  .query-row {
    flex-wrap: nowrap;
  }
}

@media (width <= 1500px) {
  .maintenance-query,
  .query-row {
    gap: 12px 18px;
  }

  .query-control {
    width: 200px;
  }

  .query-control--date {
    width: 220px;
  }
}

@media (width <= 1200px) {
  .maintenance-page {
    grid-template-columns: minmax(0, 1fr);
    grid-template-rows: auto auto minmax(480px, 1fr);
    height: auto;
    min-height: calc(
      100vh - 20px - var(--top-tool-height) - var(--tags-view-height) - var(--app-footer-height)
    );
  }

  :deep(.maintenance-tree) {
    grid-row: auto !important;
    width: 100% !important;
    height: 320px !important;
    min-width: 0 !important;
  }

  .query-actions {
    width: 100%;
  }
}

@media (width <= 768px) {
  .maintenance-query {
    padding: 12px;
  }

  .query-row,
  .query-row :deep(.el-form-item),
  .query-actions {
    width: 100%;
  }

  .query-control,
  .query-control--date {
    width: 100%;
  }

  .query-actions :deep(.el-form-item__content) {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 8px;
    width: 100%;
  }

  .query-actions :deep(.el-button) {
    width: 100%;
    margin-left: 0;
  }
}
</style>
