<template>
  	<div id="manageTenantZone">
		<el-row style="margin:5px 0 0 0;">
			<el-button style="float:left;" size="small" type="default" icon="el-icon-back" @click="goback"></el-button>
			<floor-cascader @change="changeFloor"></floor-cascader>
			<my-cascader ref="cascader" @change="changeDevice"></my-cascader>
			<el-button type="primary" size="mini" @click="handleClickSave" style="float:right;">确认</el-button>
			<el-button size="mini" style="float:right;margin-right:10px;" @click="cancel">取消</el-button>
		</el-row>
		<el-row class="main-container">
			<el-row class="main-container-header">
				<el-select v-model="isPoint" @change="handleChangeIspoint" placeholder="请选择" style="width: 100px;margin-left: 10px;">
					<el-option v-for="item in isPointOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
				</el-select>
				<el-input
					style="width:250px;margin-left: 10px;"
					placeholder="请输入设备标识关键字"
					clearable
					suffix-icon="el-icon-search"
					@change="handleChangeKeyword"
					v-model="keyword"
				></el-input>
			</el-row>
			<el-row class="main-container-box">
				<el-col :span="3" class="container-box-left">
					<el-select v-model="showName" placeholder="请选择" style="width: 100%;">
						<el-option v-for="item in showNameOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
					</el-select>
					<div class="equip-list">
						<el-scrollbar style="height:100%;" v-show="equipList.length">
							<ul v-infinite-scroll="getEquipData" infinite-scroll-disabled="disabled">
								<li class="equip-item"
                                    v-for="item in equipList"
                                    :class="{'equip-item-selected': item.selected}"
                                    :key="item.EquipID"
                                    :title="item[showName]"
                                    @click="handleSelectIcon(item)"
                                >
									<p class="equip-item-text">{{item[showName] || '--'}}</p>
									<i v-if="item.hasLocation" class="iconfont icon-hook equip-item-icon" style="color: #67C23A;font-size: 14px;"></i>
									<i v-else class="iconfont icon-cross equip-item-icon" style="color: #ccc;font-size: 14px;"></i>
								</li>
								<p style="text-align: center;" v-if="loading">加载中...</p>
								<p style="text-align: center;" v-if="noMore">没有更多了</p>
							</ul>
						</el-scrollbar>
						<div v-show="!equipList.length" class="no-data">
							<div class="position-icon">
								<i class="icon-wushuju iconfont"></i>
								暂无数据
							</div>
						</div>
					</div>
				</el-col>
				<el-col id="canvasBox" class="container-box-right" :span="21" v-loading="canvasLoading">
					<div v-show="showCanvas" style="height: 100%;">
						<canvas :height="cadHeight" :width="cadWidth" id="floorCanvas" ref="graphy"></canvas>
					</div>
					<div class="no-data" v-show="!showCanvas">
						<div class="position-icon">
							<i class="icon-wushuju iconfont"></i>
							数据暂无
						</div>
					</div>
				</el-col>
			</el-row>
		</el-row>
        <el-popover ref='popover' placement='right' trigger='manual' v-model='visible' width='400'>
            <div style="text-align: right;margin-bottom: 10px;">
                <span style="float: left;">设定Z轴高度</span>
                <el-link icon="el-icon-close" :underline="false" @click="visible = false"></el-link>
            </div>
            <el-row>
                <p>距地面高度：{{equipZ}}mm</p>
            </el-row>
            <div class="elSlider">
                <el-slider v-model="equipZ" :max="maxHeight" :step="1" :marks="marks"></el-slider>
            </div>
            <el-row style="text-align: right;">
                <el-button size="mini" @click="visible = false">取消</el-button>
                <el-button type="primary" size="mini" @click="handleUpdateZ">确认</el-button>
            </el-row>
        </el-popover>
        <span class='popStyle' :style='popoverPosition' v-popover:popover></span>
  	</div>
