<template>
  <transition name="el-zoom-in-center">
    <div class="mapPaint">
      <div class="map-view">
        <jlmap-visual ref="jlmapVisual" @onSelect="clickEvent" @onMenu="onContextmenu" />
      </div>
      <div class="map-draft">
        <div v-if="viewDraft==='draft'">
          <map-operate
            ref="mapOperate"
            :card-height="cardHeight"
            :map-info="mapInfo"
            :selected="selected"
            :map-saveing="mapSaveing"
            @handleSelectLogicalView="handleSelectLogicalView"
            @handleSelectPhysicalView="handleSelectPhysicalView"
            @handleSelectView="handleSelectView"
            @saveMapEvent="saveMapEvent"
            @verifyMapEvent="verifyMapEvent"
            @addOrUpdateMapModel="addOrUpdateMapModel"
            @delMapModel="delMapModel"
            @setCenter="setCenter"
          />
        </div>
        <div v-if="viewDraft==='route'">
          <route-operate
            ref="routeOperate"
            :card-height="cardHeight+25"
            :map-info="mapInfo"
            :selected="selected"
            @handleSelectView="handleSelectView"
            @setCenter="setCenter"
          />
        </div>
        <div v-if="viewDraft==='routing'">
          <routing-operate
            ref="routingOperate"
            :card-height="cardHeight+25"
            :map-info="mapInfo"
            :selected="selected"
            @handleSelectView="handleSelectView"
            @setCenter="setCenter"
          />
        </div>
        <div v-if="viewDraft==='automatic'">
          <automatic-operate
            ref="automaticOperate"
            :card-height="cardHeight+25"
            :map-info="mapInfo"
            :selected="selected"
            @handleSelectView="handleSelectView"
            @setCenter="setCenter"
          />
        </div>
        <div v-if="viewDraft==='swtich'">
          <switch-operate
            ref="SwitchOperate"
            :card-height="cardHeight+25"
            :map-info="mapInfo"
            :selected="selected"
            @handleSelectView="handleSelectView"
            @setCenter="setCenter"
          />
        </div>
        <div v-if="viewDraft==='path'">
          <path-operate
            ref="pathOperate"
            :card-height="cardHeight+25"
            :map-info="mapInfo"
            :selected="selected"
            @handleSelectView="handleSelectView"
            @setCenter="setCenter"
          />
        </div>
      </div>
    </div>
  </transition>
</template>
<script>
import { saveMap, getMapDetail, verifyMap } from '@/api/jmap/mapdraft';
import { ViewMode, TrainingMode, getDeviceMenuByDeviceType } from '@/scripts/ConstDic';
import { checkLoginLine } from '@/api/login';
import JlmapVisual from '@/views/jlmap/index';
import RouteOperate from './routeoperate/index';
import RoutingOperate from './routingoperate/index';
import AutomaticOperate from './automaticoperate/index';
import MapOperate from './mapoperate/index';
import SwitchOperate from './switchoperate/index';
import pathOperate from './pathoperate/index';
import WindowResizeHandler from '@/mixin/WindowResizeHandler';

