<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1" v-if="treeShow">
        <DeptTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="contentSpan" :xs="24">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item :label="t('iotDevice.code')" prop="deviceCode" style="margin-left: 25px">
            <el-input
              v-model="queryParams.deviceCode"
              :placeholder="t('iotDevice.codeHolder')"
              clearable
              @keyup.enter="handleQuery"
              class="!w-200px"
            />
          </el-form-item>
          <el-form-item :label="t('iotDevice.name')" prop="deviceName">
            <el-input
              v-model="queryParams.deviceName"
              :placeholder="t('iotDevice.nameHolder')"
              clearable
              @keyup.enter="handleQuery"
              class="!w-200px"
            />
          </el-form-item>

          <el-form-item>
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> {{ t('file.search') }}</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> {{ t('file.reset') }}</el-button
            >
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['rq:iot-device:export']"
            >
              <Icon icon="ep:download" 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="t('monitor.serial')" width="70" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="t('iotDevice.code')" align="center" prop="deviceCode" />
          <el-table-column :label="t('iotDevice.name')" align="center" prop="deviceName">
            <template #default="scope">
              <el-link :underline="false" type="primary" @click="handleDetail(scope.row.id)">
                {{ scope.row.deviceName }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column :label="t('bomList.serviceDue')" align="center">
            <template #default="scope">
              <template v-if="hasMaintenancePlan(scope.row.mainDistance)">
                <span :class="getDistanceClass(scope.row.mainDistance)">
                  {{ scope.row.mainDistance }}
                </span>
              </template>
              <span v-else>无保养计划</span>
            </template>
          </el-table-column>
          <el-table-column :label="t('iotDevice.dept')" align="center" prop="deptName" />
          <el-table-column :label="t('devicePerson.rp')" align="center" prop="responsibleNames" />
          <el-table-column :label="t('monitor.status')" align="center" prop="deviceStatus">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.PMS_DEVICE_STATUS" :value="scope.row.deviceStatus" />
            </template>
          </el-table-column>
          <!-- 工单状态列 -->
          <el-table-column :label="t('operationFill.status')" align="center">
            <template #default="scope">
              <span v-if="scope.row.shouldWorkOrder && scope.row.runningWorkOrder">
                {{ t('mainPlan.generatedNotExecuted') }}
              </span>
              <span v-else-if="scope.row.shouldWorkOrder && !scope.row.runningWorkOrder">
                {{ t('mainPlan.notGenerated') }}
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column :label="t('monitor.operation')" align="center" min-width="60px">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openBomForm(scope.row)"
                v-hasPermi="['rq:iot-device:query']"
                v-if="hasMaintenancePlan(scope.row.mainDistance)"
              >
                {{ t('monitor.details') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>
  <DeviceAlarmBomList ref="modelFormRef" :flag="flag" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { IotDeviceApi, IotDeviceVO } from '@/api/pms/device'
import { IotMainWorkOrderApi } from '@/api/pms/iotmainworkorder'
import { DICT_TYPE } from '@/utils/dict'
import DeptTree from '@/views/system/user/DeptTree.vue'
import { useCache } from '@/hooks/web/useCache'
import DeviceAlarmBomList from '@/views/pms/iotmainworkorder/DeviceAlarmBomList.vue'

/** 设备台账 列表 */
defineOptions({ name: 'IotDeviceMainAlarm' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转
const modelFormRef = ref()
const loading = ref(true) // 列表的加载中
const ifShow = ref(false)

const list = ref<IotDeviceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceCode: undefined,
  deviceName: undefined,
  brand: undefined,
  model: undefined,
  deptId: undefined,
  deviceStatus: undefined,
  assetProperty: undefined,
  picUrl: undefined,
  remark: undefined,
  manufacturerId: undefined,
  supplierId: undefined,
  manDate: [],
  nameplate: undefined,
  expires: undefined,
  plPrice: undefined,
  plDate: [],
  plYear: undefined,
  plStartDate: [],
  plMonthed: undefined,
  plAmounted: undefined,
  remainAmount: undefined,
  infoId: undefined,
  infoType: undefined,
  infoName: undefined,
  infoRemark: undefined,
  infoUrl: undefined,
  templateJson: undefined,
  creator: undefined,
  setFlag: ''
})
const queryFormRef = ref() // 搜索的表单
const flag = ref() // 查询保养计划或保养工单的标识
const exportLoading = ref(false) // 导出的加载中
const contentSpan = ref(20)
const treeShow = ref(true)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await IotMainWorkOrderApi.deviceMainDistances(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const getDistanceClass = (distance: number | string | null) => {
  if (distance === null || distance === undefined) return ''

  // 如果是数字类型，直接处理
  if (typeof distance === 'number') {
    return distance < 0 ? 'negative-distance' : distance > 0 ? 'positive-distance' : ''
  }

  // 如果是字符串，提取数字部分
  if (typeof distance === 'string') {
    // 使用正则提取数字部分（包括负号、小数点和科学计数法）
    const numericPart = distance.match(/[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/)?.[0]

    // 如果提取到数字部分，转换为数值
    if (numericPart) {
      const num = parseFloat(numericPart)
      return num < 0 ? 'negative-distance' : num > 0 ? 'positive-distance' : ''
    }
  }

  return ''
}

// 判断是否有保养计划
const hasMaintenancePlan = (mainDistance: any) => {
  // 检查：非null、非undefined、非空字符串
  return mainDistance != null && mainDistance !== ''
}

const handleDetail = (id: number) => {
  push({ name: 'DeviceDetailInfo', params: { id } })
}

const drawerVisible = ref<boolean>(false)
const showDrawer = ref()

const openBomForm = async (row) => {
  // 构建设备信息对象，包含所有需要的属性
  const deviceInfo = {
    deviceId: row.id,
    deviceCode: row.deviceCode,
    deviceName: row.deviceName,
    model: row.model // 新增 model 属性
  }
  if (row.workOrderId) {
    flag.value = 'workOrder'
    modelFormRef.value.open(row.workOrderId, flag.value, row.id)
  } else if (row.planId) {
    flag.value = 'plan'
    modelFormRef.value.open(row.planId, flag.value, deviceInfo)
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    exportLoading.value = true
    const data = await IotDeviceApi.exportIotDeviceMainAlarm(queryParams)
    download.excel(data, '保养查询.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const { wsCache } = useCache()
/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
<style scoped>
/* 正数样式 - 淡绿色 */
.positive-distance {
  color: #67c23a; /* element-plus 成功色 */
  background-color: rgba(103, 194, 58, 0.1); /* 10% 透明度的淡绿色背景 */
  padding: 2px 8px;
  border-radius: 4px;
  display: inline-block;
}

/* 负数样式 - 淡红色 */
.negative-distance {
  color: #f56c6c; /* element-plus 危险色 */
  background-color: rgba(245, 108, 108, 0.1); /* 10% 透明度的淡红色背景 */
  padding: 2px 8px;
  border-radius: 4px;
  display: inline-block;
}
</style>
