<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-button type="success" icon="Plus" @click="handleAddMaterial">新增</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>

  <!-- 新增物资对话框 -->
  <el-dialog :title="addMaterialTitle" v-model="addMaterialVisible" width="800px" append-to-body>
    <el-form ref="addMaterialRef" :model="addMaterialForm" :rules="addMaterialRules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物资编码" prop="materialCode">
            <el-input v-model="addMaterialForm.materialCode" placeholder="请输入物资编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物资名称" prop="materialName">
            <el-input v-model="addMaterialForm.materialName" placeholder="请输入物资名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物资分类" prop="categoryId">
            <el-tree-select
              v-model="addMaterialForm.categoryId"
              :data="materialCategoryOptions"
              :props="{ value: 'categoryId', label: 'categoryName', children: 'children' }"
              value-key="categoryId"
              placeholder="请选择物资分类"
              check-strictly
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规格型号" prop="specification">
            <el-input v-model="addMaterialForm.specification" placeholder="请输入规格型号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="计量单位" prop="unit">
            <el-input v-model="addMaterialForm.unit" placeholder="请输入计量单位" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生产厂家" prop="manufacturer">
            <el-input v-model="addMaterialForm.manufacturer" placeholder="请输入生产厂家" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="安全库存" prop="safetyStock">
            <el-input v-model.number="addMaterialForm.safetyStock" placeholder="请输入安全库存" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-switch v-model="addMaterialForm.status" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitAddMaterial">确 定</el-button>
        <el-button @click="cancelAddMaterial">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

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

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 addMaterialVisible = ref(false)
const addMaterialTitle = ref('新增物资')
const addMaterialForm = reactive({
  materialCode: '',
  materialName: '',
  categoryId: null,
  specification: '',
  unit: '',
  manufacturer: '',
  safetyStock: null,
  status: true
})

// 新增物资表单验证规则
const addMaterialRules = reactive({
  materialCode: [
    { required: true, message: '物资编码不能为空', trigger: 'blur' }
  ],
  materialName: [
    { required: true, message: '物资名称不能为空', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '物资分类不能为空', trigger: 'change' }
  ],
  specification: [
    { required: true, message: '规格型号不能为空', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '计量单位不能为空', trigger: 'blur' }
  ]
})

// 新增物资表单引用
const addMaterialRef = ref(null)

// 查询参数
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 handleAddMaterial = () => {
  addMaterialTitle.value = '新增物资'
  // 重置新增表单
  if (addMaterialRef.value) {
    addMaterialRef.value.resetFields()
  }
  // 设置默认状态为启用
  addMaterialForm.status = true
  addMaterialVisible.value = true
}

// 提交新增物资
const submitAddMaterial = () => {
  // 表单验证
  if (!addMaterialRef.value) return
  
  addMaterialRef.value.validate((valid) => {
    if (valid) {
      // 提交新增请求
      addWmsMaterial(addMaterialForm).then(response => {
        // 关闭新增对话框
        addMaterialVisible.value = false
        // 刷新物资列表
        handleQuery()
        // 提示新增成功
        ElMessage.success('新增物资成功')
      }).catch(error => {
        console.error('新增物资失败:', error)
        ElMessage.error('新增物资失败，请重试')
      })
    }
  })
}

// 取消新增物资
const cancelAddMaterial = () => {
  addMaterialVisible.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>