<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item
        :label="visibleSelect ? '物资柜' : '绑定物资柜'"
        prop="materialsCabinetId"
      >
        <el-select
          v-model="queryParams.materialsCabinetId"
          :disabled="visibleSelect"
          @change="handleChangeCanbinet"
          placeholder="请选择物资柜"
          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="propertyId">
        <el-select
          v-model="queryParams.propertyId"
          placeholder="请选择物资规格种类"
          @change="handlePropertyChange"
          class="!w-240px"
        >
          <el-option
            v-for="property in PropertyList"
            :key="property.id"
            :label="property.propertyName"
            :value="property.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="物资规格" prop="recordId">
        <el-select
          v-model="queryParams.recordId"
          placeholder="请选择物资规格"
          :disabled="!queryParams.propertyId"
          class="!w-240px"
        >
          <el-option
            v-for="value in filteredPropertyValues"
            :key="value.id"
            :label="value.valueName"
            :value="value.id"
          />
        </el-select>
      </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="supplier">
        <el-input
          v-model="queryParams.supplier"
          placeholder="请输入供应商"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="有效期截止" prop="expirationDate">
        <el-date-picker
          v-model="createTime"
          type="datetimerange"
          range-separator="-"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          :picker-options="pickerOptions"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="是否在柜中" prop="loanState">
        <el-select
          v-model="queryParams.loanState"
          placeholder="是否在柜中"
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MATERIAL_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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.MATERIAL_INFO_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="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['iscs:materials:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleImport"
          v-hasPermi="['iscs:materials:create']"
        >
          <Icon icon="ep:upload" class="mr-5px" /> 批量新增
        </el-button>
        <el-button
          v-if="cabinetId"
          type="primary"
          plain
          @click="handleBind"
          v-hasPermi="['iscs:materials:create']"
        >
          <Icon icon="ep:link" class="mr-5px" /> 绑定物资
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iscs:materials:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="materialsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        :label="visibleSelect ? '物资柜' : '绑定物资柜'"
        align="center"
        prop="cabinetName"
      >
        <template #default="scope">
          <span v-if="scope.row.cabinetName">{{ scope.row.cabinetName }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="物资编号" align="center" prop="id" />
      <el-table-column label="物资名称" align="center" prop="materialsName" />
      <el-table-column
        label="物资类型"
        align="center"
        prop="materialsTypeName"
      />
      <el-table-column
        label="物资规格种类"
        align="center"
        prop="propertiesProperty"
      />
      <el-table-column label="物资规格" align="center" prop="propertiesValue" />
      <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="RFID" align="center" prop="materialsRfid">
        <template #default="scope">
          <span v-if="scope.row.materialsRfid">{{ scope.row.materialsRfid }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="supplier" />
      <el-table-column label="有效期截止" align="center" prop="expirationDate" />
      <el-table-column label="是否在柜中" align="center" prop="loanState">
        <template #default="scope">
          <dict-tag
            :type="DICT_TYPE.MATERIAL_STATUS"
            :value="scope.row.loanState"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag
            :type="DICT_TYPE.MATERIAL_INFO_STATUS"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['iscs:materials:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['iscs:materials:delete']"
          >
            删除
          </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>

  <!-- 表单弹窗 -->
  <MaterialForm ref="formRef" @success="getList" />

  <!-- 导入弹窗 -->
  <ImportDialog ref="importRef" @success="getList" />

  <!-- 绑定物资弹窗 -->
  <BindDialog ref="bindRef" :cabinet-id="cabinetId" @success="getList" />
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { getDateRange} from '@/utils/formatTime'
import { handleTree } from '@/utils/tree'
import * as MaterialApi from '@/api/material/information'
import * as CabinetApi from "@/api/material/lockers/index";
import * as TypeApi from '@/api/material/type'
import * as PropertyApi from '@/api/material/standard/index'
import * as PropertyValueApi from "@/api/material/standard/propertyValue"
import MaterialForm from './MaterialForm.vue'
import ImportDialog from './ImportDialog.vue'
import BindDialog from './BindDialog.vue'

defineOptions({ name: 'MaterialInformation' })

const props = defineProps({
  cabinetId: {
    type: [String, Number],
    default: null
  }
})

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

// 列表数据
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const materialsList = ref([]) // 列表的数据
const ids = ref([]) // 选中的数据
const single = ref(true) // 非单个禁用
const multiple = ref(true) // 非多个禁用
const visibleSelect = ref(false) // 是否显示选择物资柜

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  materialsCode: undefined,
  materialsName: undefined,
  materialsRfid: undefined,
  loanState: undefined,
  materialsCabinetId: null as string | number | null,
  materialsTypeId: undefined,
  startExpirationDate: undefined,
  endExpirationDate: undefined,
  supplier: undefined,
  expirationDate: undefined,
  recordId: undefined,
  propertyId: undefined
})

// 日期选择器配置
const createTime = ref([])
const pickerOptions = {
  shortcuts: [
    {
      text: '最近一周',
      onClick(picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
        picker.$emit('pick', [start, end])
      }
    },
    {
      text: '最近一个月',
      onClick(picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        picker.$emit('pick', [start, end])
      }
    },
    {
      text: '最近三个月',
      onClick(picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
        picker.$emit('pick', [start, end])
      }
    }
  ]
}

// 物资柜选项
const cabinets = ref([])
const queryParamsCabinets = reactive({
  pageNo: 1,
  pageSize: -1
})

// 物资类型选项
const machinerytypeOptions = ref([])

// 物资规格选项
const PropertyList = ref([])
const PropertyValueList = ref([])

// 计算属性
const filteredPropertyValues = computed(() => {
  if (!queryParams.propertyId) {
    return []
  }
  return PropertyValueList.value.filter(
    (value) => value.propertyId === queryParams.propertyId
  )
})
const route=useRoute()
// 初始化
onMounted(async () => {
// 设置初始值
  setInitialCabinetId()
  await getList()
  await getTreeselect()
  await materialsCabinets()

})

// 设置初始物资柜ID
const setInitialCabinetId = () => {
  if (props.cabinetId||route.query.cabinetId) {
    queryParams.materialsCabinetId = Number(props.cabinetId)
    queryParams.materialsCabinetId = Number(route.query.cabinetId)
    visibleSelect.value = true
  } else {
    queryParams.materialsCabinetId = 1
  }
}
// 查询物资柜
const handleChangeCanbinet=(value)=>{
  console.log(value,'value')
  queryParams.materialsCabinetId = Number(value)
}
// 监听物资柜数据变化，确保值能正确回显
watch(
  () => cabinets.value,
  (newCabinets) => {
    if (newCabinets && newCabinets.length > 0) {
      // 如果当前没有选中值，但有默认值，则设置
      if (!queryParams.materialsCabinetId) {
        setInitialCabinetId()
      }
    }
  },
  { immediate: true }
)

/** 查询物资列表 */
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.startExpirationDate = startTime
      queryParams.endExpirationDate = endTime
    }
    console.log(queryParams,'queryParams')
    const data = await MaterialApi.listMaterials(queryParams)
    materialsList.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 查询物资类型下拉树结构 */
