<template>
	<div style="cursor: default">
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item>基地管理</el-breadcrumb-item>
		</el-breadcrumb>
		<SearchBar>
			<div slot="type-check">
				<el-input
					style="cursor: pointer"
					placeholder="请输入内容"
					size="mini"
					suffix-icon="el-icon-search"
					v-model="search"
					@change="searchBase"
					clearable
				></el-input>
			</div>
			<div slot="search-common">
				<el-button type="primary" size="mini" @click="addBase('新增基地')"
					>新增</el-button
				>
			</div>
		</SearchBar>
		<el-row :gutter="20">
			<el-col
				:xs="24"
				:sm="24"
				:md="12"
				:lg="12"
				:xl="8"
				class="col-item"
				v-for="(item, index) in baseList"
				:key="index"
			>
				<el-card class="box-card boxCard">
					<div class="baseCard">
						<div class="baseImg">
							<!-- <img :src="$host + item.base_img" /> -->
							<img :src="item.base_img" />
						</div>
						<div class="addBaseInfo">
							<h2>{{ item.base_name }}</h2>
							<div class="addBaseInfoDetails">
								<i class="iconfont icon-yonghu11"></i>
								<div class="caption">负责人 ：</div>
								<div>{{ item.base_charge }}</div>
							</div>
							<div class="addBaseInfoDetails">
								<i class="iconfont icon-dianhua2"></i>
								<div class="caption">电&nbsp;&nbsp;&nbsp;&nbsp;话 :</div>
								<div>{{ item.base_phone }}</div>
							</div>
							<div class="addBaseInfoDetails">
								<i class="iconfont icon-mianji"></i>
								<div class="caption">面&nbsp;&nbsp;&nbsp;&nbsp;积 ：</div>
								<div>{{ item.base_area }}</div>
							</div>
							<div class="addBaseInfoDetails">
								<i class="iconfont icon-dingwei"></i>
								<div class="caption">地&nbsp;&nbsp;&nbsp;&nbsp;址 ：</div>
								<div class="addr">{{ item.address || '未定位' }}</div>
							</div>
						</div>
					</div>
					<div
						class="baseEditBox"
						@click="editBase(item.id, '修改基地', item.address)"
					>
						<img src="@/assets/images/fourMoodBase/baseEditIcon.png" alt />
					</div>
					<div class="baseBtn">
						<span class="detailBtn" @click="detailBase(item.id)">详情</span>
						<span class="delBtn" @click="delBase(item.id)">删除</span>
					</div>
				</el-card>
			</el-col>
		</el-row>
		<!-- 暂无数据 -->
		<div class="expertDiagnosis_referral_units_not" v-if="baseList.length <= 0">
			<img
				:src="$imghost + zanwu"
				alt
				class="expertDiagnosis_referral_units_notImg"
			/>
		</div>
		<el-pagination
			v-if="baseList.length > 0"
			background
			:page-size="6"
			layout="prev, pager, next"
			:current-page="page"
			:total="totalNum"
			@current-change="changePage"
		></el-pagination>
		<!-- 基地新增/修改 -->
		<el-dialog
			:title="title"
			:visible.sync="baseAddVisible"
			width="30%"
			@close="addBaseDialogClosed"
		>
			<el-form
				ref="addBaseFormRef"
				:model="addBaseInfo"
				label-width="90px"
				:rules="addUserFormRules"
			>
				<el-form-item label="基地名称 : " prop="baseName">
					<el-input v-model="addBaseInfo.baseName"></el-input>
				</el-form-item>
				<el-form-item label="基地图片 : " prop="imgSrc">
					<el-upload
						class="avatar-uploader"
						action
						:auto-upload="false"
						:show-file-list="false"
						:on-change="changeUpload"
					>
						<!-- <img
							v-if="addBaseInfo.imgSrc"
							:src="$host + addBaseInfo.imgSrc"
							class="avatar"
						/> -->
						<img
							v-if="addBaseInfo.imgSrc"
							:src="addBaseInfo.imgSrc"
							class="avatar"
						/>
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="负责人 : " prop="principal">
					<el-input v-model="addBaseInfo.principal"></el-input>
				</el-form-item>
				<el-form-item label="联系电话 : " prop="phone">
					<el-input v-model="addBaseInfo.phone"></el-input>
				</el-form-item>
				<el-form-item label="面积(亩) : " prop="area">
					<el-input type="number" min="0" v-model="addBaseInfo.area"></el-input>
				</el-form-item>
				<el-form-item label="绑定设备 : " prop="bindEquip">
					<el-cascader
						:key="addBaseInfo.cascaderKey"
						style="width: 100%"
						:options="addBaseInfo.cascaderEquipArr"
						v-model="addBaseInfo.bindEquip"
						:props="{
							multiple: true,
							label: 'type_name',
							value: 'type_name',
							multiple: true
						}"
						clearable
						filterable
					></el-cascader>
				</el-form-item>
				<el-form-item label="基地描述 : " prop="baseIntro">
					<el-input type="textarea" v-model="addBaseInfo.baseIntro"></el-input>
				</el-form-item>
				<el-form-item label="基地地址 : " prop="address" class="addressItem">
					<el-input
						type="text"
						v-model="addBaseInfo.address"
						disabled
						placeholder="请定位"
					></el-input>
					<el-button type="primary" size="mini" @click="goLocation"
						>基地定位</el-button
					>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="baseAddVisible = false">取 消</el-button>
				<el-button type="primary" @click="addBaseSubm">确认</el-button>
			</span>
		</el-dialog>
		<!-- vueCropper 剪裁图片实现-->
		<el-dialog title="图片剪裁" :visible.sync="cropperVisible" append-to-body>
			<div class="cropper-content">
				<div style="width: 100%; height: 500px">
					<vueCropper
						ref="cropper"
						:img="option.img"
						autoCrop
						centerBox
						fixed
						:fixedNumber="option.fixedNumber"
						:outputSize="option.size"
						:outputType="option.outputType"
					></vueCropper>
				</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="cropperVisible = false">取 消</el-button>
				<el-button type="primary" @click="finish">确认</el-button>
			</div>
		</el-dialog>
		<!-- 添加定位弹框 -->
		<el-dialog
			class="map_dialog"
			title="添加定位"
			v-if="addLocationDialogVisible"
			:visible.sync="addLocationDialogVisible"
			width="800px"
			@closed="addLocationDialogClosed"
		>
			<el-form
				:inline="true"
				:model="locationForm"
				class="demo-form-inline"
				size="mini"
			>
				<el-form-item label="经度">
					<el-input v-model="locationForm.lng"></el-input>
				</el-form-item>
				<el-form-item label="维度">
					<el-input v-model="locationForm.lat"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" size="mini" @click="locationSearch"
						>定位</el-button
					>
				</el-form-item>
				<el-form-item>
					<el-input
						@change="addrChange()"
						clearable
						placeholder="请输入地区检索"
						v-model="addr"
					>
						<i slot="suffix" class="el-input__icon el-icon-search"></i>
					</el-input>
				</el-form-item>
			</el-form>
			<baidu-map
				class="Bmap"
				:center="center"
				:zoom="mapZoom"
				:scroll-wheel-zoom="true"
				@ready="handlerBMap"
				@click="locationPoint"
			></baidu-map>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addLocationDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="addLocationSubm">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>
