<template>
  <el-card>
    <el-form :inline="true">
      <el-form-item label="库房名称" style="width: 200px">
        <el-select
            v-model="query.wareId"
            clearable
            filterable
            placeholder="请选择库房"
            @visible-change="handleWareVisible"
            @change="getAreaData"
        >
          <el-option
              v-for="item in wareOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="垛位分区" style="width: 200px">
        <el-select  placeholder="请选择区域" v-model="query.areaId">
                    <el-option
                        v-for="item in areaList"
                        :key="item.id"
                        :label="item.areaName"
                        :value="item.id"
                    />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getLayoutData">查询</el-button>
        <el-button type="info" @click="reset">重置</el-button>
<!--        <el-button type="success" @click="insertPartition">新增分区</el-button>-->
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <div style="display: flex;justify-content: space-between">
      <div class="switchB">
        <el-button @click="openBatchAddDialog" type="success">新增区块</el-button>
        <el-switch v-model="draggable" active-text="可拖动" inactive-text="" />
        <el-switch v-model="resizable" active-text="可调整大小" inactive-text="" />
      </div>
      <div>
        <el-button type="warning" @click="saveOrUpload">保存</el-button>
      </div>
    </div>
<!--    {{layout}}-->
    <GridLayout
        v-model:layout="layout"
        :col-num="colNum"
        :row-height="30"
        :is-draggable="draggable"
        :is-resizable="resizable"
    >
      <template #item="{ item }">
        <div class="item-container" @dblclick="startEditing(item)">
        <span
            v-if="!item.isEditing"
            class="text"
        >
          {{ item.name || item.i }}
        </span>
          <el-input
              v-else
              v-model="item.tempName"
              class="edit-input"
              size="small"
              @blur="finishEditing(item)"
              @keyup.enter="finishEditing(item)"
              @click.stop
          />
        </div>
        <span
            class="remove"
            @click.stop="removeItem(item.i)"
        >
        x
      </span>
      </template>
    </GridLayout>
  </el-card>
  <el-dialog
      v-model="batchAddDialogVisible"
      title="批量新增垛位"
      width="500px"
  >
    <el-form :model="batchAddForm" label-width="100px">
      <el-form-item label="新增数量">
        <el-input-number
            v-model="batchAddForm.count"
            :min="1"
            :max="100"
            controls-position="right"
        />
      </el-form-item>
      <el-form-item label="起始编号">
        <el-input-number
            v-model="batchAddForm.startFrom"
            :min="0"
            controls-position="right"
        />
      </el-form-item>
      <el-form-item label="前缀">
        <el-input
            v-model="batchAddForm.prefix"
            placeholder="请输入垛位前缀"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="batchAddDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="batchAddItems">确定</el-button>
      </span>
    </template>
  </el-dialog>

<!--  新增分区弹窗-->
<!--  <el-dialog-->
<!--      class="diaClass"-->
<!--      :close-on-click-modal="false"-->
<!--      draggable-->
<!--      title="新增"-->
<!--      v-model="partition"-->
<!--      width="40%"-->
<!--      top="5vh"-->
<!--  >-->
<!--      <el-form :model="partitionForm" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="partitionRules">-->
<!--        <el-row>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="所属库房" prop="wareId">-->
<!--              <el-select v-model="partitionForm.wareId" placeholder="请选择库房" style="width: 100%;">-->
<!--                <el-option-->
<!--                    v-for="item in wareOptions"-->
<!--                    :key="item.value"-->
<!--                    :label="item.label"-->
<!--                    :value="item.value"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="分区名称" prop="areaName">-->
<!--              <el-input v-model="partitionForm.areaName" maxlength="100" placeholder="请输入分区名称"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="分区编码" prop="areaCode">-->
<!--              <el-input v-model="partitionForm.areaCode" maxlength="50" placeholder="请输入分区编码"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--      </el-form>-->
<!--    <template #footer>-->
<!--      <div class="dialog-footer">-->
<!--        <el-button type="success" plain @click="handleInsert(ruleFormRef)">保存</el-button>-->
<!--        <el-button type="danger" plain @click="handleCancelSave">取消</el-button>-->
<!--      </div>-->
<!--    </template>-->
<!--  </el-dialog>-->

</template>

<script setup lang="ts">
import {getCurrentInstance, reactive, ref} from 'vue'
import {ElMessage} from "element-plus";
import axios from "axios";

const {proxy} = getCurrentInstance()
// ==========================================垛位操控======================================
let index = 0

const draggable = ref(true)
const resizable = ref(true)
const colNum = ref(12)

let layout = ref([
])

// 在 script setup 中添加批量新增相关变量
const batchAddDialogVisible = ref(false)
const batchAddForm = reactive({
  count: 1,
  startFrom: 0,
  prefix: '垛位'
})

// 批量新增方法
function batchAddItems() {
  if(query.value.wareId==''||query.value.areaId==''){
    return ElMessage.error('请选择库房和分区！')
  }

  if(batchAddForm.count <= 0) {
    return ElMessage.error('新增数量必须大于0')
  }

  for(let i = 0; i < batchAddForm.count; i++) {
    const newIndex = batchAddForm.startFrom + i
    layout.value.push({
      x: (newIndex * 2) % (colNum.value || 12),
      y: newIndex + (colNum.value || 12),
      w: 2,
      h: 2,
      i: `${batchAddForm.prefix}${newIndex}`,
      name: `${batchAddForm.prefix}${newIndex}`
    })
  }

  batchAddDialogVisible.value = false
  ElMessage.success(`成功新增 ${batchAddForm.count} 个垛位`)
}

