<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>
			<div id="buildFloor">
                <span class="buildFloor">建筑楼层</span>
                <el-cascader ref="floorCascader" placeholder="请选择" :props="props" :options="bfOptions" filterable size="small" @change="changeFloor"></el-cascader>
            </div>
			<my-cascader ref="cascader" @change="changeDevice"></my-cascader>
			<el-button type="primary" size="mini" @click="handleClickSave" :disabled="!isChange" 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.id"
                                    :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" :min="minHeight" :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, buildingQuery } from '@/api/scan/request';
import { LocationPointScene, FloorView, Opt, SpaceItem, ZoneItem } from "@saga-web/cad-engine/lib";
import { SPoint, SColor } 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,
        minHeight: -99000,
        popoverPosition: {
            top: 0,
            left: 0,
        },
        selectedIcon: null,
		buildId: "", //建筑Id
		floorId: "", //楼层Id
		floorMap: "", //楼层平面图地址
		floorOutline: null, //楼层平面图蒙版地址
		classCode: "", //设备类别
		isPoint: "all", //是否有坐标（全部-all、有坐标-yes、无坐标-no）
		keyword: "", //设备标识关键字
		showName: "localName", //显示名称
		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: "localName",
          label: "显示设备本地名称"
        }, {
          value: "localId",
          label: "显示设备本地编码"
        }, {
          value: "cADID",
          label: "显示图纸编码"
		}],
        equipList: [],
        marks: {
            0: '本层地面',
            99000: '本层屋顶'
        },
		loading: false,
		pageNumber: 1,
		pageSize: 50,
        total: 0,
        isChange: false, //平面图设备是否更改
        isMarking: false, // 标记是否选中的是无坐标的设备,true-打点,打完以后重置为false
        props: {
            value: 'id',
            label: 'localName',
            children: 'floor'
        }, // 建筑楼层字段绑定
        bfOptions: [], // 建筑楼层下拉
        fIdToFloor: {}, // 楼层id映射楼层对象
	};
  },
  computed: {
	...mapGetters("layout", ["projectId", "projects"]),
	noMore () {
		return this.equipList.length >= this.total
	},
	disabled () {
		return this.loading || this.noMore
	}
  },
  created() {
      this.getCascader()
  },
  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" });
        })
    },
    getCascader() {
      let param = {
        cascade: [
          { name: "floor", orders: "floorSequenceID desc" }
        ],
        orders: "localName asc",
        pageNumber: 1,
        pageSize: 50
      }
      buildingQuery(param, res => {
        this.fIdToFloor = {}
        this.bfOptions = res.content.map(t => {
            if (t.floor && t.floor.length) {
                 t.floor = t.floor.map(item => {
                    this.fIdToFloor[item.id] = item;
                    return item
                }).filter(it => it)
            }
            return t
        })
      })
    },
    // 二次确认
    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.id === item.id) {
                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.id) {
                        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: `classCode='${this.classCode}'`,
				pageSize: this.pageSize,
				orders: 'createTime desc, id desc',
				pageNumber: this.pageNumber
			}
			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 += `;localName contain'${this.keyword}' or localId 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.id,
                                X: item.locationJson.x, 
                                Y: -item.locationJson.y, 
                                Z: item.locationJson.z,
                                text: [`${item.localName || '--'}\n${item.localId || '--'}\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) {
            const p = item.mapToScene(e[0].x, e[0].y)
            this.scene.addIconText({
                id: this.equipData.id,
                X: p.x, 
                Y: p.y, 
                Z: 0,
                text: [`${this.equipData.localName || '--'}\n${this.equipData.localId || '--'}\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) {
		this.showCanvas = false;
		this.clearGraphy();
		if (value[0]) {
			this.buildId = value[0];
		}
		if (value[1]) {
			this.floorId = value[1];
            this.floorData = this.fIdToFloor[value[1]];
		} else {
			this.floorId = "";
            this.floorData = {}
        }
		if (this.floorData.infos && this.floorData.infos.floorMap) {
			this.floorMap = this.floorData.infos.floorMap;
			this.showCanvas = true;
			this.getGraphy();
		} else {
			this.initParams();
			this.floorMap = "";
        }
        if (this.floorData.infos && this.floorData.infos.height) {
            this.maxHeight = this.floorData.infos.height;
            this.minHeight = -(this.floorData.infos.height);
        } else {
            this.maxHeight = 99000;
            this.minHeight = -99000;
        }
		if (this.floorData.outline && this.floorData.outline.length) {
			this.floorOutline = this.floorData.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 && this.isChange) {
            this.isChange = false
            let param = {content: []}
            this.scene.iconList.map((item) => {
                if (item.data.id) {
                    param.content.push({
                        id: item.data.id,
                        bimLocation: `${item.x},${-item.y},${item.data.Z}`
                    })
                }
            })
            updateEquip(param, () => {
                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.infos && this.floorData.infos.floorMapRatio && this.floorData.infos.floorMapShift) {
            const point = JSON.parse(this.floorData.infos.floorMapShift);
            x = point.x;
            y = point.y;
            scale = this.floorData.infos.floorMapRatio;
        }
        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 = '';
        console.log('数据解析异常');
        return;
      }
      this.view.scene = this.scene;
      // 蒙版
      if (this.floorOutline) {
        Opt.sceneMarkColor = new SColor('#ffffff');
        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%;
  #buildFloor{
    margin-left: 10px;
    float: left;
    .buildFloor {
        color: #999999;
        font-size: 14px;
        margin-right: 12px;
    }
  }
  .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>
