<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="物资柜" prop="cabinetId">
        <el-select
          v-model="queryParams.cabinetId"
          placeholder="请选择物资柜"
          clearable
          @change="handleChangeCabinet"
          :disabled="visibleSelect"
          class="!w-240px"
        >
          <el-option
            v-for="dict in cabinets"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物资名称" prop="materialsName">
        <el-input
          v-model="queryParams.materialsName"
          placeholder="请输入物资名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="物资类型" prop="materialsTypeId">
        <el-tree-select
          v-model="queryParams.materialsTypeId"
          :data="materialstypeOptions"
          :props="{ label: 'materialsTypeName', value: 'id' }"
          placeholder="请选择物资类型"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="RFID" prop="materialsRfid">
        <el-input
          v-model="queryParams.materialsRfid"
          placeholder="请输入RFID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="检查时间" prop="checkDate">
        <el-date-picker
          v-model="checkDate"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          @clear="handleClearTime(checkDate)"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="检查结果" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择检查结果" class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CHECKS_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="异常原因" prop="reason">
        <el-select v-model="queryParams.reason" placeholder="请选择异常原因" class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.EXCEPTIONS_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:user:export']"
        >
          <Icon icon="ep:download" />导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
    >
      <el-table-column label="计划名称" align="center" prop="planName" width="200">
        <template #default="scope">
          <span>{{ scope.row.planName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物资柜" align="center" prop="cabinetName" />
      <el-table-column label="物资编号" align="center" prop="materialsId" />
      <el-table-column label="物资名称" align="center" prop="materialsName" />
      <el-table-column label="物资类型" align="center" prop="materialsTypeName" />
      <el-table-column label="物资图片" align="center" prop="materialsTypePicture"  width="85">
        <template #default="scope">
          <UploadImg
            v-if="scope.row.materialsTypePicture"
            v-model="scope.row.materialsTypePicture"
            :limit="1"
            height="50px"
            width="50px"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="RFID" align="center" prop="materialsRfid">
        <template #default="scope">
          <span>{{ scope.row.materialsRfid || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检查时间" align="center" prop="checkDate" width="250" />
      <el-table-column label="检查结果" align="center" prop="status">
        <template #default="scope">
          <dict-tag
            :type="DICT_TYPE.CHECKS_STATUS"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="异常原因" align="center" prop="reason">
        <template #default="scope">
          <dict-tag
            v-if="scope.row.reason !== '0'"
            :type="DICT_TYPE.EXCEPTIONS_STATUS"
            :value="scope.row.reason"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="措施" align="center" prop="measure">
        <template #default="scope">
          <span>{{ scope.row.measure || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更换记录" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleViewRecord(scope.row)">
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-model:total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { handleTree } from '@/utils/tree'
import * as RecordApi from '@/api/material/checkRecord'
import * as CabinetApi from '@/api/material/information/index'
import * as TypeApi from '@/api/material/type'
import download from '@/utils/download'

import {getDateRange} from "@/utils/formatTime";


defineOptions({ name: 'InspectionRecords' })

const props = defineProps<{
  planName?: string
  planId?: string | number
  cabinetId?: string | number
}>()

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

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const cabinets = ref([]) // 物资柜数据
const materialstypeOptions = ref([]) // 物资类型选项
const visibleSelect = ref(false) // 是否显示物资柜选择
// 在 setup 中定义
const route = useRoute()
const router = useRouter()
const emit = defineEmits<{
  recordId: [recordId: string | number]
}>()
// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  materialsRfid: undefined,
  materialsName: undefined,
  loanState: undefined,
  materialsId: undefined,
  materialsTypeId: undefined,
  startTime: undefined,
  endTime: undefined,
  reason: undefined,
  status: undefined,
  planId: undefined,
  planName: undefined,
  cabinetId: undefined
})

const checkDate = ref(null) // 检查时间
const queryFormRef = ref() // 搜索的表单
const handleChangeCabinet=(value)=>{
  queryParams.cabinetId = value
  console.log(value,'wuziId')
}
/** 查询检查记录列表 */
const getList = async () => {
  loading.value = true
  try {
    // 处理时间范围
    if (Array.isArray(checkDate.value) && checkDate.value.length == 2) {
      const [startTime, endTime] = getDateRange(checkDate.value[0], checkDate.value[1])
      queryParams.startTime = startTime
      queryParams.endTime = endTime
    }
    // // 定义字段配置，包含类型转换规则
    const paramConfig = {
      planName: { type: 'string' },
      planId: { type: 'number' },
      cabinetId: { type: 'number' },
      materialsCabinetId: { type: 'number' }
    } as const

    // 批量处理参数
    if(props.cabinetId||route.query.cabinetId){
      Object.entries(paramConfig).forEach(([field, { type }]) => {
        const value = props[field] ?? route.query[field]

        if (value !== undefined && value !== null && value !== '') {
          queryParams[field] = type === 'number' ? Number(value) : String(value)
        } else {
          queryParams[field] = null
        }
      })
    }


    // 处理 cabinetId 的特殊逻辑
    if (route.query.cabinetId || props.cabinetId) {
      visibleSelect.value = true
    }
    const data = await RecordApi.listCheckRecord(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取物资类型树形结构 */
const getMaterialTypes = async () => {
  const data = await TypeApi.listType({
    pageNo: 1,
    pageSize: -1
  })
  materialstypeOptions.value = handleTree(
    data.list,
    'id',
    'parentId',
    'children'
  )
}

/** 获取物资柜列表 */
const getCabinets = async () => {
  const data = await CabinetApi.getMaterialsCabinets({
    pageNo: 1,
    pageSize: -1
  })
  if (data?.list) {
    cabinets.value = data.list.map((item) => ({
      value: item.id,
      label: item.cabinetName
    }))
  }
}

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

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

/** 清空时间 */
const handleClearTime = (value: any) => {
  if (value == null) {
    queryParams.startTime = null
    queryParams.endTime = null
  }
}

/** 查看更换记录 */
const handleViewRecord = (row: any) => {
  if (props.cabinetId) {
    emit('recordId', row.recordId)
  } else {
    router.push({
      path: '/material/material/replacementrecords',
      query: {
        recordId: row.recordId
      }
    })
  }
}
/** 导出按钮操作 */
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RecordApi.exportCheckRecord(queryParams)
    download.excel(data, '物资检查记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}


/** 初始化 **/
onMounted(async () => {
  await Promise.all([
    getList(),
    getMaterialTypes(),
    getCabinets()
  ])

})



</script>

<style lang="scss" scoped>
.text-primary {
  color: var(--el-color-primary);
}

.cursor-pointer {
  cursor: pointer;
}
</style>
