<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="计量器具" prop="measureId">
            <el-input
              v-model="formData.measureName"
              disabled
              placeholder="计量器具"
              style="width: 300px">
              <template #append>
                <el-link :disabled="measureSelectLocked" @click="selectMeasure" :underline="false">
                  选择
                </el-link>
              </template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="证书编码" prop="measureCertNo">
            <el-input v-model="formData.measureCertNo" placeholder="请输入证书编码" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="检测/校准日期" prop="detectDate">
            <el-date-picker
              v-model="formData.detectDate"
              type="date"
              value-format="x"
              placeholder="选择检测/校准日期"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="检测/校准机构" prop="detectOrg">
            <el-input v-model="formData.detectOrg" placeholder="请输入检测/校准机构" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="检测/校准标准" prop="detectStandard">
            <el-input v-model="formData.detectStandard" placeholder="请输入检测/校准标准" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="检测/校准有效期" prop="validityPeriod">
            <el-date-picker
              v-model="formData.validityPeriod"
              type="date"
              value-format="x"
              placeholder="选择检测/校准有效期"
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="精度" prop="precisions">
            <el-input v-model="formData.precisions" placeholder="请输入精度" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="校准金额" prop="detectAmount">
            <el-input v-model="formData.detectAmount" placeholder="请输入校准金额" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="检测周期" prop="detectCycle">
            <el-select v-model="formData.detectCycle" placeholder="检测周期" clearable>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.QHSE_DETECT_CYCLE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="检测/校准内容" prop="detectContent">
            <Editor v-model="formData.detectContent" height="150px" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="附件" prop="file">
            <UploadFile
              v-model="formData.file"
              :file-type="['doc', 'docx', 'pdf', 'jpg', 'png', 'jpeg', 'xls', 'xlsx', 'bmp']"
              :limit="3"
              :file-size="100"
              class="min-w-80px" />
          </el-form-item>
        </el-col>
      </el-row>
    </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 label="序列号" prop="serialNo">
          <el-input
            v-model="queryParams.serialNo"
            placeholder="请输入序列号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px" />
        </el-form-item>

        <el-form-item label="计量器具编码" prop="measureName">
          <el-input
            v-model="queryParams.measureCode"
            placeholder="请输入计量器具编码"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px" />
        </el-form-item>

        <el-form-item label="责任人" prop="dutyPerson">
          <el-input
            v-model="queryParams.dutyPerson"
            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">
      <zm-table
        :loading="loading"
        :data="measureList"
        :stripe="true"
        :show-overflow-tooltip="true"
        ref="measureTableRef">
        <zm-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>
        </zm-table-column>
        <zm-table-column :label="t('monitor.serial')" width="70" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </zm-table-column>
        <zm-table-column label="计量器具编码" align="center" prop="measureCode" />
        <zm-table-column label="序列号" align="center" prop="serialNo" />
        <zm-table-column label="计量器具名称" align="center" prop="measureName" />
        <zm-table-column label="计量单位" align="center" prop="measureUnit" />

        <zm-table-column label="责任人" align="center" prop="dutyPerson" />
        <zm-table-column label="品牌" align="center" prop="brand" />
        <zm-table-column label="规格型号" align="center" prop="modelName" />
        <zm-table-column label="分类" align="center" prop="classify" />
        <zm-table-column label="采购日期" align="center" prop="buyDate">
          <template #default="scope">
            {{ formatDateCorrectly(scope.row.buyDate) }}
          </template>
        </zm-table-column>
        <zm-table-column label="有效期" align="center" prop="validity">
          <template #default="scope">
            {{ formatDateCorrectly(scope.row.validity) }}
          </template>
        </zm-table-column>
        <zm-table-column label="上次检验日期" align="center" prop="lastTime" min-width="150">
          <template #default="scope">
            {{ formatDateCorrectly(scope.row.lastTime) }}
          </template>
        </zm-table-column>
        <zm-table-column label="价格" align="center" prop="measurePrice">
          <template #default="scope">
            {{ scope.row.measurePrice }}
          </template>
        </zm-table-column>
        <zm-table-column label="备注" align="center" prop="remark" />
      </zm-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), (selectedMeasureId = undefined))"
        >取 消</el-button
      >
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { IotMeasureDetectApi, IotMeasureDetectVO, IotInstrumentApi } from '@/api/pms/qhse/index'
import { formatDate } from '@/utils/formatTime'
import { handleTree } from '@/utils/tree'
import { onMounted, ref } from 'vue'
import * as DeptApi from '@/api/system/dept'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