// 打开批量新增对话框
function openBatchAddDialog() {
  if(query.value.wareId==''||query.value.areaId==''){
    return ElMessage.error('请选择库房和分区！')
  }
  batchAddDialogVisible.value = true
  batchAddForm.count = 1
  batchAddForm.startFrom = layout.value.length
  batchAddForm.prefix = '垛位'
}


// function addItem() {
//   if(query.value.wareId==''||query.value.areaId==''){
//     return ElMessage.error('请选择库房和分区！')
//   }
//   layout.value.push({
//     x: (layout.value.length * 2) % (colNum.value || 12),
//     y: layout.value.length + (colNum.value || 12), // puts it at the bottom
//     w: 2,
//     h: 2,
//     i: `${index++}`,
//   })
// }

function removeItem(id: string) {
  const index = layout.value.findIndex(item => item.i === id)

  if (index > -1) {
    layout.value.splice(index, 1)
  }
}
// ========================================查询=============================================
let query = ref({
  wareId: '',
  areaId:''
})
const reset = () => {
  query.value = {
    wareId: '',
    areaId:''
  }
  layout.value = []
  areaList.value = []
}
// ----------------------------查询库房列表------------------------------
const wareOptions = ref([])
const handleWareVisible = (visible) => {
  if (visible && wareOptions.value.length === 0) {
    fetchWareOptions()
  }
}
const fetchWareOptions = () => {
  proxy.$axios.get('sto/Ware/options', {}).then((response) => {
    if (response.data.code === 0 || response.data.code === '0') {
      wareOptions.value = toOptions(response.data.data, 'label', 'value')
    }
  })
}
const toOptions = (list, labelKey, valueKey) => (list || []).map((item) => {
      if (typeof item === 'string') {
        return {
          label: item,
          value: item
        }
      }
      return {
        label: item?.[labelKey] ?? item?.label ?? item?.name ?? item?.value ?? '',
        value: item?.[valueKey] ?? item?.value ?? item?.id ?? item?.code ?? item?.label ?? ''
      }
    }).filter((item) => item.label !== '' && item.value !== '')
// ----------------------------查询分区列表------------------------------
const areaList = ref([])
const getAreaData = () => {
  if(query.value.wareId==null || query.value.wareId==''){
    query.value.areaId = ''
  }
  const params = {
    page: 1,
    rows:99999,
    wareId: query.value.wareId,
    json: JSON.stringify(query.value)
  }
  proxy.$axios.get('sto/Area/query', params).then((response) => {
    if (response.data.code === 0) {
      areaList.value = response.data.data.records
      if(areaList.value.length==0){
        query.value.areaId = ''
      }
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
// ----------------------------查询垛位布局------------------------------
const getLayoutData = () => {
  if(query.value.wareId==''||query.value.areaId==''){
    return ElMessage.error('请选择库房和分区！')
  }
  proxy.$axios.get('sto/MaintStack/queryByWareIdAndAreaId', {
    wareId: query.value.wareId,
    areaId: query.value.areaId
  }).then((response) => {
    if (response.data.code === '0') {
      layout.value = response.data.data
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
// =========================================新增分区============================================
// let partition = ref(false)
// let partitionForm = ref({
//   wareId: '',
//   areaName: '',
//   areaCode: ''
// })
// const partitionRules = reactive({
//   wareId: [{ required: true, message: '请选择所属库房', trigger: 'change' }],
//   areaName: [{ required: true, message: '请输入分区名称', trigger: 'blur' }],
//   areaCode: [{ required: true, message: '请输入分区编码', trigger: 'blur' }]
// })
// const insertPartition = () => {
//   partition.value = true
// }
// ===========================================修改垛位名称=======================================
// 在 script setup 中添加编辑功能
function startEditing(item: any) {
  // 保存原始名称
  item.tempName = item.name || item.i
  item.isEditing = true
}

function finishEditing(item: any) {
  // 如果输入不为空，则更新名称
  if (item.tempName && item.tempName.trim()) {
    item.i = item.tempName.trim()
  }
  item.isEditing = false
}
// ==========================================保存=============================================
const saveOrUpload = () => {
  if(query.value.wareId==''||query.value.areaId==''){
    return ElMessage.error('请选择库房和分区！')
  }

  const requestData = {
    wareId: query.value.wareId,
    areaId: query.value.areaId,
    layoutStacks: layout.value
  }

  axios.post('sto/MaintStack/saveOrUpdateStack', requestData, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
      .then((response) => {
        if (response && response.data && response.data.code === '0') {
          ElMessage.success('操作成功！')
        } else {
          ElMessage.error('操作失败！' + (response?.data?.msg || '未知错误'))
        }
      })
      .catch((error) => {
        console.error('保存失败:', error);
        ElMessage.error('保存失败：' + (error.message || '网络错误'));
      })
}


</script>

<style scoped>
.vgl-layout {
  background-color: #eee;
  --vgl-resizer-border-color: #f15642;
}

:deep(.vgl-item:not(.vgl-item--placeholder)) {
  background-color: #ccc;
  border: 1px solid black;
}

:deep(.vgl-item--resizing) {
  opacity: 90%;
}

:deep(.vgl-item--static) {
  background-color: #cce;
}

.text {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  margin: auto;
  font-size: 24px;
  text-align: center;
}



.remove {
  position: absolute;
  top: 0;
  right: 2px;
  cursor: pointer;
}
.action-btn {
  position: absolute;
  cursor: pointer;
}
.switchB {
  margin: 15px;
  display: flex;
  justify-content: space-between;
  width: 26%;
}

.item-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.text {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  margin: auto;
  font-size: 24px;
  text-align: center;
  line-height: 100%; /* 让文字垂直居中 */
  cursor: pointer;
  user-select: none; /* 防止双击选中文本 */
}

.edit-input {
  position: absolute;
  width: 80%;
  height: 80%;
  z-index: 10;
  cursor: text;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}


</style>