export default {
	name: 'MapView',
	components: {
		JlmapVisual,
		MapOperate,
		RouteOperate,
		RoutingOperate,
		SwitchOperate,
		pathOperate,
		AutomaticOperate
	},
	mixins: [
		WindowResizeHandler
	],
	data() {
		return {
			mapSaveing: false,
			cardHeight: 400,
			ViewMode: ViewMode,
			viewDraft: 'draft',
			autoSaveTask: null,
			selected: null,
			mapInfo: { name: '请选择地图' },
			timeDemon: null
		};
	},
	watch: {
		'$store.state.map.mapDataLoadedCount': function (val) {
			this.initAutoSaveTask();
		},
		'viewDraft': function () {
			this.initAutoSaveTask();
		},
		$route() {
			this.loadInitPage();
		}
	},
	mounted() {
		this.resizeHandler();
		this.loadInitPage();
		this.timeDemon = setInterval(() => {
			checkLoginLine();
		}, 5000 * 60);
	},
	beforeDestroy() {
		this.clearAutoSave();
		this.$store.dispatch('map/mapClear');
		if (this.timeDemon) {
			clearTimeout(this.timeDemon);
		}
	},
	methods: {
		resizeHandler: function () {
			this.cardHeight = this._clientHeight - 195;
		},
		endViewLoading(isSuccess) {
			if (!isSuccess) {
				this.$store.dispatch('map/mapClear');
			}
		},
		loadInitPage() {
			this.$store.dispatch('training/changeMode', { mode: TrainingMode.MAP_EDIT });
			this.viewDraft = this.$route.params.view;
			this.mapInfo = { name: '请选择地图', id: this.$route.params.mapId };
			if (parseInt(this.mapInfo.id)) {
				this.mapInfo.name = this.$route.query.name;
				getMapDetail(this.$route.params.mapId).then(response => {
					this.$store.dispatch('map/mapClear').then(() => {
						this.$store.dispatch('map/setMapData', response.data);
						this.setDelayUnlockStatus(response.data, '00');
						this.initAutoSaveTask();
					});
				}).catch(() => {
					this.$messageBox('加载地图数据失败');
					this.endViewLoading();
				});
			} else {
				this.endViewLoading();
			}
		},
		initAutoSaveTask() {
			const timeout = 1000 * 60 * 3;
			this.clearAutoSave(this.autoSaveTask);
			if (this.viewDraft == 'draft') {
				this.autoSaveTask = setInterval(this.saveMapEvent, timeout);
			}
		},
		clearAutoSave() {
			if (this.autoSaveTask) {
				clearInterval(this.autoSaveTask);
				this.autoSaveTask = null;
			}
		},
		handleSelectControlPage (model) {
			if (this.$refs && this.$refs.mapOperate) {
				this.$refs.mapOperate.handleSelectControlPage(model);
			}
		},
		handleSelectView(handle) {
			if (this.$refs && this.$refs.jlmapVisual) {
				this.$refs.jlmapVisual.setLayerVisible(handle);
			}
		},
		handleSelectLogicalView(handle) {
			if (this.$refs && this.$refs.jlmapVisual) {
				this.$refs.jlmapVisual.setLevelVisible(handle);
			}
		},
		handleSelectPhysicalView(handle) {
			if (this.$refs && this.$refs.jlmapVisual) {
				this.$refs.jlmapVisual.setLevelVisible(handle);
			}
		},
		clickEvent(em) {
			var device = this.getDeviceByEm(em);
			this.onSelect(device);
			switch (this.viewDraft) {
			case 'route':
				this.$refs.routeOperate.setSelected(device);
				break;
			case 'routing':
				this.$refs.routingOperate.setSelected(device);
				break;
			case 'automatic':
				this.$refs.automaticOperate.setSelected(device);
				break;
			case 'swtich':
				this.$refs.SwitchOperate.setSelected(device);
				break;
			case 'path':
				this.$refs.pathOperate.setSelected(device);
				break;
			}
		},
		// 获取设备数据
		getDeviceByEm(em) {
			var	device = this.$store.getters['map/getDeviceByCode'](em.deviceCode) || null;
			if (device) {
				device._viewVal = em.val;
			}
			return device;
		},
		onSelect(device) {
			this.selected = device || null;
			this.selected && this.handleSelectControlPage(device);
		},
		onContextmenu(em) {
			this.point = {
				x: em.clientX,
				y: em.clientY
			};

			var menu = getDeviceMenuByDeviceType('Cancel');

			this.$store.dispatch('menuOperation/setPopMenu', { position: this.point, menu: menu });
		},
		saveMapEvent() {
			if (this.$refs.jlmapVisual) {
				const map = this.$store.state.map.map;
				if (map && parseInt(this.$route.params.mapId)) {
					for (const i in map.sectionList) {
						if (map.sectionList[i].points.length > 0) {
							for (let index = 0; index < map.sectionList[i].points.length; index++) {
								if (String(map.sectionList[i].points[index].x) == 'undefined' || String(map.sectionList[i].points[index].y) == 'undefined') {
									this.$messageBox('区段坐标缺失');
									return;
								}
							}
						} else {
							this.$messageBox('区段坐标缺失');
							return;
						}
					}

					this.mapSaveing = true;
					this.$store.dispatch('map/saveMapDeviceDefaultConvert').then(() => {
						console.log(Object.assign(map, { mapId: this.$route.params.mapId }));
						saveMap(Object.assign(map, { mapId: this.$route.params.mapId })).then(response => {
							this.$message.success('保存成功');
							this.mapSaveing = false;
							this.initAutoSaveTask();
						}).catch(error => {
							this.$messageBox('保存失败');
							this.mapSaveing = false;
							if (error.code === 40004 || error.code === 40005 || error.code === 40003) {
								this.clearAutoSave();
							} else {
								this.initAutoSaveTask();
							}
						});
					});
				}
			}
		},
		verifyMapEvent() {
			if (this.$refs.jlmapVisual) {
				const map = this.$store.state.map.map;
				if (map && this.$route.params.mapId) {
					verifyMap(this.$route.params.mapId).then(res => {
						if (res.data.length) {
							this.tableToExcel(res.data);
							this.$messageBox('数据校验不通过');
						} else {
							this.$message.success('数据校验通过！');
						}
					}).catch(() => {
						this.$messageBox('请求失败');
					});
				}
			}
		},

		tableToExcel(data) {
			const filterVal = ['index'];
			const arr = [];
			data.forEach(item => {
				arr.push({ index: item });
			});
			const dataList = this.formatJson(filterVal, arr);
			import('@/utils/Export2Excel').then(excel => {
				excel.export_json_to_excel(['有问题数据'], dataList, '数据列表');
			});
		},
		formatJson(filterVal, jsonData) {
			return jsonData.map(v => filterVal.map(j => v[j]));
		},

		setDelayUnlockStatus(data, status) {
			if (data && data.delayShowList) {
				data.delayShowList.forEach(elem => {
					elem.status = status;
				});
			}
		},
		// 增加数据数据 给vuex map对象中
		addOrUpdateMapModel(obj) {
			this.$store.dispatch('map/updateMapDevices', obj).then((devices) => {
				this.$refs.jlmapVisual.addOrUpdateDevices(devices);
			});
		},
		// 删除数据 同时del map
		delMapModel(obj) {
			this.$store.dispatch('map/deleteMapDevices', obj).then((devices) => {
				this.$refs.jlmapVisual.deleteDevices(devices);
				this.selected = null;
			});
		},
		// 设置显示中心
		setCenter(code) {
			this.$refs.jlmapVisual.setCenter(code);
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    @import "src/styles/mixin.scss";

    .map-view {
        float: left;
        width: auto;
    }

    .map-draft {
        float: right;
        width: 520px;

        /deep/ .el-scrollbar__view {
            width: 510px !important;
        }
    }

    .physical-view {
        line-height: 25px;
        height: 60px;
        padding-left: 12px;

        .el-checkbox {
            width: 70px;
            margin: 0;
            margin-right: 12px;
        }
    }
</style>
