<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->

    <DeptTree @node-click="handleDeptNodeClick" v-model:collapsed="isLeftContentCollapsed" />

    <el-col :xs="24" :span="isLeftContentCollapsed ? 24 : 20">
      <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-180px"
            />
          </el-form-item>
          <el-form-item label="是否过期" prop="expired">
            <el-select
              v-model="queryParams.expired"
              placeholder="请选择是否过期"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button @click="handleAdd" type="primary"
              ><Icon icon="ep:plus" class="mr-5px" />新增</el-button
            >
            <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-button @click="handleExport" type="success" plain :loading="exportLoading"
              ><Icon icon="ep:download" class="mr-5px" /> 导出</el-button
            >
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap class="flex-1 overflow-hidden mt-15px">
        <el-table
          v-loading="loading"
          :data="list"
          height="calc(78vh - 145px)"
          :show-overflow-tooltip="true"
          :row-style="tableRowStyle"
        >
          <el-table-column :label="t('monitor.serial')" width="70" align="center" fixed="left">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column
            label="名称"
            align="center"
            prop="measureName"
            fixed="left"
            width="120"
          />
          <el-table-column
            label="编码"
            align="center"
            prop="measureCode"
            width="150"
            fixed="left"
          />
          <el-table-column label="计量单位" align="center" prop="measureUnit" />

          <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" width="150">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.MEASURE_TYPE" :value="scope.row.classify" />
            </template>
          </el-table-column>
          <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="measurePrice">
            <template #default="scope">
              {{ scope.row.measurePrice }}
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />

          <el-table-column
            :label="t('devicePerson.operation')"
            align="center"
            fixed="right"
            min-width="120px"
          >
            <template #default="scope">
              <el-button link type="primary" @click="handleEdit(scope.row)"> 编辑 </el-button>
              <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
      <ContentWrap style="margin-top: -5px">
        <el-alert title="台账已过期红色预警" type="error" show-icon :closable="false">
          <template #icon>
            <Bell />
          </template>
        </el-alert>
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 新增/编辑台账对话框 -->
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="800px"
    destroy-on-close
    @close="closeDialog"
  >
    <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="measureName">
            <el-input v-model="formData.measureName" placeholder="请输入计量器具名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="责任人" prop="dutyPerson">
            <el-input v-model="formData.dutyPerson" placeholder="请输入责任人" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <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-col>
        <el-col :span="12">
          <el-form-item label="品牌" prop="brand">
            <el-input v-model="formData.brand" placeholder="请输入品牌" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="规格型号" prop="modelName">
            <el-input v-model="formData.modelName" placeholder="请输入规格型号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="measureUnit">
            <el-input v-model="formData.measureUnit" placeholder="请输入单位" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分类" prop="classify">
            <el-select
              v-model="formData.classify"
              placeholder="请选择分类"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.MEASURE_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="价格" prop="measurePrice">
            <el-input-number
              v-model="formData.measurePrice"
              :precision="2"
              :step="1"
              placeholder="请输入价格"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="采购日期" prop="buyDate">
            <el-date-picker
              v-model="formData.buyDate"
              type="date"
              value-format="x"
              placeholder="请选择采购日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入描述" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <!-- <el-col :span="12">
          <el-form-item label="有效期" prop="validity">
            <el-date-picker
              v-model="formData.validity"
              type="date"
              value-format="x"
              placeholder="请选择有效期"
              style="width: 100%"
            />
          </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="remark">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入描述" />
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>

    <template #footer>
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { IotInstrumentApi } from '@/api/pms/qhse/index'
import DeptTree from '@/views/system/user/DeptTree2.vue'
import { handleTree } from '@/utils/tree'
import { defaultProps } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { ElMessageBox } from 'element-plus'
const deptList = ref<Tree[]>([]) // 树形结构
const deptList2 = ref<Tree[]>([]) // 树形结构
import { formatDate } from '@/utils/formatTime'
import { DICT_TYPE, getStrDictOptions, getBoolDictOptions } from '@/utils/dict'

defineOptions({ name: 'IotQHSEMeasure' })

const loading = ref(true) // 列表的加载中
const formLoading = ref(false) // 表单加载中
const submitLoading = ref(false) // 提交按钮加载中
let exportLoading = ref(false)

const isLeftContentCollapsed = ref(false)

const { t } = useI18n()

