<template>
  <el-dialog :title="title" v-model="dialogVisible" width="1200px" append-to-body>
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
      <el-form-item label="物资编码" prop="materialCode">
        <el-input
          v-model="queryParams.materialCode"
          placeholder="请输入物资编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物资名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资分类" prop="categoryId">
        <el-tree-select
          v-model="queryParams.categoryId"
          :data="materialCategoryOptions"
          :props="{ value: 'categoryId', label: 'categoryName', children: 'children' }"
          value-key="categoryId"
          placeholder="请选择物资分类"
          check-strictly
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格型号" prop="specification">
        <el-input
          v-model="queryParams.specification"
          placeholder="请输入规格型号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计量单位" prop="unit">
        <el-input
          v-model="queryParams.unit"
          placeholder="请输入计量单位"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物资编码" align="center" prop="materialCode" />
      <el-table-column label="物资名称" align="center" prop="materialName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="计量单位" align="center" prop="unit" />
      <el-table-column label="生产厂家" align="center" prop="manufacturer" />
      <el-table-column label="安全库存" align="center" prop="safetyStock" />
      <el-table-column label="状态" align="center" prop="status" />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="MaterialSelectDialog">
import { ref, reactive, watch } from 'vue'
import { listWmsMaterial } from "@/api/ware/wmsMaterial"
import { listWmsMaterialCategory } from "@/api/ware/wmsMaterialCategory"

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '选择物资'
  }
})

const emit = defineEmits(['update:visible', 'confirm', 'cancel'])

// 本地对话框可见性状态
const dialogVisible = ref(props.visible)

// 监听props变化，同步本地状态
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
})

// 监听本地状态变化，通知父组件
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 物资列表
const materialList = ref([])
// 加载状态
const loading = ref(false)
// 总条数
const total = ref(0)
// 选中的物资
const selectedMaterials = ref([])
// 物资分类树选项
const materialCategoryOptions = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  materialCode: null,
  materialName: null,
  categoryId: null,
  specification: null,
  unit: null
})

// 加载物资列表
const handleQuery = () => {
  loading.value = true
  listWmsMaterial(queryParams).then(response => {
    materialList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 重置查询参数
const resetQuery = () => {
  queryParams.materialCode = null
  queryParams.materialName = null
  queryParams.categoryId = null
  queryParams.specification = null
  queryParams.unit = null
  queryParams.pageNum = 1
  handleQuery()
}

// 物资选择变化
const handleSelectionChange = (selection) => {
  selectedMaterials.value = selection
}

// 确认选择
const handleConfirm = () => {
  if (selectedMaterials.value.length === 0) {
    return
  }
  emit('confirm', selectedMaterials.value)
  dialogVisible.value = false
}

// 取消选择
const handleCancel = () => {
  emit('cancel')
  dialogVisible.value = false
}

// 查询物资分类下拉树结构
const getTreeselect = () => {
  return new Promise((resolve) => {
    listWmsMaterialCategory().then(response => {
      materialCategoryOptions.value = []
      const data = { categoryId: 0, categoryName: '顶级节点', children: [] }
      data.children = handleTree(response.data, "categoryId", "parentId")
      materialCategoryOptions.value.push(data)
      resolve()
    })
  })
}

// 处理树数据
const handleTree = (data, id, parentId, children) => {
  children = children || 'children'
  const result = []
  const hash = {}
  data.forEach((item) => {
    hash[item[id]] = item
  })

  data.forEach((item) => {
    const hashParent = hash[item[parentId]]
    if (hashParent) {
      !hashParent[children] && (hashParent[children] = [])
      hashParent[children].push(item)
    } else {
      result.push(item)
    }
  })
  return result
}

// 暴露方法
const exposeMethods = {
  handleQuery,
  getTreeselect
}

defineExpose(exposeMethods)
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>