<template>
	<div class="common-page device-manage">

    	<!-- 表格 -->
		<div class="panel-bottom page-row">
			<h3>区域信息管理</h3>
			<div class="ctin-box">
				<div class="content-within">
					<div class="content-fix">
						<div class="toolbar">
							<el-button size="mini" type="primary" icon="el-icon-plus" @click="toAdd">新增</el-button>
						</div>
						<div class="content">
							<el-table :data="tableData" v-loading="loading" border style="width:auto" :row-class-name="tableRowClassName">
								<el-table-column prop="name" label="区域名称" align="center"></el-table-column>
								<el-table-column prop="areaclass" label="所属类别" align="center"></el-table-column>
								<el-table-column prop="card" label="区域标识图" align="center">
									<template slot-scope="scope">
										<img :src="imgSrcStart + '/avatar/' + scope.row.card" width="40" height="40"/>
									</template>
								</el-table-column>
								<el-table-column prop="max" label="最大承接量" align="center"></el-table-column>
								<el-table-column prop="createTime" label="日期" align="center"></el-table-column>
								<el-table-column label="操作" align="center" fixed="right">
									<template slot-scope="scope">
										<el-button size="mini" type="primary" icon="el-icon-edit" @click="toEdit(scope.row)"></el-button>
										<el-button size="mini" type="danger" icon="el-icon-delete" @click="toDelete(scope.row)"></el-button>
									</template>
								</el-table-column>
							</el-table>
							<!--分页组件-->
							<el-pagination :total="total" :current-page="page" style="margin-top: 8px;" layout="total, prev, pager, next, sizes" @size-change="sizeChange" @current-change="pageChange" />
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 表单渲染 -->
		<el-dialog append-to-body :close-on-click-modal="true" :before-close="cancelForm" :visible.sync="form.visible" :title="form.title" width="800px">
			<el-form :model="form.item" :rules="rules" ref="form1" :inline="true" size="small" label-width="150px">
				<el-form-item label="区域名称" prop="name">
					<el-input v-model="form.item.name" style="width:160px;" placeholder="请输入区域名称" :disabled="form.reqType == 'edit'"/>
				</el-form-item>
				<el-form-item label="所属类别" prop="areaclass">
					<el-select v-model="form.item.areaclass" placeholder="请选择所属类别" size="small" style="width:160px;">
						<el-option v-for="(obj,index) in RegionalTypeData" :label="obj.classname" :value="obj.classname" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="是否需要遮罩层" prop="shadow">
					<el-select v-model="form.item.shadow" placeholder="请选择是否需要遮罩层" style="width:160px;">
						<el-option label="是" value="是"></el-option>
						<el-option label="否" value="否"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="最大承接车辆数" prop="max">
					<el-input v-model="form.item.max" style="width:160px;" placeholder="请输入最大承接车辆数"/>
				</el-form-item>
				<el-form-item label="区域标记">
					<el-input v-model="picFileName" style="width:160px;" placeholder="请选择图片" disabled />
					<input type="file" name="image" @change="excelImport($event)" />
				</el-form-item>
				<div id="centerDiv" class="mapcontainer3" v-show="form.reqType == 'add'">
					<mars3dViewerMap :url="configUrl" @onload="onMapload" ref="mars3dViewerMapMethod"/>
				</div>


				<!-- 如果所属类型是电子围栏，要添加一下属性 -->
				<el-form-item label="启用时间段" v-show="form.item.areaclass == '电子围栏'">
					<el-time-picker
						v-model="form.item.startTime"
						placeholder="开始时间">
					</el-time-picker>
					<el-time-picker
						v-model="form.item.endTime"
						placeholder="结束时间">
					</el-time-picker>
				</el-form-item>
				<el-form-item label="限制类型" prop="limitclass" v-show="form.item.areaclass == '电子围栏'">
					<el-select v-model="form.item.limitclass" placeholder="请选择限制类型" style="width:160px;">
						<el-option label="限入" value="限入"></el-option>
						<el-option label="限出" value="限出"></el-option>
					</el-select>
				</el-form-item>
				<br/>
				<el-form-item label="选择车辆" prop="cars" v-show="form.item.areaclass == '电子围栏'">
					<div class="checkboxViews">
						<el-checkbox-group v-model="checkDataList" style="width:480px;">
							<el-checkbox v-for="(obj,index) in carInformationData" :label="obj.number" :key="index">{{obj.number}}</el-checkbox>
						</el-checkbox-group>
					</div>
				</el-form-item>
				<el-form-item label="启停状态" prop="status" v-show="form.item.areaclass == '电子围栏'">
					<el-select v-model="form.item.status" placeholder="请选择启停状态" style="width:160px;">
						<el-option label="启用" value="启用"></el-option>
						<el-option label="停用" value="停用"></el-option>
					</el-select>
				</el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button type="text" @click="cancelForm">取消</el-button>
				<el-button :loading="form.status.cu === 2" type="primary" @click="submitForm('form1', form.item)">确认</el-button>
			</div>

		</el-dialog>

	</div>