/** 计量器具-检测校准明细 表单 */
defineOptions({ name: 'IotMeasureDetectForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const deptList2 = ref<Tree[]>([]) // 树形结构

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const measureSelectLocked = ref(false)
const formData = ref({
  detectDate: undefined,
  detectOrg: undefined,
  detectContent: undefined,
  detectStandard: undefined,
  validityPeriod: undefined,
  detectAmount: undefined,
  deptId: undefined,
  measureName: '',
  measureId: '',
  measureCertNo: '',
  file: '',
  precisions: '',
  detectCycle: ''
})
const formRules = reactive({
  measureId: [{ required: true, message: '计量器具不能为空', trigger: 'blur' }],
  detectDate: [{ required: true, message: '检测/校准日期不能为空', trigger: 'blur' }],
  detectOrg: [{ required: true, message: '检测/校准机构不能为空', trigger: 'blur' }],
  detectContent: [{ required: true, message: '检测/校准内容不能为空', trigger: 'blur' }],
  validityPeriod: [{ required: true, message: '检测/校准有效期不能为空', trigger: 'blur' }],
  measureCertNo: [{ required: true, message: '证书编码不能为空', trigger: 'blur' }],
  detectStandard: [{ required: true, message: '检测/校准标准不能为空', trigger: 'blur' }],
  file: [{ required: true, message: '请上传文件', trigger: 'blur' }],
  precisions: [{ required: true, message: '精度不能为空', trigger: 'blur' }],
  detectCycle: [{ required: true, message: '请选择检测周期', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const measureList = ref([])

/** 打开弹窗 */
const open = async (
  type: string,
  id?: number,
  presetData?: {
    measureId?: number | string
    measureName?: string
    deptId?: number | string
    lockMeasureSelect?: boolean
  }
) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  measureSelectLocked.value = !!presetData?.lockMeasureSelect
  if (type === 'create' && presetData) {
    formData.value.measureId = presetData.measureId || ''
    formData.value.measureName = presetData.measureName || ''
    formData.value.deptId = presetData.deptId
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const res = await IotMeasureDetectApi.getIotMeasureDetect(id)
      console.log('res>>>>>>>>>>>>>>>>>>>', res)
      formData.value = { ...res }
      formData.value.measureName = res.measureCode
      formData.value.detectDate = Number(formData.value.detectDate)
    } 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 IotMeasureDetectVO
    if (formType.value === 'create') {
      if (data.file instanceof Array) {
        data.file = data.file.join(',')
      }
      await IotMeasureDetectApi.createIotMeasureDetect(data)
      message.success(t('common.createSuccess'))
    } else {
      if (data.file instanceof Array) {
        data.file = data.file.join(',')
      }

      await IotMeasureDetectApi.updateIotMeasureDetect(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.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)
}

/** 重置表单 */
const resetForm = () => {
  measureSelectLocked.value = false
  formData.value = {
    detectDate: undefined,
    detectOrg: undefined,
    detectContent: undefined,
    validityPeriod: undefined,
    detectAmount: undefined,
    deptId: undefined,
    measureName: '',
    measureId: '',
    measureCertNo: '',
    detectStandard: undefined,
    file: ''
  }
  formRef.value?.resetFields()
}

/** 获取计量器具列表 */
let loading = ref(false)
let total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  measureName: undefined,
  measureCode: undefined,
  deptId: undefined,
  dutyPerson: undefined,
  serialNo: undefined
})

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const resetQuery = () => {
  queryParams.measureName = undefined
  queryParams.measureCode = undefined
  queryParams.deptId = undefined
  queryParams.dutyPerson = undefined
  queryParams.serialNo = undefined
  handleQuery()
}
// 仪器选择相关
const measureDialogVisible = ref(false)
const selectedMeasureId = ref<number | undefined>(undefined) // 当前选中的仪器ID
const selectedMeasure = ref<any>(null) // 当前选中的仪器对象
// 处理单选框变化
const handleRadioChange = (row: any) => {
  selectedMeasureId.value = row.id
  selectedMeasure.value = row
}
const selectMeasure = () => {
  if (measureSelectLocked.value) return
  measureDialogVisible.value = true
  getList()

  selectedMeasureId.value = formData.value.measureId
}

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

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

  // 关闭选择仪器对话框
  measureDialogVisible.value = false
  selectedMeasureId.value = 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
  }
}

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