<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :model="query" label-width="auto" label-position="right">
        <el-row :gutter="10">
          <el-col :span="5">
            <el-form-item label="所属库房" style="margin-bottom: 0px;">
              <el-select
                v-model="queryWare"
                placeholder="请选择库房"
                clearable
                style="width: 100%;"
                @change="change"
                @clear="clear"
              >
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="名称/编码" style="margin-bottom: 0px;">
              <el-input v-model="query" clearable placeholder="请输入名称或编码" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="" style="margin-bottom: 0px; margin-top: 5px;">
              <el-button type="primary" @click="search">查询</el-button>
              <el-button type="success" @click="handleAdd">新增</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

<!--    <el-card :body-style="cardBodyStyle" v-show="isShowLayout">-->
<!--      <div id="wareLayout" style="margin: 10px; width: 600px; height: 300px; background-color: #00FFFF;"></div>-->
<!--    </el-card>-->

    <el-card :body-style="cardBodyStyle">
      <el-table v-loading="loading" :data="tableData" border highlight-current-row>
        <el-table-column type="index" label="序号" align="center" width="60">
          <template #default="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="wareName" label="所属库房" width="120" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="name" label="垛位名称" width="120" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="code" label="垛位编码" width="120" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="stackX" label="起始X" width="120" header-align="center" align="center" />
        <el-table-column prop="stackY" label="起始Y" width="120" header-align="center" align="center" />
        <el-table-column prop="width" label="垛位长度" width="120" header-align="center" align="center" />
        <el-table-column prop="height" label="垛位宽度" width="120" header-align="center" align="center" />
        <el-table-column prop="isLayer" label="是否分层" width="120" header-align="center" align="center" :formatter="typeFormatter" />
        <el-table-column label="操作" header-align="center" align="center" width="200" fixed="right">
          <template #default="scope">
            <el-button plain type="warning" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button plain type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card :body-style="cardBodyStyle">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        :total="totalRows"
        background="background"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog
      class="diaClass"
      :close-on-click-modal="false"
      draggable
      :title="stack.id ? '编辑' : '新增'"
      v-model="dialogVisible"
      width="40%"
      top="5vh"
    >
      <el-card :body-style="cardBodyStyle">
        <el-form :model="stack" label-width="120px" label-position="right" inline>
          <el-row>
            <el-col :span="12">
              <el-form-item label="所属库房">
                <el-select v-model="stack.wareId" clearable placeholder="请选择库房" style="width: 100%;">
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="垛位名称">
                <el-input v-model="stack.name" maxlength="100" placeholder="请输入垛位名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="垛位编码">
                <el-input v-model="stack.code" maxlength="50" placeholder="请输入垛位编码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="起始X">
                <el-input v-model.number="stack.stackX" type="number" placeholder="请输入起始X"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="起始Y">
                <el-input v-model.number="stack.stackY" type="number" placeholder="请输入起始Y"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="垛位长度">
                <el-input v-model.number="stack.width" type="number" placeholder="请输入垛位长度"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="垛位宽度">
                <el-input v-model.number="stack.height" type="number" placeholder="请输入垛位宽度"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="是否分层">
                <el-radio-group v-model="stack.isLayer">
                  <el-radio label="0">不分层</el-radio>
                  <el-radio label="1">自动分层</el-radio>
                  <el-radio label="2">手动分层</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" plain @click="handleSave">保存</el-button>
          <el-button type="danger" plain @click="handleCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
	import axios from '@/axios'
	// import zrender from 'zrender'
	// import {
	// 	mapState
	// } from 'vuex'
	import tools from '@/tools'

	export default {
		computed: {
			// ...mapState({
			// 	wareBackgroundColor: state => state.color.wareBackgroundColor,
			// 	stackColor: state => state.color.stackColor,
			// 	stackSelectedColor: state => state.color.stackSelectedColor
			// }),
			cardBodyStyle() {
				return tools.style.card
			}
		},
		components: {

		},
		data() {
			return {
				//表格初始化参数
				tableData: [],
				currentPage: 1,
				totalRows: 0,
				pageSizes: [ 10, 20, 30, 40],
				pageSize: 10,
				//查询条件
				query: '',
				queryWare: '',
				queryByWareId: '',
				//录入框
				dialogVisible: false,
				stack: {
					id: '',
					name: '',
					code: '',
					wareId: '',
					stackX: 0,
					stackY: 0,
					width: 0,
					height: 0,
					isLayer: "0"
				},
				isShow: false,
				isShowLayout: false,
				loading: true,
				options: [],
				maintStackLayout: {},
				isMouseDown: false,
				isChild: false,
				rectNew: {},
				startX: 0,
				startY: 0,
				rectSelect: {},
				stackSelect: {},
				disX: 0,
				disY: 0,
			}
		},
		//界面渲染完毕调用   初始化表格参数
		mounted() {
			this.getTableData()
			this.getAllWare()
		},
		// 组件销毁时清理资源
		beforeDestroy() {
			if (this.maintStackLayout && this.maintStackLayout.dispose) {
				this.maintStackLayout.dispose()
			}
		},
		methods: {
			typeFormatter: function(row, column) {
				switch (row.isLayer) {
					case "0":
						return "不分层";
						break;
					case "1":
						return "自动分层";
						break;
					case "2":
						return "手动分层";
						break;
				}
			},
			// 获取table数据
			getTableData() {
				this.loading = true
				var url = 'sto/MaintStack/query.do'
				this.queryByWareId = this.queryWare
				var param = {
					page: this.currentPage,
					rows: this.pageSize,
					query: this.query,
					queryWare: this.queryByWareId
				}
				axios.get(url, param).then(response => {
					if (response.data.code == 0) {
						this.tableData = response.data.data.records
						this.totalRows = response.data.data.total
					} else {
						this.$message({
							type: 'error',
							message: '查询失败：' + response.data.msg,
						});
					}
					this.loading = false
				}).catch(error => {
					this.$message({
						type: 'error',
						message: '查询失败：' + error.message,
					});
					this.loading = false
				});
			},
			getAllWare() {
				var url = 'sto/Ware/options'
				var param = {}
				axios.get(url, param).then(response => {
					if (response.data.code == 0) {
						this.options = response.data.data || []
					} else {
						this.$message({
							type: 'error',
							message: '获取库房选项失败：' + response.data.msg,
						});
					}
				}).catch(error => {
					this.$message({
						type: 'error',
						message: '获取库房选项失败：' + error.message,
					});
				});
			},
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageSize = val
				this.getTableData()
			},
			// 修改当前页事件
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.currentPage = val
				this.getTableData()
			},
			//保存按钮事件
			handleSave() {
				var tempStack = JSON.parse(JSON.stringify(this.stack));
				// 从 options 中找到对应的库房名称
				var wareOption = this.options.find(item => item.id === tempStack.ware.id);
				if (wareOption) {
					tempStack.ware.name = wareOption.name;
				} else {
					tempStack.ware.name = tempStack.ware.id;
				}
				var json = JSON.stringify(tempStack)
				var url = 'sto/MaintStack/save.do'
				var param = {
					json: json
				}
				this.loading = true
				axios.post(url, param).then(response => {
					if (response.data.code == 0) {
						this.$message({
							type: 'success',
							message: '保存成功!',
						});
						this.getTableData()
						if (this.queryWare) {
							// this.getAllStackByWareName(this.queryWare)
						}
						this.dialogVisible = false
						this.loading = false
					} else {
						this.$message({
							type: 'error',
							message: '保存失败：' + response.data.msg,
						});
						this.loading = false
					}
				}).catch(error => {
					this.$message({
						type: 'error',
						message: '保存失败：' + error.message,
					});
					this.loading = false
				});
			},
			//保存取消按钮事件   关闭编辑对话框
			handleCancelSave(row) {
				this.dialogVisible = false
			},
			// 新增按钮事件
			handleAdd() {
				// 从 options 中找到对应的库房名称
				var wareName = '';
				if (this.queryWare) {
					var wareOption = this.options.find(item => item.id === this.queryWare);
					wareName = wareOption ? wareOption.name : this.queryWare;
				}
				this.dialogVisible = true
				this.stack = {
					id: '',
					name: '',
					code: '',
					ware: {
						id: this.queryWare || '',
						name: wareName
					},
					stackX: 0,
					stackY: 0,
					width: 0,
					height: 0,
					isLayer: "0"
				}
			},
			// 编辑按钮事件
			handleEdit(row) {
				var tempRow = JSON.parse(JSON.stringify(row));
				// 确保 ware 对象存在
				if (!tempRow.ware) {
					tempRow.ware = { id: '', name: '' };
				}
				this.dialogVisible = true
				this.stack = tempRow
			},

			// 删除按钮事件
			handleDelete(id) {
				this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {

					var url = 'sto/MaintStack/remove.do'
					var param = {
						id: id
					}
					axios.post(url, param).then(response => {
						if (response.data.code == 0) {
							this.$message({
								type: 'success',
								message: '删除成功!',
							});
							this.getTableData()
						} else {
							this.$message({
								type: 'error',
								message: '删除失败;' + response.data.msg
							});
						}
					});
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			// 查询按钮事件
			search() {
				this.currentPage = 1
				this.getTableData()
			},
			change(val) {
				//console.log("change(val)"+val)

				if (val != '') {
					this.isShowLayout = true
					this.getTableData()
					// this.getAllStackByWareName(val)
				}
			},
			clear() {
				this.isShowLayout = false
			},
			// getAllStackByWareName(val) {
			// 	var url = 'sto/MaintStack/queryByWareId.do'
			// 	var param = {
			// 		wareId: val
			// 	}
			// 	axios.get(url, param).then(response => {
			// 		if (response.data.code == 0) {
			// 			this.drawWareLayout(response.data.data)
			// 		} else {
			// 			this.$message({
			// 				type: 'error',
			// 				message: '获取垛位布局失败：' + response.data.msg,
			// 			});
			// 		}
			// 	}).catch(error => {
			// 		this.$message({
			// 			type: 'error',
			// 			message: '获取垛位布局失败：' + error.message,
			// 		});
			// 	});
			// },

			// drawWareLayout(data) {
			// 	// 如果已经初始化过，先清空
			// 	if (this.maintStackLayout && this.maintStackLayout.dispose) {
			// 		this.maintStackLayout.dispose()
			// 	}
			// 	// 重置状态
			// 	this.isMouseDown = false
			// 	this.isChild = false
			// 	this.maintStackLayout = zrender.init(document.getElementById('wareLayout'))
			// 	this.maintStackLayout.on('mousedown', (e) => {
			// 		this.isMouseDown = true
			// 		var startX = 0
			// 		var endX = 0
			// 		var startY = 0
			// 		var endY = 0
			// 		var width = 0
			// 		var height = 0
			// 		for (let i = 0; i < this.maintStackLayout.storage._roots.length; i++) {
			// 			startX = this.maintStackLayout.storage._roots[i].shape.x
			// 			startY = this.maintStackLayout.storage._roots[i].shape.y
			// 			endX = this.maintStackLayout.storage._roots[i].shape.x + this.maintStackLayout.storage._roots[i].shape.width
			// 			endY = this.maintStackLayout.storage._roots[i].shape.y + this.maintStackLayout.storage._roots[i].shape.height
			// 			width = this.maintStackLayout.storage._roots[i].shape.width
			// 			height = this.maintStackLayout.storage._roots[i].shape.height
			// 		if (e.offsetX >= startX && e.offsetX <= endX && e.offsetY >= startY && e.offsetY <= endY) {
			// 			console.log(i)
			// 			this.isChild = true
			// 			this.rectSelect = this.maintStackLayout.storage._roots[i]
			// 			this.stackSelect = JSON.parse(JSON.stringify(data[i]))
			// 			this.disX = e.offsetX - this.rectSelect.shape.x
			// 			this.disY = e.offsetY - this.rectSelect.shape.y
			// 			break
			// 		}
			// 		}

			// 		if (this.isChild) {
			// 			console.log("click rect:" + this.isChild)
			// 		} else {

			// 			this.startX = e.offsetX
			// 			this.startY = e.offsetY
			// 			this.rectNew = new zrender.Rect({
			// 				shape: {
			// 					x: e.offsetX, //data[i].stackX * 600 / data[i].ware.width,
			// 					y: e.offsetY, //data[i].stackY * 300 / data[i].ware.height,
			// 					width: 1, // data[i].width * 600 / data[i].ware.width,
			// 					height: 1, //data[i].height * 300 / data[i].ware.height,
			// 				},
			// 				style: {
			// 					text: 'A', //data[i].name,
			// 					textAlign: 'center',
			// 					textVerticalAlign: 'middle',
			// 					fill: this.stackColor,
			// 					stroke: '#000000',
			// 				},
			// 			})
			// 			this.maintStackLayout.add(this.rectNew);
			// 		}

			// 	});
			// 	this.maintStackLayout.on('mousemove', (e) => {

			// 		if (this.isMouseDown) {

			// 			if (this.isChild) {
			// 				//console.log(" this.rectSelect.shape.x：" + this.rectSelect.shape.x)
			// 				this.rectSelect.attr('shape', {
			// 					x: e.offsetX - this.disX,
			// 					y: e.offsetY - this.disY
			// 				})
			// 			} else {
			// 				var width = e.offsetX - this.startX
			// 				var height = e.offsetY - this.startY
			// 				this.rectNew.attr('shape', {
			// 					width: width,
			// 					height: height
			// 				})
			// 			}
			// 		}

			// 	});
			// 	this.maintStackLayout.on('mouseup', (e) => {
			// 		this.isMouseDown = false
			// 		if (this.isChild) {
			// 			this.stackSelect.stackX = e.offsetX - this.disX
			// 			this.stackSelect.stackY = e.offsetY - this.disY
			// 			//
			// 			this.stack = this.stackSelect
			// 			console.log(JSON.stringify(this.stack))
			// 			this.handleSave()
			// 		} else {
			// 			var width = e.offsetX - this.startX
			// 			var height = e.offsetY - this.startY
			// 			this.dialogVisible = true
			// 			this.stack = {
			// 				id: '',
			// 				name: '',
			// 				code: '',
			// 				ware: {
			// 					id: this.queryWare,
			// 					name: this.queryWare
			// 				},
			// 				stackX: this.startX,
			// 				stackY: this.startY,
			// 				width: width,
			// 				height: height,
			// 				isLayer: "0"
			// 			}
			// 		}
			// 		this.isChild = false
			// 	});
			// 	for (let i = 0; i < data.length; i++) {
			// 		this.rectNew = new zrender.Rect({
			// 			shape: {
			// 				x: data[i].stackX, // * 600 / data[i].ware.width,
			// 				y: data[i].stackY, //* 300 / data[i].ware.height,
			// 				width: data[i].width, //* 600 / data[i].ware.width,
			// 				height: data[i].height, //* 300 / data[i].ware.height,
			// 			},
			// 			style: {
			// 				text: data[i].name,
			// 				textAlign: 'center',
			// 				textVerticalAlign: 'middle',
			// 				fill: this.stackColor,
			// 				stroke: '#000000',

			// 			}
			// 		})
			// 		// rect.on('mousedown', (e) => {
			// 		// 	this.isMouseDown = true
			// 		// })
			// 		// rect.on('mousemove', (e) => {
			// 		// 	if (this.isMouseDown) {
			// 		// 		 var disX = e.offsetX - e.target.shape.x
			// 		// 		 var disY = e.offsetY - e.target.shape.y
			// 		// 		e.target.attr('shape', {
			// 		// 			x: e.target.offsetX +disX,
			// 		// 			y: e.target.offsetY+disY
			// 		// 		})
			// 		// 	}
			// 		// });
			// 		// rect.on('mouseup', (e) => {
			// 		// 	this.isMouseDown = false
			// 		// })
			// 		this.maintStackLayout.add(this.rectNew);
			// 	}
			// },

		}
	}
</script>
<style scoped>
::v-deep .diaClass .el-form-item {
  width: 100%;
}
::v-deep .el-autocomplete {
  width: 100%;
}
::v-deep .el-dialog__body {
  background-color: #F2F6FC;
}
.el-select-dropdown .el-scrollbar .el-scrollbar__wrap {
  overflow: scroll !important;
}
</style>