</template>

<script>
import { Tools, HttpReq, Dates} from '@/assets/js/common.js';
import mars3dViewerMap from '../../../components/mars3d/Map3.vue' //地图

export default {
	name: 'CarType',
	components: {
		mars3dViewerMap,
	},
	data() {
		const basePathUrl = window.basePathUrl || ''
		return {
			//地图图片
			configUrl: basePathUrl + 'config/config.json',
			imgSrcStart:process.env.VUE_APP_LOCAL_API2,
			loading: false,
			page: 1,
			size: 10,
			total: 0,
			query:{},
			picFileName:'',
			tableData: [],
			RegionalTypeData:[],
			carInformationData:[],
			checkAll: false,
			checkDataList:[],
			oldCheckDataList:[],
			form: {
				title:'新增区域信息',
				visible:false,
				reqType:'add',
				status:{cu:0},
				item:{},
			},
			rules: {
				name: [
					{required: true, message: '请输入区域名称', trigger: 'blur' }
				],
				areaclass: [
					{required: true, message: '请选择所属类别', trigger: 'change' }
				],
			},

		}
	},
	mounted() {
		var that = this;
		this.$nextTick(() => {
			this.loadData();
		})
	},
	methods: {
		//获取区域信息数据
		loadData() {
			var sort = 'createTime,desc';
			var param = this.query;
			param.page = this.page - 1;
			param.size = this.size;
			param.sort = sort;
			
			this.$nextTick(()=>{
				HttpReq.truckDispatching.RegionalInformationQuery(param).then((res) => {
					if(res.code == 200){
						this.loading = false;
						this.tableData = res.data.content;
						this.total = res.data.totalElements;
					}
				})
				//获取所属类别
				HttpReq.truckDispatching.RegionalTypeQuery(param).then((res) => {
					if(res.code == 200){
						this.RegionalTypeData = res.data.content;
					}
				})
				//获取车辆信息
				HttpReq.truckDispatching.carInformationQuery(param).then((res) => {
					if(res.code == 200){
						this.carInformationData = res.data.content;
					}
				})
			})

		},
		tableRowClassName({row, rowIndex}) {
			if (rowIndex === 1) {
				return 'warning-row';
			} else if (rowIndex === 3) {
				return 'success-row';
			}
			return '';
		},	
		cancelForm(a, b, c){
			this.form.visible = false;
		},
		toAdd() {
			// 请除表单验证
			this.$refs['form1'] && this.$refs['form1'].clearValidate();
			this.form.title = '新增区域信息';
			this.form.status.cu = 0;
			this.form.visible = true;
			this.form.reqType = 'add';
			this.form.item = {};
			this.picFileName = '';
			this.checkDataList = [];
		},
		toEdit(item) {
			// 请除表单验证
			this.$refs['form1'] && this.$refs['form1'].clearValidate();
			this.form.title = '修改区域信息';
			this.form.status.cu = 0;
			this.form.visible = true;
			this.form.item = {...item};
			this.form.reqType = 'edit';
			this.picFileName = this.form.item.card;
			let oldCheckDataListCenterId = [];
			let oldCheckDataListCenterCarIn = [];
			HttpReq.truckDispatching.RegionalInformationCarQuery({areaName:item.name}).then((res) => {
				if(res.code == 200){
					res.data.content.forEach((item)=>{
						oldCheckDataListCenterId.push(item.id);
						oldCheckDataListCenterCarIn.push(item.car);
					})
				}
			})
			this.checkDataList = oldCheckDataListCenterCarIn;
			this.oldCheckDataList = oldCheckDataListCenterId;
		},
		toDelete(item) {
			var id = item.id;
			var weilanName = item.name;
			this.$confirm('确认删除该条数据吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then((e) => {
				this.reqRemoveProject([id],[weilanName])
			}).catch((e) => {})
		},
		pageChange(e) {
			this.page = e
			this.loadData()
		},
		sizeChange(e) {
			this.page = 1
			this.size = e
			this.loadData()
		},
		submitForm(validateName, item){
			if(!this.form.status.cu){
				this.form.status.cu = 2;
				this.$refs[validateName].validate(valid => {
					if(valid){
						if(this.form.reqType === 'add'){
							this.reqAddItem(this.form, item)
						}else{
							this.reqUpdateItem(this.form, item)
						}
					}else{
						this.form.status.cu = 0
					}
				});
			};
		},
		//新增区域信息
		reqAddItem(form, item){
			let areaclass1 = item.areaclass;
			let areaColor = '';
			this.RegionalTypeData.forEach((obj1)=>{
				if(obj1.classname == areaclass1){
					areaColor = obj1.color;
				}
			})

			let panduan1 = this.tableData.find((obj,index)=>{
				return obj.name == item.name;
			})
			if(panduan1){
				this.$notify({
					title: '区域名称重复,请重新输入区域名称！',
					type: 'error',
					duration: 2500
				})
				form.status.cu = 0
				return
			}else{
				let lastData = {...item};
				lastData.card = this.picFileName;
				//this.$refs.mars3dViewerMapMethod.uploaded(lastData.name);
				HttpReq.truckDispatching.RegionalInformationAdd(lastData).then((res) => {
					form.visible = false;
					if(res.code == 200){
						this.$notify({
							title: '区域信息上传中，请稍等！',
							type: 'success',
							duration: 2500
						});
						this.loadData();
						this.$nextTick(()=>{
							this.$refs.mars3dViewerMapMethod.uploaded(lastData.name,areaColor);
						})
					}else{
						this.$notify({
							title: res.msg,
							type: 'error',
							duration: 2500
						})
					}
				}).catch(function(error) {
					form.status.cu = 0
				});

				this.checkDataList.forEach((carItem,index)=>{
					let uploadCarData = {};
					uploadCarData.car = carItem;
					uploadCarData.areaId = item.code;
					console.log('uploadCarData',uploadCarData);
					HttpReq.truckDispatching.RegionalInformationCarAdd(uploadCarData).then((res) => {
						if(res.code == 200){
						}else{
							this.$notify({
								title: res.msg,
								type: 'error',
								duration: 2500
							})
						}
					}).catch(function(error) { });
				})

			}

		},
		//修改区域信息
		reqUpdateItem(form, item){
			let lastData = {...item};
			lastData.card = this.picFileName;
			lastData.cars = this.checkDataList;
			HttpReq.truckDispatching.RegionalInformationUpdate(lastData).then((res) => {
				form.visible = false;
				if(res.code == 200){
					this.$notify({
						title: '区域信息修改成功！',
						type: 'success',
						duration: 2500
					});
					this.loadData()
				}else{
					this.$notify({
						title: res.msg,
						type: 'error',
						duration: 2500
					})
					this.loadData()
				}
			}).catch(function(error) {
				form.status.cu = 0
			});
			HttpReq.truckDispatching.RegionalInformationCarDel(this.oldCheckDataList).then((res) => {	})
			this.$nextTick(()=>{
				this.checkDataList.forEach((carItem,index)=>{
					let uploadCarData = {};
					uploadCarData.car = carItem;
					uploadCarData.areaId = item.code;
					HttpReq.truckDispatching.RegionalInformationCarAdd(uploadCarData).then((res) => {
						if(res.code == 200){
						}else{
							this.$notify({
								title: res.msg,
								type: 'error',
								duration: 2500
							})
						}
					}).catch(function(error) { });
				})
			})
		},
		//删除区域信息
		reqRemoveProject(item,weilanName){
			HttpReq.truckDispatching.RegionalInformationDel(item).then((res) => {
				if(res.status == 400){
					this.$notify({
						title: res.msg,
						type: 'error',
						duration: 2500
					})
				}else{
					this.$notify({
						title: '删除成功！',
						type: 'success',
						duration: 2500
					});
				}
				this.loadData();
			})
			HttpReq.truckDispatching.screenMapSetUpDel(weilanName).then((res) => {
				// if(res.status == 400){
				// 	this.$notify({
				// 		title: res.msg,
				// 		type: 'error',
				// 		duration: 2500
				// 	})
				// 	}else{
				// 	this.$notify({
				// 		title: '删除成功！',
				// 		type: 'success',
				// 		duration: 2500
				// 	});
				// }
          	})
		},
		//图片上传
		excelImport(event) {
			let that = this;
			let file = event.target.files[0];
			let formData1 = new FormData();
			formData1.append("avatar", file);
			HttpReq.truckDispatching.uploadPictures(formData1).then((res) => {
				this.$notify({
					title: '上传成功！',
					type: 'success',
					duration: 2500
				});
				that.picFileName = res.avatar;
			})
		},

		// 地图构造完成回调
		onMapload(map) {
			// 以下为演示代码

			// 创建entity图层
			const graphicLayer = new this.mars3d.layer.GraphicLayer()
			map.addLayer(graphicLayer)

			// 2.在layer上绑定监听事件
			graphicLayer.on(this.mars3d.EventType.click, function (event) {
				console.log('监听layer，单击了矢量对象', event)
			})
			graphicLayer.on(this.mars3d.EventType.mouseOver, function (event) {
				console.log('监听layer，鼠标移入了矢量对象', event)
			})
			graphicLayer.on(this.mars3d.EventType.mouseOut, function (event) {
				console.log('监听layer，鼠标移出了矢量对象', event)
			})
			// 可在图层上绑定popup,对所有加到这个图层的矢量数据都生效
			graphicLayer.bindPopup('我是layer上绑定的Popup', {
				anchor: [0, -10]
			})
			// 可在图层绑定右键菜单,对所有加到这个图层的矢量数据都生效
			graphicLayer.bindContextMenu([
				{
					text: '删除对象',
					iconCls: 'fa fa-trash-o',
					callback: function (e) {
						const graphic = e.graphic
						if (graphic) {
						graphicLayer.removeGraphic(graphic)
						}
					}
				}
			])
		},

	}
}
</script>