const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  measureName: undefined,
  deptId: undefined,
  expired: undefined
})
const queryFormRef = ref(null) // 搜索的表单

const tableRowStyle = ({ row }) => {
  if (row.expired) {
    return { backgroundColor: '#ffe6e6' }
  }
  return {}
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单相关
const formRef = ref()
const formData = ref({
  measureName: '',
  measureUnit: '',
  dutyPerson: '',
  brand: '',
  modelName: '',
  classify: '',
  buyDate: null,
  remark: '',
  deptId: '',
  measureCode: '',
  // validity: null, // 有效期

  measurePrice: 0, // 价格
  measureCertNo: ''
})

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

  // 如果是秒级时间戳，转换为毫秒级
  let time = Number(timestamp)
  if (time < 10000000000) {
    // 小于这个数通常表示秒级时间戳
    time = time * 1000
  }

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

// 表单验证规则
const formRules = {
  measureName: [{ required: true, message: '计量器具名称不能为空', trigger: 'blur' }],
  dutyPerson: [{ required: true, message: '责任人不能为空', trigger: 'blur' }],
  classify: [{ required: true, message: '分类不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
  measureCertNo: [{ required: true, message: '证书编码不能为空', trigger: 'blur' }],
  validity: [{ required: true, message: '有效期不能为空', trigger: 'blur' }]
}

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

const downloadFile = (response: any) => {
  // 创建 blob 对象
  const blob = new Blob([response], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
  })

  // 获取文件名
  let fileName = '计量器具台账.xlsx'
  const disposition = response.headers ? response.headers['content-disposition'] : ''
  if (disposition) {
    const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
    const matches = filenameRegex.exec(disposition)
    if (matches != null && matches[1]) {
      fileName = matches[1].replace(/['"]/g, '')
    }
  }

  // 创建下载链接
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', fileName)

  // 触发下载
  document.body.appendChild(link)
  link.click()

  // 清理
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}

const handleExport = async () => {
  try {
    exportLoading.value = true
    // 调用导出接口
    const response = await IotInstrumentApi.exportInstrument(queryParams)

    // 下载文件
    downloadFile(response)
    exportLoading.value = false
  } catch (error) {
    ElMessage.error('导出失败，请重试')
    console.error('导出错误:', error)
  } finally {
  }
}

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

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

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

// 显示新增对话框
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增台账'
  resetForm()
  dialogVisible.value = true
}

// 显示编辑对话框
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑台账'

  formData.value = {
    ...row,
    // 确保日期字段正确处理
    buyDate: row.buyDate ? ensureMillisecondTimestamp(row.buyDate) : null,
    validity: row.validity ? ensureMillisecondTimestamp(row.validity) : null
  }

  dialogVisible.value = true
}

// 确保时间戳是毫秒级的
const ensureMillisecondTimestamp = (timestamp) => {
  let time = Number(timestamp)
  if (time < 10000000000) {
    // 秒级时间戳转为毫秒级
    return time * 1000
  }
  return time
}

//删除成套
const handleDelete = async (id: number) => {
  ElMessageBox.confirm('确定要删除该台账吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await IotInstrumentApi.deleteInstrument(id)
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        console.error(error)
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 重置表单
const resetForm = () => {
  formData.value = {
    measureName: '',
    measureUnit: '',
    dutyPerson: '',
    brand: '',
    modelName: '',
    classify: '',
    buyDate: null,
    remark: '',
    deptId: '',
    measureCode: '',
    // validity: null, // 有效期

    measurePrice: 0, // 价格
    measureCertNo: ''
  }
  formRef.value?.clearValidate()
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    // 准备提交数据
    const submitData = {
      ...formData.value,
      // 确保日期字段以正确的格式提交
      buyDate: formData.value.buyDate,
      validity: formData.value.validity
    }

    if (isEdit.value) {
      // 编辑
      await IotInstrumentApi.updateInstrument(submitData)
      ElMessage.success('编辑成功')
    } else {
      // 新增
      await IotInstrumentApi.createInstrument(submitData)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error(error)
  } finally {
    submitLoading.value = false
  }
}

onMounted(async () => {
  getList()

  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  deptList2.value = handleTree(await DeptApi.getSimpleDeptList())
})
</script>

<style scoped>
::deep(.el-tree--highlight-current) {
  height: 200px !important;
}
::deep(.el-transfer-panel__body) {
  height: 700px !important;
}
</style>
