<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="物资柜" prop="cabinetId">
        <el-select
          :disabled="visibleSelect"
          v-model="queryParams.cabinetId"
          placeholder="请选择物资柜"
          clearable
          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="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="原物资编号" prop="oldMaterialsId">
        <el-input
          v-model="queryParams.oldMaterialsId"
          placeholder="请输入原物资编号（数字格式）"
          clearable
          @keyup.enter="handleQuery"
          @input="val => queryParams.oldMaterialsId = val.replace(/\D/g, '')"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="原RFID" prop="oldMaterialsRfid">
        <el-input
          v-model="queryParams.oldMaterialsRfid"
          placeholder="请输入原RFID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="新物资编号" prop="newMaterialsId">
        <el-input
          v-model="queryParams.newMaterialsId"
          placeholder="请输入新物资编号（数字格式）"
          clearable
          @keyup.enter="handleQuery"
          @input="val => queryParams.newMaterialsId = val.replace(/\D/g, '')"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="新RFID" prop="newMaterialsRfid">
        <el-input
          v-model="queryParams.newMaterialsRfid"
          placeholder="请输入新RFID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="更换人" prop="changeUserName">
        <el-input
          v-model="queryParams.changeUserName"
          placeholder="请输入更换人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="更换时间">
        <el-date-picker
          v-model="createTime"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="dateShortcuts"
          @change="handleClearTime(createTime)"
          class="!w-240px"
        />
      </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-form-item>
    </el-form>
  </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table
        v-loading="loading"
        :data="changeRecordList"
      >
        <el-table-column label="物资柜" align="center" prop="cabinetName">
          <template #default="scope">
            {{ scope.row.cabinetName || '-' }}
          </template>
        </el-table-column>
        <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="原物资编号" align="center" prop="oldMaterialsId" />
        <el-table-column label="原物资名称" align="center" prop="oldMaterialsName" />
        <el-table-column label="原RFID" align="center" prop="oldMaterialsRfid" />
        <el-table-column label="新物资编号" align="center" prop="newMaterialsId" />
        <el-table-column label="新物资名称" align="center" prop="newMaterialsName" />
        <el-table-column label="新RFID" align="center" prop="newMaterialsRfid" />
        <el-table-column label="更换人" align="center" prop="changeUserName" />
        <el-table-column label="更换时间" align="center" prop="changeDate">
          <template #default="scope">
            {{ scope.row.changeDate || '-' }}
          </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 * as ReplaceApi from '@/api/material/replace/index'
import * as lockerApi from '@/api/material/lockers/index'
import * as TypeApi from '@/api/material/type'
import { getDateRange} from '@/utils/formatTime'
import { handleTree } from '@/utils/tree'
defineOptions({ name: 'MaterialReplaceRecord' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const route=useRoute()
// 数据定义
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const changeRecordList = ref([]) // 列表的数据
const createTime = ref([]) // 创建时间
const visibleSelect = ref(false) // 是否禁用物资柜选择
const cabinets = ref([]) // 物资柜选项
const materialstypeOptions = ref([]) // 物资类型选项
const props = defineProps<{
  cabinetId?: string
  recordId?: string | number
}>()
// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  cabinetId: undefined,
  materialsTypeId: undefined,
  oldMaterialsId: undefined,
  oldMaterialsRfid: undefined,
  newMaterialsId: undefined,
  newMaterialsRfid: undefined,
  changeUserName: undefined,
  startTime: undefined,
  endTime: undefined,
  recordId: undefined
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

/** 查询物资更换记录列表 */
const getList = async () => {
  loading.value = true
  try {
    // 格式化日期
    if (Array.isArray(createTime.value) && createTime.value.length === 2) {
      const [startTime, endTime] = getDateRange(createTime.value[0], createTime.value[1])
      queryParams.startTime = startTime
      queryParams.endTime = endTime
    }

    if(props.cabinetId||props.recordId){
      queryParams.cabinetId = Number(props.cabinetId)
      if(props.recordId){
        queryParams.recordId = Number(props.recordId)
      }

    }
    if(route.query.cabinetId||route.query.recordId){
      queryParams.cabinetId = Number(route.query.cabinetId)
      if(route.query.recordId){
        queryParams.recordId = Number(route.query.recordId)

      }
    }
    // 处理 cabinetId 的特殊逻辑
    if (route.query.cabinetId || props.cabinetId) {
      visibleSelect.value = true
    }
    console.log(queryParams,'查询参数')
    const data = await ReplaceApi.listChangeRecord(queryParams)
    changeRecordList.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

/** 查询物资柜列表 */
const getCabinets = async () => {
  const data = await lockerApi.listMaterialsCabinet({ pageNo: 1, pageSize: -1 })
  cabinets.value = data.list.map(item => ({
    value: item.id,
    label: item.cabinetName
  }))
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const queryFormRef=ref()
/** 重置按钮操作 */
const resetQuery = () => {
  createTime.value = []
  queryParams.startTime = undefined
  queryParams.endTime = undefined
  queryFormRef.value?.resetFields()
  handleQuery()
}

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

/** 初始化 **/
onMounted(async () => {
  await getList()
  await getTreeselect()
  await getCabinets()
})
</script>

<style lang="scss" scoped>
.table-container {
  width: 100%;
  overflow-x: auto;
}
</style>