<style rel="stylesheet/scss" lang="scss" scope>
	.el-table .warning-row {
		background: oldlace;
	}
	.el-table .success-row {
		background: #f0f9eb;
	}
	
	.device-manage{
		.panel-bottom{
			.el-button{margin:2px 0;padding:6px 15px;font-size:14px;}
			.btn-groub2{
				display:inline-block;
				.el-button{margin:2px 0;padding:6px 15px;font-size:15px;}
				.el-button--warning {
					background-color: #e6a23c;
					border-color: #e6a23c;
				}
				.el-button--warning:focus,.el-button--warning:hover{background:#ebb563;border-color:#ebb563;}
			}
			
		}
		
	}
	.mapcontainer3 {
		height: 50vh;
		width: 750px;
		overflow: hidden;
		margin-bottom: 10px;
	}
	.checkboxViews{
		padding-left: 10px;
		box-sizing: border-box;
		width: 490px;
		height: 120px;
		border: 1px gainsboro solid;
		overflow-y:scroll;
		overflow-x:hidden;
	}
	.ecahrt1-dialog{
		display:flex;align-items:center;
		.el-dialog{
			margin-top:inherit !important;display:table !important;width:fit-content;
			.el-form-item{margin-right:0;}
		}

		.el-dialog__header{height:0;padding:0;display:block;}
		.form-body{
			border:1px solid #999;width:800px;height:500px;position:relative;
			>div{position:absolute;top:0;left:0;height:100%;width:100%;}
		}
	}
</style>
