<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item :label="t('bomList.name')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="t('bomList.nHolder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('bomList.status')" prop="result">
        <el-select
          v-model="queryParams.result"
          :placeholder="t('bomList.status')"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in resultOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('common.createTime')" prop="createTime" label-width="100px">
        <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="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @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="['pms:iot-main-work-order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />  {{ t('operationFill.add') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['pms:iot-main-work-order: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('iotDevice.serial')" width="70" align="center">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <!--
      <el-table-column label="工单号" align="center" prop="orderNumber" /> -->
      <el-table-column :label="t('bomList.name')" align="center" prop="name" />
      <el-table-column :label="t('bomList.status')" align="center" prop="result" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PMS_MAIN_WORK_ORDER_RESULT" :value="scope.row.result" />
        </template>
      </el-table-column>
      <el-table-column :label="t('bomList.serviceDue')" align="center">
        <template #default="scope">
          <span :class="getDistanceClass(scope.row.mainDistance)">
            {{ scope.row.mainDistance }}
          </span>
        </template>
      </el-table-column>
      <el-table-column :label="t('bomList.type')" align="center" prop="type" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PMS_MAIN_WORK_ORDER_TYPE" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column :label="t('iotMaintain.PersonInCharge')" align="center" prop="responsiblePersonName" />
      <el-table-column :label="t('iotMaintain.operation')" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['pms:iot-main-work-order:update']"
            v-if="scope.row.result === 1"
          >
            {{ t('operationFill.fill') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="detail(scope.row.id)"
            v-hasPermi="['pms:iot-main-work-order:query']"
          >
            {{ t('operationFill.view')  }}
          </el-button>
          <!--
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['pms:iot-main-work-order:delete']"
          >
            删除
          </el-button>
          -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

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

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { IotMainWorkOrderApi, IotMainWorkOrderVO } from '@/api/pms/iotmainworkorder'
import IotMainWorkOrderForm from './IotMainWorkOrderForm.vue'
import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";
const { push } = useRouter() // 路由跳转

/** 保养工单 列表 */
defineOptions({ name: 'IotMainWorkOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<IotMainWorkOrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  planId: undefined,
  planSerialNumber: undefined,
  deptId: undefined,
  orderNumber: undefined,
  name: undefined,
  type: undefined,
  responsiblePerson: undefined,
  responsiblePersonName: undefined,
  cost: undefined,
  result: undefined,
  otherCost: undefined,
  laborCost: undefined,
  outsourcingFlag: undefined,
  actualStartTime: [],
  actualEndTime: [],
  remark: undefined,
  status: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

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

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

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

// 保养状态 下拉列表 添加数据字典外的选项
const resultOptions = computed(() => [
  {
    label: t('operationFill.all'),
    value: '0' // 空值会触发 clearable 效果
  },
  ...getStrDictOptions(DICT_TYPE.PMS_MAIN_WORK_ORDER_RESULT)
])

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 formRef = ref()
const openForm = (type: string, id?: number) => {
  // 修改
  if (typeof id === 'number') {
    push({ name: 'IotMainWorkOrderBom', params: {id } })
    return
  } else {
    push({ name: 'IotMainWorkOrderAdd', params:{} })
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await IotMainWorkOrderApi.deleteIotMainWorkOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

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

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await IotMainWorkOrderApi.exportIotMainWorkOrder(queryParams)
    download.excel(data, '保养工单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
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>