const getTreeselect = async () => {
  const data = await TypeApi.listType({ pageNo: 1, pageSize: -1 })
  machinerytypeOptions.value = handleTree(
    data.list,
    'id',
    'parentId',
    'children'
  )
  // 获取物资属性名和属性值
  const propertyData = await PropertyApi.PropertyPage({ pageSize: -1, pageNo: 1 })
  PropertyList.value = propertyData.list
  const propertyValueData = await PropertyValueApi.PropertyValuePage({ pageSize: -1, pageNo: 1 })
  PropertyValueList.value = propertyValueData.list
}

/** 查询物资柜列表 */
const materialsCabinets = async () => {
  const data = await CabinetApi.listMaterialsCabinet(queryParamsCabinets)

  if (data?.list) {
    cabinets.value = data.list.map((item) => ({
      value: item.id,
      label: item.cabinetName
    }))
    cabinets.value.push({ value: 0, label: '空' })
  }
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  createTime.value = []
  queryParams.materialsCode = undefined
  queryParams.materialsName = undefined
  queryParams.loanState = undefined
  if(route.query.cabinetId) {
    queryParams.materialsCabinetId = Number(route.query.cabinetId)
  }else {
    queryParams.materialsCabinetId = undefined
  }
  queryParams.materialsTypeId = undefined
  queryParams.startExpirationDate = undefined
  queryParams.endExpirationDate = undefined
  queryParams.materialsRfid = undefined
  queryParams.supplier = undefined
  queryParams.propertyId = undefined
  queryParams.recordId = undefined
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id?: number) => {
  const materialsIds = id || ids.value
  try {
    await message.delConfirm()
    await MaterialApi.deleteMaterials(materialsIds)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 导入按钮操作 */
const importRef = ref()
const handleImport = () => {
  importRef.value.open()
}

/** 绑定物资按钮操作 */
const bindRef = ref()
const handleBind = () => {
  bindRef.value.open()
}

/** 属性改变处理 */
const handlePropertyChange = () => {
  queryParams.recordId = undefined
}

// /** 日期清空处理 */
// const handleClearTime = (value: any) => {
//   if (value == null) {
//     queryParams.startExpirationDate = undefined
//     queryParams.endExpirationDate = undefined
//   }
// }
</script>
