<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="物资柜" prop="loanFromId">
        <el-select
          :disabled="visibleSelect"
          v-model="queryParams.loanFromId"
          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="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="machinerytypeOptions"
          :props="{ label: 'materialsTypeName', value: 'id' }"
          placeholder="请选择物资类型"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="领取人" prop="loanUserName">
        <el-input
          v-model="queryParams.loanUserName"
          placeholder="请输入领取人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="领取时间" prop="loanTime">
        <el-date-picker
          v-model="loanTime"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          @change="handleClearLoanTime"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="归还人" prop="restitutionUserName">
        <el-input
          v-model="queryParams.restitutionUserName"
          placeholder="请输入归还人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="归还时间" prop="restitutionTime">
        <el-date-picker
          v-model="restitutionTime"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          @change="handleClearRestitutionTime"
          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 getStrDictOptions(DICT_TYPE.RECORD_OF_COLLECTION)"
            :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="danger" plain v-if="!visibleSelect" @click="handleQueryStatus">
          <Icon icon="ep:warning" class="mr-5px" /> 超时未还
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column v-if="!visibleSelect" label="物资柜" align="center" prop="loanFromName" />
      <el-table-column label="物资编号" align="center" prop="materialsId" />
      <el-table-column label="物资名称" align="center" prop="materialsName" />
      <el-table-column label="物资类型" align="center" prop="materialsTypeName" width="180" />
      <el-table-column label="物资图片" prop="materialsTypePicture" width="90">
        <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="loanUserName" />
      <el-table-column label="领取时间" align="center" prop="loanTime" />
      <el-table-column label="归还人" align="center" prop="restitutionUserName" />
      <el-table-column label="归还时间" align="center" prop="actualRestitutionTime" />
      <el-table-column label="借出时长" align="center" prop="loanDuration" :formatter="formatLoanDuration"/>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.RECORD_OF_COLLECTION" :value="scope.row.status" />
        </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,getStrDictOptions } from '@/utils/dict'
import { handleTree } from '@/utils/tree'
import * as LoanApi from '@/api/material/loan/index'
import * as CabinetApi from '@/api/material/lockers/index'
import * as TypeApi from '@/api/material/type/index'
import {getDateRange} from "@/utils/formatTime";


// 定义组件 props
const props = defineProps({
  cabinetId: {
    type: String || null,
    required: false
  }
})
defineOptions({ name: 'CollectionManagement' })



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

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const cabinets = ref([]) // 物资柜数据
const machinerytypeOptions = ref([]) // 物资类型数据
const visibleSelect = ref(false) // 是否显示物资柜选择

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  materialsName: undefined,
  materialsCode: undefined,
  loanUserName: undefined,
  loanTimeStart: undefined,
  loanTimeEnd: undefined,
  restitutionUserName: undefined,
  restitutionTimeStart: undefined,
  restitutionTimeEnd: undefined,
  restitutionRequired: undefined,
  restitutionToName: undefined,
  restitutionToId: undefined,
  loanFormName: undefined,
  loanFromId: undefined,
  status: undefined
})

const loanTime = ref(null) // 领取时间
const restitutionTime = ref(null) // 归还时间
const queryFormRef = ref() // 搜索的表单

/** 查询领取记录列表 */
const getList = async () => {
  loading.value = true
  try {
    // 处理时间范围
    if (Array.isArray(loanTime.value) && loanTime.value.length === 2) {
      const [startTime, endTime] = getDateRange(loanTime.value[0], loanTime.value[1])
      queryParams.loanTimeStart = startTime
      queryParams.loanTimeEnd = endTime
    }
    if (Array.isArray(restitutionTime.value) && restitutionTime.value.length === 2) {
      const [startTime, endTime] = getDateRange(restitutionTime.value[0], restitutionTime.value[1])
      queryParams.restitutionTimeStart = startTime
      queryParams.restitutionTimeEnd = endTime
    }
    const data = await LoanApi.listLoan(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
const formatLoanDuration = (row) => {
  const duration = row.loanDuration || ''
  // 假设返回格式是 "0小时 18分 54秒"
  return duration
    .replace(/^0小时\s*/, '')   // 去掉开头的 "0小时"
    .replace(/^0分\s*/, '')     // 如果有 "0分" 在最前面也去掉
    .trim()
}

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

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  loanTime.value = null
  restitutionTime.value = null
  queryFormRef.value?.resetFields()
  queryParams.loanTimeStart = null
  queryParams.loanTimeEnd = null
  queryParams.restitutionTimeStart = null
  queryParams.restitutionTimeEnd = null
  handleQuery()
}

/** 查询超时未还 */
const handleQueryStatus = () => {
  queryParams.status = '2'
  queryParams.pageNo = 1
  getList()
}



/** 清空领取时间 */
const handleClearLoanTime = (value: any) => {
  if (value == null) {
    queryParams.loanTimeStart = null
    queryParams.loanTimeEnd = null
  }
}

/** 清空归还时间 */
const handleClearRestitutionTime = (value: any) => {
  if (value == null) {
    queryParams.restitutionTimeStart = null
    queryParams.restitutionTimeEnd = null
  }
}

/** 初始化 **/
onMounted(async () => {
  queryParams.loanFromId = Number(props.cabinetId) || null
  if (props.cabinetId) {
    visibleSelect.value = true
  }
  await Promise.all([getList(), getCabinets(), getTreeselect()])
})
</script>

<style lang="scss" scoped>
.img-box {
  width: 50px;
  height: 50px;
  position: relative;

  #eyeicon {
    display: none;
  }

  &:hover {
    background: #000;

    .images {
      opacity: 0.6;
    }

    #eyeicon {
      display: block;
      position: absolute;
      top: 40%;
      left: 40%;
      z-index: 100;
      color: white;
      pointer-events: none;
    }
  }
}
</style>
