<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="计量器具" prop="measureId">
        <el-input v-model="formData.measureName" disabled placeholder="选择计量器具">
          <template #append>
            <el-link @click="selectMeasure" :underline="false">选择计量器具</el-link>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="使用日期" prop="useDate">
        <el-date-picker
          v-model="formData.useDate"
          type="date"
          value-format="x"
          placeholder="选择使用日期"
        />
      </el-form-item>
      <el-form-item label="使用原因" prop="useReason">
        <el-input v-model="formData.useReason" placeholder="请输入使用原因" />
      </el-form-item>
      <el-form-item label="计量项目" prop="measureProject">
        <el-input v-model="formData.measureProject" placeholder="请输入计量项目" />
      </el-form-item>
      <el-form-item label="使用人" prop="usePerson">
        <el-input v-model="formData.usePerson" placeholder="请输入使用人" />
      </el-form-item>

      <el-form-item label="部门" prop="deptId">
        <el-tree-select
          clearable
          v-model="formData.deptId"
          :data="deptList2"
          :props="defaultProps"
          check-strictly
          node-key="id"
          filterable
          placeholder="请选择所在部门"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <Dialog title="选择仪器" v-model="measureDialogVisible" width="60%">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="计量器具名称" prop="measureName">
          <el-input
            v-model="queryParams.measureName"
            placeholder="请输入计量器具名称"
            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('devicePerson.search') }}</el-button
          >
          <el-button @click="resetQuery"
            ><Icon icon="ep:refresh" class="mr-5px" /> {{ t('devicePerson.reset') }}</el-button
          >
        </el-form-item>
      </el-form>
    </ContentWrap>
    <div class="pb-10">
      <el-table
        v-loading="loading"
        :data="measureList"
        :stripe="true"
        :show-overflow-tooltip="true"
        ref="measureTableRef"
      >
        <el-table-column width="50" align="center">
          <template #default="scope">
            <el-radio
              :model-value="selectedMeasureId"
              :label="scope.row.id"
              @change="handleRadioChange(scope.row)"
            >
              &nbsp;
            </el-radio>
          </template>
        </el-table-column>
        <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="单位" align="center" prop="measureUnit" />
        <el-table-column label="名称" align="center" prop="measureName" />
        <el-table-column label="责任人" align="center" prop="dutyPerson" />
        <el-table-column label="品牌" align="center" prop="brand" />
        <el-table-column label="规格型号" align="center" prop="modelName" />
        <el-table-column label="分类" align="center" prop="classify" />
        <el-table-column label="采购日期" align="center" prop="buyDate">
          <template #default="scope">
            {{ formatDateCorrectly(scope.row.buyDate) }}
          </template>
        </el-table-column>
        <el-table-column label="有效期" align="center" prop="validity">
          <template #default="scope">
            {{ formatDateCorrectly(scope.row.validity) }}
          </template>
        </el-table-column>
        <el-table-column label="上次检验日期" align="center" prop="lastTime" min-width="150">
          <template #default="scope">
            {{ formatDateCorrectly(scope.row.lastTime) }}
          </template>
        </el-table-column>
        <el-table-column label="价格" align="center" prop="measurePrice">
          <template #default="scope">
            {{ scope.row.measurePrice }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <template #footer>
      <el-button @click="confirmSelectMeasure" type="primary">确 定</el-button>
      <el-button @click="measureDialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { IotMeasureRecordApi, IotMeasureRecordVO, IotInstrumentApi } from '@/api/pms/qhse/index'
import { onMounted, ref } from 'vue'
import { formatDate } from '@/utils/formatTime'
import { handleTree } from '@/utils/tree'
import { defaultProps } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'

/** 计量器具-使用记录 表单 */
defineOptions({ name: 'IotMeasureRecordForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  measureId: undefined,
  measureName: '', // 添加计量器具名称字段
  useDate: undefined,
  useReason: undefined,
  measureProject: undefined,
  usePerson: undefined,
  userId: undefined,
  deptId: undefined
})
const formRules = reactive({
  measureId: [{ required: true, message: '计量器具不能为空', trigger: 'blur' }],
  useDate: [{ required: true, message: '使用日期不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

// 仪器选择相关
const measureDialogVisible = ref(false)

const selectedMeasureId = ref<number | undefined>(undefined) // 当前选中的仪器ID
const selectedMeasure = ref<any>(null) // 当前选中的仪器对象
const deptList2 = ref<Tree[]>([]) // 树形结构

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

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const recordData = await IotMeasureRecordApi.getIotMeasureRecord(id)
      formData.value = recordData

      // 特别处理 useDate 字段
      if (recordData.useDate) {
        // 确保 useDate 是正确的毫秒时间戳
        const date = new Date(recordData.useDate)
        if (!isNaN(date.getTime()) && date.getFullYear() >= 1900) {
          formData.value.useDate = recordData.useDate
        } else {
          formData.value.useDate = undefined
        }
      }

      // 设置选中的仪器ID
      selectedMeasureId.value = formData.value.measureId
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as IotMeasureRecordVO
    if (formType.value === 'create') {
      await IotMeasureRecordApi.createIotMeasureRecord(data)
      message.success(t('common.createSuccess'))
    } else {
      await IotMeasureRecordApi.updateIotMeasureRecord(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    measureId: undefined,
    measureName: '',
    useDate: undefined,
    useReason: undefined,
    measureProject: undefined,
    usePerson: undefined,
    userId: undefined,
    deptId: undefined
  }
  formRef.value?.resetFields()
  selectedMeasureId.value = undefined
  selectedMeasure.value = null
}

const resetQuery = () => {
  queryParams.measureName = undefined
  queryParams.deptId = undefined
  handleQuery()
}

const measureList = ref([])
let total = ref(0)
const loading = ref(true) // 列表的加载中
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  measureName: undefined,
  deptId: undefined
})

const getList = async () => {
  loading.value = true
  try {
    const data = await IotInstrumentApi.getInstrumentList(queryParams)
    measureList.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const selectMeasure = () => {
  measureDialogVisible.value = true
  getList()
}

// 处理单选框变化
const handleRadioChange = (row: any) => {
  selectedMeasureId.value = row.id
  selectedMeasure.value = row
}

// 确认选择仪器
const confirmSelectMeasure = () => {
  if (!selectedMeasure.value) {
    message.warning('请先选择一个计量器具')
    return
  }

  // 将选中的仪器信息填入表单
  formData.value.measureId = selectedMeasure.value.id
  formData.value.measureName = selectedMeasure.value.measureName

  // 关闭选择仪器对话框
  measureDialogVisible.value = false
}

// 正确格式化日期的函数
const formatDateCorrectly = (timestamp) => {
  if (!timestamp) return ''

  // 确保处理各种可能的时间戳格式
  let time = Number(timestamp)

  // 处理不同时间戳格式
  if (time < 10000000000) {
    time = time * 1000
  }

  // 检查是否为有效日期
  const date = new Date(time)
  if (isNaN(date.getTime())) {
    return ''
  }

  // 验证日期合理性（例如：不能是过于久远的日期）
  const minValidYear = 1900
  if (date.getFullYear() < minValidYear) {
    console.warn('Invalid date detected:', timestamp)
    return ''
  }

  return formatDate(time).substring(0, 10)
}

onMounted(async () => {
  deptList2.value = handleTree(await DeptApi.getSimpleDeptList())
})
</script>