</template>
<script>
import floorCascader from "@/components/ledger/lib/floorCascader";
import myCascader from "@/components/ledger/lib/cascader";
import { queryEquip, updateEquip } from '@/api/scan/request';
import { LocationPointScene, FloorView, Opt, SpaceItem, ZoneItem } from "@saga-web/cad-engine/lib";
import { SPoint } from "@saga-web/draw";
import { mapGetters } from "vuex";
import { SMathUtil } from "@saga-web/cad-engine/lib/utils/SMathUtil"
export default {
  components: {
    floorCascader,
    myCascader
  },
  data() {
    return {
        visible: false,
        equipZ: 0,
        maxHeight: 99000,
        popoverPosition: {
            top: 0,
            left: 0,
        },
        selectedIcon: null,
		buildId: "", //建筑Id
		floorId: "", //楼层Id
		floorMap: "", //楼层平面图地址
		floorOutline: null, //楼层平面图蒙版地址
		classCode: "", //设备类别
		isPoint: "all", //是否有坐标（全部-all、有坐标-yes、无坐标-no）
		keyword: "", //设备标识关键字
		showName: "EquipLocalName", //显示名称
		isIndeterminate: false, //全选样式显示
		checkAll: false, //是否全选
		checkedEquip: [], //选中的设备
		cadWidth: 800,
		cadHeight: 800,
		view: "",
      	scene: null,
		showCanvas: false, //是否有底图数据
		canvasLoading: false,
		isPointOptions: [{
          value: "all",
          label: "全部"
        }, {
          value: "yes",
          label: "有坐标"
        }, {
          value: "no",
          label: "无坐标"
		}],
		showNameOptions: [{
          value: "EquipLocalName",
          label: "显示设备本地名称"
        }, {
          value: "EquipLocalID",
          label: "显示设备本地编码"
        }, {
          value: "CADID",
          label: "显示图纸编码"
		}],
        equipList: [],
        marks: {
            0: '本层地面',
            99000: '本层屋顶'
        },
		loading: false,
		pageNumber: 1,
		pageSize: 50,
        total: 0,
        isChange: false, //平面图设备是否更改
        isMarking: false, // 标记是否选中的是无坐标的设备,true-打点,打完以后重置为false
	};
  },
  computed: {
	...mapGetters("layout", ["projectId", "projects"]),
	noMore () {
		return this.equipList.length >= this.total
	},
	disabled () {
		return this.loading || this.noMore
	}
  },
  created() {},
  mounted() {
    this.cadWidth = document.getElementById('canvasBox').offsetWidth;
    this.cadHeight = document.getElementById('canvasBox').offsetHeight;
    // 添加监听点击事件,处理popover显隐
    window.addEventListener('click', this.handlePopover, false)
    this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('click', this.handlePopover)
    })
  },
  methods: {
    // 返回
    goback() {
        this.confirm(() => {
            this.$router.push({ name: "facilityLedger" });
        })
    },
    // 二次确认
    confirm(callback) {
        if (this.isChange) {
            this.$confirm('平面图数据未保存，此操作将不会保存修改数据！', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                callback();
            });
        } else {
            callback();
        }
    },
    // 点击列表设备
    handleSelectIcon(equip) {
        // 保存当前选中设备数据
        this.equipData = equip;
        // 选中样式处理
        this.equipList.forEach(item => {
            if (equip.EquipID === item.EquipID) {
                item.selected = true;
            } else {
                item.selected = false;
            }
        })
        // 有坐标 执行选中
        if (equip.hasLocation) {
            // 清除打点动作
            this.isMarking = false;
            // 关联平面图设备选中
            if (this.scene) {
                this.scene.iconList.forEach(item => {
                    if (item.data.id === equip.EquipID) {
                        this.scene.selectContainer.setItem(item);
                    }
                })
            }
        } else {
            // 无坐标 执行打点
            this.isMarking = true;
        }
    },
    handleClickIcon(item, events) {
        const e = events[0];
        this.selectedIcon = item;
        if (item.data.Z) {
            this.equipZ = (item.data.Z);
        } else {
            this.equipZ = 0;
        }
        this.visible = false
        this.$nextTick(() =>{
            this.popoverPosition.top = `${e.clientY}px`;
            this.popoverPosition.left = `${e.clientX}px`;
            this.visible = true;
        })
    },
    // 修改设备Z坐标
    handleUpdateZ() {
        if (this.selectedIcon.data.Z !== this.equipZ) {
            this.selectedIcon.data.Z = this.equipZ;
            this.isChange = true;
            this.visible = false;
            try {
                const str = this.selectedIcon.textItemList[0].text.split('\n');
                str[2] = this.equipZ
                this.selectedIcon.textItemList[0].text = str.join('\n');
            } catch (e) {
                console.log(e);
            }
        }
    },
    listChange(item, ev) {
        if (!ev[0].length) {
            this.visible = false;
            this.selectedIcon = null;
        }
    },
    /**
     * @description 处理popover显隐
     * 当点击位置不在canvas内部时 ( 如点击 页面空白,图例,楼层,设备设施左侧列表项时),将visible置为false,隐藏popover
     */
    handlePopover(e) {
        this.$nextTick(() => {
            if (!this.$refs.graphy.contains(e.target)) {
                this.visible = false
            }
        })
    },
	//获取所以主体数据---用于维护信息
	getEquipData() {
		if (this.classCode && this.floorId && (this.floorId != "noKnow" || this.floorId != "all")) {
			this.loading = true;
			let params = {
				Filters: `category='${this.classCode}'`,
				PageSize: this.pageSize,
				Orders: 'createTime desc, EquipID desc',
				PageNumber: this.pageNumber,
				Projection: ['Category', 'EquipLocalName', 'EquipLocalID', 'EquipID', 'BIMID', 'CADID', 'LocationJson', 'BIMLocation'],
			}
			if (this.buildId == 'noKnow') {
				params.Filters += `;buildingId isNull`
			} else if (this.buildId && this.buildId != 'all') {
				params.Filters += `;buildingId='${this.buildId}'`
			}

			if (this.floorId == 'noKnow') {
				params.Filters += `;floorId isNull`
			} else if (this.floorId && this.floorId != 'all') {
				params.Filters += `;floorId='${this.floorId}'`
			}

			if (this.isPoint == "yes") {
				params.Filters += `;not BIMLocation isNull`
			} else if (this.isPoint == "no") {
				params.Filters += `;BIMLocation isNull`
			}

			if (this.keyword) {
				params.Filters += `;EquipLocalName contain'${this.keyword}' or EquipLocalID contain '${this.keyword}' or CADID contain '${this.keyword}'`
			}

	        this.canvasLoading = true;
			queryEquip(params, (res) => {
				this.equipList = this.equipList.concat(res.Content.map(item => {item.selected = false; item.hasLocation = !!item.BIMLocation; return item;}));
				if (this.view && this.view.scene) {
					res.Content.forEach(item =>{
						if (item.LocationJson && item.LocationJson.X && item.LocationJson.Y) {
                            this.scene.addIconText({
                                id: item.EquipID,
                                X: item.LocationJson.X, 
                                Y: -item.LocationJson.Y, 
                                Z: item.LocationJson.Z,
                                text: [`${item.EquipLocalName || '--'}\n${item.EquipLocalID || '--'}\n${item.LocationJson.Z || '--'}`]
                            });
						}
                    });
                    this.scene.iconMove(this, this.iconMove);
                    this.scene.spaceClick(this, this.spaceClick);
                    this.scene.iconChangeText(this, this.handleClickIcon);
					this.view.update();
                    this.canvasLoading = false;
                    this.isChange = false;
				}
				this.total = res.Total;
				if (!this.noMore) { //判断是否有更多数据
					this.pageNumber++;
				}
				this.loading = false;
			})
		}
    },
    //设备移动回调
    iconMove(item) {
        this.isChange = true;
    },
    // 打点
    spaceClick(item, e) {
        if (this.isMarking) {
            this.scene.addIconText({
                id: this.equipData.EquipID,
                X: e[0].x, 
                Y: e[0].y, 
                Z: 0,
                text: [`${this.equipData.EquipLocalName || '--'}\n${this.equipData.EquipLocalID || '--'}\n0`]
            });
            // 保存按钮
            this.isChange = true;
            // 设置有坐标标识
            this.equipData.hasLocation = true;
            // 绑定事件
            this.scene.iconChangeText(this, this.handleClickIcon)
            // 重置打点动作
            this.isMarking = false;
        }
        // 取消选中状态
        this.scene && this.scene.selectContainer.clear()
    },
	//初始化条件并查询设备
	initParams() {
		this.pageNumber = 1;
		this.total = 0;
		this.equipList = [];
        this.clearIcon();
        if (this.view) {
            this.view.update();
        }
		this.getEquipData();
	},
    //修改楼层
    changeFloor(value, data) {
        this.floorData = data;
		this.showCanvas = false;
		this.clearGraphy();
		if (value[0]) {
			this.buildId = value[0];
		}
		if (value[1]) {
			this.floorId = value[1];
		} else {
			this.floorId = "";
		}
		if (data.StructureInfo && data.StructureInfo.FloorMap) {
			this.floorMap = data.StructureInfo.FloorMap;
			this.showCanvas = true;
			this.getGraphy();
		} else {
			this.initParams();
			this.floorMap = "";
        }
        if (data.StructureInfo && data.StructureInfo.Height) {
            this.maxHeight = data.StructureInfo.Height;
        } else {
            this.maxHeight = 99000;
        }
		if (data.Outline && data.Outline.length) {
			this.floorOutline = data.Outline;
		} else {
			this.floorOutline = null;
		}
	},
    //修改设备族
    changeDevice(value) {
		if (value.code) {
			this.classCode = value.code;
		} else {
			this.classCode = "";
		}
		this.initParams();
	},
	//切换是否有坐标
	handleChangeIspoint() {
		this.initParams();
	},
	//检索关键字
	handleChangeKeyword() {
		this.initParams();
    },
    // 保存数据
    handleClickSave() {
        if (this.scene && this.scene.iconList.length) {
            let param = {Content: []}
            this.scene.iconList.map((item) => {
                if (item.data.id) {
                    param.Content.push({
                        EquipID: item.data.id,
                        BIMLocation: `${item.x},${-item.y},${item.data.Z}`
                    })
                }
            })
            updateEquip(param, () => {
                this.isChange = false
                this.$message({message: '保存成功！', type: 'success'});
            })
        }
    },
	// 获取底图
    getGraphy() {
      this.scene = new LocationPointScene();
      this.scene.selectContainer.connect('listChange', this, this.listChange)
      this.canvasLoading = true;
      const temp = this.floorMap.split('.')[1];
      if (temp && temp.toString().toLowerCase() == 'png' || temp.toString().toLowerCase() == 'jpg') {
        let x = 0;
        let y = 0;
        let scale = 1;
        if (this.floorData && this.floorData.Properties) {
            x = this.floorData.Properties.X;
            y = this.floorData.Properties.Y;
            const pro = this.floorData.Properties;
            const dis = SMathUtil.pointDistance(pro.Line[0].x, pro.Line[0].y, pro.Line[1].x, pro.Line[1].y)
            const proText = pro.Text.substring(0, pro.Text.length - 3);
            scale = proText / dis;
        }
        this.scene.loadImg(`/image-service/common/image_get?systemId=dataPlatform&key=${this.floorMap}`, res => {
          this.getGraphtSuc(res)
        }, x, y, scale)
      } else {
        this.scene.loadUrl(`/image-service/common/file_get?systemId=revit&key=${this.floorMap}`).then(res => {
          this.getGraphtSuc(res)
        })
      }
	},
	getGraphtSuc(res) {
	  this.initParams();
      this.canvasLoading = false;
      if (res == 'error') {
        this.FloorMap = '';
        this.$message.warning('数据解析异常');
        return;
      }
      this.view.scene = this.scene;
      // 蒙版
      if (this.floorOutline) {
        let newArr = this.floorOutline.map(t => {
          return new SPoint(t.X, t.Y);
        })
        this.scene.addSceneMark(newArr)
      }
	  this.scene.isSpaceSelectable = false;
	  this.view.fitSceneToView();
    //   this.view.minScale = this.view.scale;
    //   if (this.$refs.canvasFun) {
    //     this.$refs.canvasFun.everyScale = this.view.scale;
	//   }
    },
	//清空平面图
    clearGraphy() {
      if (this.view) {
        this.view.scene = null;
        return
	  }
      this.view = new FloorView("floorCanvas");
	},
	//清空标记
	clearIcon() {
        if (this.scene)
        this.scene.clearIcon();
    },
    // 取消操作
    cancel() {
        this.initParams();
    }
  },
  watch: {
    projectId() {
      this.$router.push({ name: "facilityLedger" });
    }
  }
};
</script>
<style lang="less" scoped>
@normal-border-color: #e4e4e4;
@normal-border-active-color: #e8e8e8;
#manageTenantZone {
  position: relative;
  height: 100%;
  .main-container {
    margin-top: 10px;
    background: #fff;
    border: 1px solid @normal-border-color;
    height: calc(100% - 53px);
	overflow: hidden;
	.main-container-header {
		padding: 10px 0;
		border-bottom: 1px solid @normal-border-color;
	}
	.main-container-box {
		height: calc(100% - 53px);
		.container-box-left {
			height: 100%;
			border-right: 1px solid @normal-border-color;
			/deep/ .el-input__inner {
				border: none;
				border-bottom: 1px solid #DCDFE6;
				border-radius: 0;
			}
			.equip-list {
				height: calc(100% - 32px);
				/deep/ .el-scrollbar__wrap {
					overflow-x: hidden;
				}
				.equip-item {
					padding-left: 15px;
					padding-right: 10px;
					width: 100%;
					height: 32px;
					line-height: 32px;
					box-sizing: border-box;
					cursor: pointer;
					.equip-item-text {
						display: inline-block;
						width: calc(100% - 20px);
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
					.equip-item-icon {
						float: right;
					}
                }
                .equip-item-selected {
                    background-color: #f5f7fa;
                }
				.equip-item:hover {
					background-color: #f5f7fa;
				}
			}
		}
		.container-box-right {
			height: 100%;
		}
	}
  }
  .popStyle {
    position: fixed;
  }
}
.elSlider{
    padding: 10px 24px;
    margin-bottom:15px;
    /deep/ .el-slider__marks-text:nth-child(2) {
        width: 80px;
    }
}
.no-data {
	height: 100%;
	text-align: center;
	box-sizing: border-box;
	position: relative;
	.position-icon {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}
}
</style>