<script>
import SearchBar from '@/components/SearchBar'
export default {
	data() {
		var checkMobile = (rule, value, callback) => {
			const regMobile = /^1\d{10}$/
			if (regMobile.test(value)) {
				callback()
			} else {
				// 返回一个错误提示
				callback(new Error('请输入合法的手机号码'))
			}
		}
		return {
			zanwu: '/images/expertDiagnosis/zanwu.png',
			dialogTxt: '',
			search: '',
			page: 1,
			flag: null, //编辑基地提交为1，添加基地为2
			totalNum: null,
			baseAddVisible: false,
			cropperVisible: false,
			title: '',
			addBaseInfo: {
				baseName: '',
				imgSrc: '',
				principal: '',
				phone: '',
				area: 0,
				cascaderKey: 0, //绑定key值，key值改变，cascader就重新渲染
				cascaderEquipArr: [],
				bindEquip: [],
				baseIntro: '',
				address: '',
				lng: '',
				lat: '',
				base_id: ''
			},
			addUserFormRules: {
				baseName: [
					{ required: true, message: '请输入基地名称', trigger: 'blur' }
				],
				imgSrc: [
					{ required: true, message: '请选择基地图片', trigger: 'change' }
				],
				principal: [
					{ required: true, message: '请输入负责人', trigger: 'blur' }
				],
				phone: [
					{ required: true, trigger: 'blur', message: '手机号不能为空' },
					{ required: true, validator: checkMobile, trigger: 'blur' }
				],
				cascaderEquipArr: [
					{ required: true, message: '请选择基地设备', trigger: 'change' }
				],
				address: [
					{ required: true, message: '请选择基地地址', trigger: 'change' }
				]
			},
			// 裁剪组件的基础配置option
			option: {
				img:
					'https://qn-qn-kibey-../../assets-cdn.app-echo.com/goodboy-weixin.PNG', // 裁剪图片的地址
				info: true, // 裁剪框的大小信息
				outputSize: 0.8, // 裁剪生成图片的质量
				outputType: 'jpeg', // 裁剪生成图片的格式
				// canScale: false, // 图片是否允许滚轮缩放
				// autoCrop: true, // 是否默认生成截图框
				// autoCropWidth: 300, // 默认生成截图框宽度
				// autoCropHeight: 200, // 默认生成截图框高度
				// fixedBox: true, // 固定截图框大小 不允许改变
				fixed: true, // 是否开启截图框宽高固定比例
				fixedNumber: [10, 7], // 截图框的宽高比例
				full: true, // 是否输出原图比例的截图
				canMoveBox: false, // 截图框能否拖动
				original: false, // 上传图片按照原始比例渲染
				centerBox: false, // 截图框是否被限制在图片里面
				infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
			},
			baseList: [],
			//添加基地定位
			addLocationDialogVisible: false,
			addr: '', //地图检索的地址
			locationForm: {
				lng: '',
				lat: ''
			},
			center: { lng: 113.271429, lat: 23.135336 },
			mapZoom: 6
		}
	},
	components: {
		SearchBar
	},
	created() {
		this.getBaseList()
	},
	methods: {
		getBaseList() {
			this.$axios({
				method: 'POST',
				url: '/api/api_gateway?method=base.bases.base_list',
				data: this.qs.stringify({
					ret: 'list',
					page_size: 6,
					search: this.search,
					page: this.page
				})
			}).then((res) => {
				if (res.data.message == '') {
					let data = res.data.data.data
					let _this = this
					this.baseList = []
					getList(0, data.length)
					function getList(j, length) {
						let lat = data[j].lat
						let lng = data[j].lng
						_this
							.$jsonp(
								`http://api.map.baidu.com/reverse_geocoding/v3/?renderReverse&output=json&coordtype=wgs84ll`,
								{
									ak: 'nroAiX0Lf6ppNEGt2dBLtDkOldGCPFwF',
									location: `${lat},${lng}`
								}
							)
							.then((res) => {
								let addressComponent = res.result && res.result.addressComponent
								if (addressComponent) {
									data[j].address =
										addressComponent.province +
										addressComponent.city +
										addressComponent.district
								} else {
									data[j].address = ''
								}
								_this.baseList.push(data[j])
								if (++j < length) {
									getList(j, length)
								}
							})
					}
					this.totalNum = res.data.data.page_size
				}
			})
		},
		searchBase() {
			this.page = 1
			this.getBaseList()
		},
		//获取所有未绑定设备+自己已绑定的设备
		getEquipList(id) {
			this.$axios({
				method: 'POST',
				url: '/api/api_gateway?method=base.bases.base_equip',
				data: this.qs.stringify({
					base_id: id
				})
			}).then((res) => {
				let data = res.data.data.data
				this.addBaseInfo.cascaderEquipArr = data
			})
		},
		changePage(val) {
			this.page = val
			this.getBaseList()
		},
		addBaseDialogClosed() {
			this.$refs.addBaseFormRef.resetFields()
			this.addBaseInfo.cascaderKey++
			this.addBaseInfo.baseName = ''
			this.addBaseInfo.principal = ''
			this.addBaseInfo.phone = ''
			this.addBaseInfo.area = ''
			this.addBaseInfo.imgSrc = ''
			this.addBaseInfo.cascaderEquipArr = []
			this.addBaseInfo.bindEquip = []
			this.addBaseInfo.baseIntro = ''
			this.addBaseInfo.address = ''
			this.addBaseInfo.lat = ''
			this.addBaseInfo.lng = ''
		},
		//添加/删除基地
		addBaseSubm() {
			this.$refs.addBaseFormRef.validate((valid) => {
				if (valid) {
					let arr = this.addBaseInfo.bindEquip.map((item) => {
						return item[1]
					})
					if (this.flag == 1) {
						let ret = 'modify'
						//编辑
						this.baseFun(ret, arr, '修改成功')
					} else if (this.flag == 2) {
						let ret = 'add'
						//添加
						this.baseFun(ret, arr, '添加成功')
					}
				} else {
					return false
				}
			})
			// this.getEquipList()
		},
		baseFun(ret, arr, txt) {
			this.$axios({
				method: 'POST',
				url: '/api/api_gateway?method=base.bases.base_list',
				data: this.qs.stringify({
					ret: ret,
					base_id: this.addBaseInfo.base_id,
					base_name: this.addBaseInfo.baseName,
					base_charge: this.addBaseInfo.principal,
					base_phone: this.addBaseInfo.phone,
					base_area: this.addBaseInfo.area,
					base_img: this.addBaseInfo.imgSrc, //去掉/api/
					base_equip: arr.join('#'),
					base_describe: this.addBaseInfo.baseIntro,
					lng: this.addBaseInfo.lng,
					lat: this.addBaseInfo.lat
				})
			}).then((res) => {
				if (res.data.message == '') {
					this.baseAddVisible = false
					this.getBaseList()
					this.$message.success(txt)
				}
			})
		},
		// 上传按钮   限制图片大小
		changeUpload(file, fileList) {
			const isLt5M = file.size / 1024 / 1024 < 5
			if (!isLt5M) {
				this.$message.error('上传文件大小不能超过 5MB!')
				return false
			}
			// 上传成功后将图片地址赋值给裁剪框显示图片
			this.$nextTick(() => {
				this.option.img = URL.createObjectURL(file.raw)
				this.cropperVisible = true
			})
		},
		// 点击裁剪，这一步是可以拿到处理后的地址
		finish() {
			// 获取截图的base64 数据
			this.$refs.cropper.getCropBlob((data) => {
				var form = new FormData()
				let resFile = this.blobToFile(data, 'filename.jpg')
				form.append('img_file', resFile)
				this.cropperVisible = false
				this.$axios({
					method: 'POST',
					url: '/api/api_gateway?method=base.bases.base_photo',
					data: form
				}).then((res) => {
					if (res.data.message == '') {
						this.addBaseInfo.imgSrc = res.data.data.src
					}
				})
			})
		},
		//转成blob
		blobToFile(Blob, fileName) {
			Blob.lastModifiedDate = new Date()
			Blob.name = fileName
			return Blob
		},
		dataURLtoFile(dataurl, filename) {
			//将base64转换为文件
			var arr = dataurl.split(','),
				mime = arr[0].match(/:(.*?);/)[1],
				bstr = atob(arr[1]),
				n = bstr.length,
				u8arr = new Uint8Array(n)
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n)
			}
			if (!!window.ActiveXObject || 'ActiveXObject' in window) {
				// ie浏览器
				return new Blob([u8arr.buffer], { type: mime })
			} else {
				//主流浏览器
				return new File([u8arr], filename, { type: mime })
			}
		},
		goLocation() {
			this.addLocationDialogVisible = true
		},
		addrChange() {
			let local = new this.BMap.LocalSearch(this.map, {
				renderOptions: { map: this.map, panel: 'r-result' }
			})
			local.search(this.addr)
		},
		addLocationDialogClosed() {},
		locationSearch() {},
		handlerBMap({ BMap, map }) {
			this.BMap = BMap
			this.map = map
		},
		//在地图中点击定位
		locationPoint(e) {
			let { point } = e
			this.locationForm = point
			this.map.clearOverlays()
			this.map.addOverlay(new BMap.Marker(point))
		},
		addLocationSubm() {
			let { lng, lat } = this.locationForm
			this.$jsonp(
				`http://api.map.baidu.com/reverse_geocoding/v3/?renderReverse&output=json&coordtype=wgs84ll`,
				{
					ak: 'nroAiX0Lf6ppNEGt2dBLtDkOldGCPFwF',
					location: `${lat},${lng}`
				}
			).then((res) => {
				let addressComponent = res.result && res.result.addressComponent
				if (addressComponent) {
					this.addBaseInfo.address =
						addressComponent.province +
						addressComponent.city +
						addressComponent.district
				} else {
					this.addBaseInfo.address = ''
				}
				this.addBaseInfo.lng = lng
				this.addBaseInfo.lat = lat
				this.addLocationDialogVisible = false //关闭弹框
			})
		},
		editBase(id, title, address) {
			this.title = title
			this.flag = 1
			this.addBaseInfo.base_id = id
			this.$axios({
				method: 'POST',
				url: '/api/api_gateway?method=base.bases.base_list',
				data: this.qs.stringify({
					ret: 'details',
					base_id: id
				})
			}).then((res) => {
				let item = res.data.data[0]
				this.addBaseInfo.baseName = item.base_name
				this.addBaseInfo.principal = item.base_charge
				this.addBaseInfo.phone = item.base_phone
				this.addBaseInfo.area = Number(item.base_area)
				this.addBaseInfo.imgSrc = item.base_img
				this.addBaseInfo.bindEquip = item.base_equip
				this.addBaseInfo.baseIntro = item.base_describe
				this.addBaseInfo.address = address
				this.addBaseInfo.lat = item.lat
				this.addBaseInfo.lng = item.lng
				this.getEquipList(id) //获取所有未绑定和已绑定的设备
				this.dialogTxt = '编辑基地'
				this.baseAddVisible = true
			})
		},
		addBase(title) {
			this.title = title
			this.flag = 2
			this.getEquipList('')
			this.baseAddVisible = true
			this.dialogTxt = '新建基地'
		},
		delBase(id) {
			console.log(id)
			this.$confirm(`确定删除基地么?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.$axios({
						method: 'POST',
						url: '/api/api_gateway?method=base.bases.base_list',
						data: this.qs.stringify({
							ret: 'del',
							base_id: id
						})
					}).then((res) => {
						this.getBaseList()
						this.$message({
							type: 'success',
							message: '删除成功!'
						})
					})
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					})
				})
		},
		detailBase(id) {
			this.$router.push({ path: '/index/baseShow', query: { id: id } })
		}
	}
}
</script>
<style lang="less" scoped>
.boxCard {
	position: relative;
	.baseCard {
		display: flex;
		.baseImg {
			flex: 1;
			overflow: hidden;
			height: 160px;
			img {
				width: 100%;
				height: auto;
			}
		}
		.addBaseInfo {
			flex: 1;
			padding-left: 15px;
			h2 {
				font-size: 16px;
				margin-bottom: 10px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				width: 80%;
			}
			.addBaseInfoDetails {
				display: flex;
				padding-bottom: 10px;
				color: #525252;
				line-height: 18px;
				font-size: 14px;
				i {
					font-size: 14px;
				}
				.caption {
					margin-left: 5px;
					width: 70px;
					flex-grow: 0;
					flex-shrink: 0;
					text-align: left;
				}
				.addr {
					flex-grow: 1;
					text-overflow: -o-ellipsis-lastline;
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					line-clamp: 2;
					-webkit-box-orient: vertical;
					min-height: 40px;
				}
			}
		}
	}
	.baseEditBox {
		position: absolute;
		right: 20px;
		top: 0;
		cursor: pointer;
		img {
			width: 35px;
		}
	}
	.baseBtn {
		position: absolute;
		right: 20px;
		bottom: 10px;
		line-height: 22px;
		span {
			display: inline-block;

			width: 60px;
			border-radius: 20px;
			color: #666;
			text-align: center;
			cursor: pointer;
		}
		.delBtn {
			background: #ddd;
		}
		.detailBtn {
			background: #14a478;
			color: #fff;
			margin-right: 10px;
		}
	}
}
.avatar-uploader {
	/deep/.el-upload {
		.el-upload-dragge {
			width: 100%;
			height: 100%;
		}
	}
}
.col-item {
	height: 223px;
}
.cropper {
	width: auto;
	height: 300px;
}
.addressItem {
	/deep/.el-form-item__content {
		display: flex;
		.el-input {
			flex: 1;
			margin-right: 15px;
		}
	}
}
.Bmap {
	width: 100%;
	height: 400px;
}

</style>
