<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="locationCode">
        <el-input
          v-model="queryParams.locationCode"
          placeholder="请输入货架编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货架名称" prop="locationName">
        <el-input
          v-model="queryParams.locationName"
          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="handleAdd" v-hasPermi="['ware:wmsLocation:add']">新增货架</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="locationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="货架编码" align="center" prop="locationCode" />
      <el-table-column label="货架名称" align="center" prop="locationName" />
      <el-table-column label="所属库区" align="center" prop="area.areaName" />
      <el-table-column label="货架状态" align="center" prop="status" >
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 库区选择对话框组件 -->
    <AreaSelectTreeDialog ref="areaSelectDialogRef" v-model:visible="areaDialogVisible" title="选择库区"
      @confirm="handleAreaConfirm" />

    <!-- 新增货架对话框 -->
    <el-dialog :title="addTitle" v-model="addOpen" width="500px" append-to-body>
      <el-form ref="locationRef" :model="addForm" :rules="addRules" label-width="80px">
        <el-form-item label="货架编码" prop="locationCode">
          <el-input v-model="addForm.locationCode" placeholder="请输入货架编码" />
        </el-form-item>
        <el-form-item label="货架名称" prop="locationName">
          <el-input v-model="addForm.locationName" placeholder="请输入货架名称" />
        </el-form-item>
        <el-form-item label="所属库区" prop="areaId">
          <el-row :gutter="10">
            <el-col :span="18">
              <el-input v-model="addForm.area.areaName" placeholder="请选择所属库区" readonly />
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="openAreaSelect">选择库区</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="最大容量" prop="maxCapacity">
          <el-input v-model="addForm.maxCapacity" placeholder="请输入最大容量" />
        </el-form-item>
        <el-form-item label="当前容量" prop="currentCapacity">
          <el-input v-model="addForm.currentCapacity" placeholder="请输入当前容量" />
        </el-form-item>
        <el-form-item label="承重限制" prop="weightLimit">
          <el-input v-model="addForm.weightLimit" placeholder="请输入承重限制" />
        </el-form-item>
        <el-form-item label="长度" prop="length">
          <el-input v-model="addForm.length" placeholder="请输入长度" />
        </el-form-item>
        <el-form-item label="宽度" prop="width">
          <el-input v-model="addForm.width" placeholder="请输入宽度" />
        </el-form-item>
        <el-form-item label="高度" prop="height">
          <el-input v-model="addForm.height" placeholder="请输入高度" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addForm.remark" type="textarea" placeholder="请输入备注内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAddForm">确 定</el-button>
          <el-button @click="handleAddCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <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="LocationSelectDialog">
import { ref, reactive, watch } from 'vue'
import { listWmsLocation, addWmsLocation } from "@/api/ware/wmsLocation"
import AreaSelectTreeDialog from "@/components/AreaSelectTreeDialog.vue"
const { proxy } = getCurrentInstance()

const { sys_normal_disable } = proxy.useDict('sys_normal_disable')

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 locationList = ref([])
// 加载状态
const loading = ref(false)
// 总条数
const total = ref(0)
// 选中的货架
const selectedLocations = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  locationCode: null,
  locationName: null,
  areaId: null,
  xCoordinate: null,
  yCoordinate: null,
  zCoordinate: null,
  status: null
})

// 加载货架列表
const handleQuery = () => {
  loading.value = true
  listWmsLocation(queryParams).then(response => {
    locationList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 重置查询参数
const resetQuery = () => {
  queryParams.locationCode = null
  queryParams.locationName = null
  queryParams.areaId = null
  queryParams.xCoordinate = null
  queryParams.yCoordinate = null
  queryParams.zCoordinate = null
  queryParams.status = null
  queryParams.pageNum = 1
  handleQuery()
}

// 货架选择变化
const handleSelectionChange = (selection) => {
  selectedLocations.value = selection
}

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

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

// 新增货架相关状态
const addOpen = ref(false)
const addTitle = ref("")
const areaDialogVisible = ref(false)
const areaSelectDialogRef = ref(null)

const addForm = reactive({
  locationId: null,
  locationCode: null,
  locationName: null,
  areaId: null,
  area: {
    areaId: null,
    areaName: null,
  },
  locationType: null,
  xCoordinate: null,
  yCoordinate: null,
  zCoordinate: null,
  maxCapacity: null,
  currentCapacity: null,
  weightLimit: null,
  length: null,
  width: null,
  height: null,
  status: null,
  rfidAntennaId: null,
  lastInventoryTime: null,
  remark: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null
})

// 新增货架表单验证规则
const addRules = reactive({
  locationCode: [
    { required: true, message: "货架编码不能为空", trigger: "blur" }
  ],
  areaId: [
    { required: true, message: "所属库区ID不能为空", trigger: "blur" }
  ],
})

// 打开新增货架对话框
function handleAdd() {
  resetAddForm()
  addOpen.value = true
  addTitle.value = "添加货架信息"
}

// 关闭新增货架对话框
function handleAddCancel() {
  addOpen.value = false
  resetAddForm()
}

// 重置新增货架表单
function resetAddForm() {
  Object.assign(addForm, {
    locationId: null,
    locationCode: null,
    locationName: null,
    areaId: null,
    area: {
      areaId: null,
      areaName: null,
    },
    locationType: null,
    xCoordinate: null,
    yCoordinate: null,
    zCoordinate: null,
    maxCapacity: null,
    currentCapacity: null,
    weightLimit: null,
    length: null,
    width: null,
    height: null,
    status: null,
    rfidAntennaId: null,
    lastInventoryTime: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  })
  proxy.resetForm("locationRef")
}

// 打开库区选择对话框
function openAreaSelect() {
  areaDialogVisible.value = true
  if (areaSelectDialogRef.value) {
    areaSelectDialogRef.value.handleQuery()
  }
}

// 处理库区选择确认
function handleAreaConfirm(areas) {
  if (areas && areas.length > 0) {
    addForm.areaId = areas[0].areaId
    addForm.area.areaName = areas[0].areaName
  }
}

// 提交新增货架表单
function submitAddForm() {
  proxy.$refs["locationRef"].validate(valid => {
    if (valid) {
      addWmsLocation(addForm).then(response => {
        proxy.$modal.msgSuccess("新增成功")
        addOpen.value = false
        handleQuery() // 刷新货架列表
      })
    }
  })
}

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

defineExpose(exposeMethods)
</script>

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