<template>
	<view class="addGasStation">

		<div class="addGasStationForm">
			<div class="formItem">
				<div class="formItemTitle">
					<text>*</text>
					<text class="title">
						电站名称
					</text>
				</div>
				<div class="formItemValue">
					<input class="ipt" type="text" placeholder="请输入电站名称" v-model="storeName" />
				</div>
			</div>

			<div class="formItem">
				<div class="formItemTitle">
					<text>*</text>
					<text class="title">
						电站区域
					</text>
				</div>
				<uni-data-picker :localdata="localData" popup-title="请选择省市区" @change="onchange"
					@nodeclick="onnodeclick">
					<div class="formItemValue">
						<input disabled class="ipt" :value="province+''+city+''+area" type="text"
							placeholder="请选择电站所属区域" />
						<image class="downIcon" src="/static/downIcon.png" mode=""></image>
					</div>
				</uni-data-picker>
			</div>

			<div class="formItem">
				<div class="formItemTitle">
					<text>*</text>
					<text class="title">
						详细地址
					</text>
				</div>

				<div class="formItemValue">
					<input class="ipt" type="text" placeholder="请输入详细地址" v-model="detailedAddress" />
				</div>
			</div>
			
			<div class="formItemTitle" style="margin-bottom: 0;">
				<text>*</text>
				<text class="title">
					电站价格
				</text>
			</div>
			<view class="formItemValueBox">
				<view class="text">价格</view>
				<div class="formItemValue" style="flex: 1; margin-bottom: 20rpx;margin-top: 20rpx;">
					<input class="ipt" type="text" v-model="powerStationPrice" placeholder="请输入" />
				</div>
			</view>
			
			<div class="formItemTitle" style="margin-bottom: 0;">
				<text class="title">
					常时
				</text>
			</div>
			<view class="formItemValueBox">
				<view class="text">电费</view>
				<div class="formItemValue" style="flex: 1; margin-bottom: 20rpx;margin-top: 20rpx;">
					<input class="ipt" type="text" v-model="frequentlyPrice" placeholder="请输入" />
				</div>
			</view>
			<view class="formItemValueBox">
				<view class="text">服务费</view>
				<div class="formItemValue" style="flex: 1; margin-bottom: 20rpx;margin-top: 20rpx;">
					<input class="ipt" type="text"  v-model="frequentlyServiceCharge" placeholder="请输入" />
				</div>
			</view>

			<div class="formItem">
				<div class="formItemTitle" style="margin-bottom: 0;">
					<text>*</text>
					<text class="title">
						时段价格
					</text>
				</div>
				<div v-for="(item,index) in periodTimeList" :key="index">
					<view class="formItemValueBox" @click="isShowStartTime = true,idx = index">
						<view class="text">开始时间</view>
						<div class="formItemValue" style="flex: 1; margin-bottom: 20rpx;margin-top: 20rpx;">
							<input class="ipt" disabled v-model="item.beginTime" type="text" placeholder="请输入" />
						</div>
					</view>
					<view class="formItemValueBox" @click="isShowEndTime = true,idx = index">
						<view class="text">结束时间</view>
						<div class="formItemValue" style="flex: 1; margin-bottom: 20rpx;margin-top: 20rpx;">
							<input class="ipt" disabled v-model="item.endTime" type="text" placeholder="请输入" />
						</div>
					</view>
					<view class="formItemValueBox">
						<view class="text">电费</view>
						<div class="formItemValue" style="flex: 1; margin-bottom: 20rpx;margin-top: 20rpx;">
							<input class="ipt" v-model="item.price" type="text" placeholder="请输入" />
						</div>
					</view>

					<view class="formItemValueBox">
						<view class="text">服务费</view>
						<div class="formItemValue" style="flex: 1; margin-bottom: 20rpx;margin-top: 20rpx;">
							<input class="ipt" v-model="item.serviceCharge" type="text" placeholder="请输入" />
						</div>
					</view>
					
					
					<!-- <view class="formItemValueBox">
						<view class="text">平台价格</view>
						<div class="formItemValue" style="flex: 1; margin-bottom: 20rpx;margin-top: 20rpx;">
							<input class="ipt" v-model="item.platformPrice" type="text" placeholder="请输入" />
						</div>
					</view> -->
					

					<div class="addBtn" @click="addOilInfo">
						+增加价格
					</div>
				</div>


			</div>

			<div class="formItem">
				<div class="formItemTitle">
					<text>*</text>
					<text class="title">
						电站照片
					</text>
				</div>

				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					:maxCount="6"></u-upload>
			</div>

			<!-- <div class="formItem" @click="isShowShopType = true">
				<div class="formItemTitle">
					<text>*</text>
					<text class="title">
						电站状态
					</text>
				</div>

				<div class="formItemValue">
					<input disabled class="ipt" :value="storeStatus === 0 ? '上架':'下架'" type="text"
						placeholder="请选择电站状态" />
					<image class="downIcon" src="/static/downIcon.png" mode=""></image>
				</div>
			</div> -->
		</div>

		<div class="saveBtn" @click="saveBtn">
			保存
		</div>
		<u-picker :show="isShowShopType" :columns="[shopTypeArr]" @confirm="confirmShopType"
			@cancel="isShowShopType = false" keyName="name"></u-picker>
		<u-picker :show="isShowoliName" :columns="[oliNameArr]" @confirm="confirmOliName"
			@cancel="isShowoliName = false" keyName="name"></u-picker>

		<u-datetime-picker title="选择开始时间" @close="closeIsShow" @cancel="closeIsShow" @confirm="confirmStart"
			ref="datetimePicker" :show="isShowStartTime" :minDate="minDate" mode="time"
			:formatter="formatter"></u-datetime-picker>
		<u-datetime-picker title="选择结束时间" @close="closeIsShow" @cancel="closeIsShow" @confirm="confirmEnd"
			ref="datetimePicker" :show="isShowEndTime" :minDate="minDate" mode="time"
			:formatter="formatter"></u-datetime-picker>

	</view>
</template>

<script>
	const cityRows = require('../../components/map.json')

	export default {
		data() {
			return {
				storeName: '',
				// 省市区
				localData: [],
				province: '',
				city: '',
				area: '',
				areaCode: '',
				fileList1: [],
				storeStatus: '',
				shopTypeArr: [{
					name: '上架',
					id: 0
				}, {
					name: '下架',
					id: 1
				}],
				oliNameArr: [{
					name: '#92',
				}, {
					name: '#95',
				}, {
					name: '#98',
				}],
				isShowShopType: false,
				isShowoliName: false,
				periodTimeList: [{
					beginTime: '',
					endTime: '',
					price: '',
					serviceCharge: ''
				}],
				idx: 0,
				detailedAddress: '',
				lon: '1',
				lat: '1',
				type: '',

				isShowStartTime: false,
				isShowEndTime: false,
				minDate: Number(new Date()),
				beginTime: '',
				endTime: '',
				powerStationPrice:'',
				frequentlyPrice:'',
				frequentlyServiceCharge:'',
				
			}
		},
		onLoad(op) {
			// 省市区数据树生成
			this.localData = this.get_city_tree()
			this.type = op.type
			this.id = op.id
			uni.setNavigationBarTitle({
				title: op.type == 'edit' ? '编辑电站' : '添加电站'
			})
			if (op.type == 'edit') {
				this.getDetails()
			}
			// console.log(JSON.stringify(this.localData))
			uni.getLocation({
				type: 'wgs84',
				success: (res) => {
					console.log('当前位置的经度：' + res.longitude);
					console.log('当前位置的纬度：' + res.latitude);
				},
				fail: (err) => {
					console.log(err);
				}
			});

		},
		methods: {

			getDetails() {
				this.$http.get('/api/store/power/details', {
					id: this.id,
					lon: '1',
					lat: '1'
				}).then(res => {
					this.storeName = res.data.storeName
					this.areaName = res.data.areaName
					this.areaCode = res.data.areaCode
					this.province = res.data.province
					this.city = res.data.city
					this.area = res.data.area

					this.detailedAddress = res.data.detailedAddress
					this.lon = res.data.lon
					this.lat = res.data.lat
					this.periodTimeList = res.data.periodTimeList
					this.frequentlyPrice = res.data.frequentlyPrice
					this.frequentlyServiceCharge = res.data.frequentlyServiceCharge
					this.powerStationPrice = res.data.powerStationPrice
					let fileList1 = []
					res.data.pictureList.map(item => {
						fileList1.push({
							url: item
						})
					})
					this.fileList1 = fileList1
					// this.oilInfoData = res.data.periodTimeList.length ? res.data.periodTimeList[0] : ''
				})
			},


			saveBtn() {
				console.log(this.fileList1);
				let pictureList = []
				this.fileList1.map(item => {
					pictureList.push(item.url)
				})
				let data = {
					storeName: this.storeName,
					province: this.province,
					city: this.city,
					area: this.area,
					areaCode: this.areaCode,
					detailedAddress: this.detailedAddress,
					lon: this.lon,
					lat: this.lat,
					periodTimeList: this.periodTimeList,
					pictureList,
					powerStationPrice:this.powerStationPrice,
					frequentlyPrice:this.frequentlyPrice,
					frequentlyServiceCharge:this.frequentlyServiceCharge,
				}
				console.log(data);
				let api = ''
				console.log(this.type);
				api = this.type == 'edit' ? '/api/store/power/edit' : '/api/store/power/add'
				if (this.type == 'edit') data.id = this.id
				this.$http.post(api, data).then(res => {
					console.log(res);
					uni.showToast({
						icon: 'none',
						title: res.msg
					})
					if (res.code == 200) {
						setTimeout(() => {
							uni.navigateBack()
						}, 800)
					}
				})
			},

			confirmOliName(e) {
				console.log(e);
				this.isShowoliName = false
				this.periodTimeList[this.idx].oliName = e.value[0].name
			},

			addOilInfo() {
				let list = this.periodTimeList
				list.push({
					beginTime: '',
					endTime: '',
					price: '',
					serviceCharge: ''
				})
				this.periodTimeList = list
			},

			confirmShopType(e) {
				console.log(e);
				this.isShowShopType = false
				this.storeStatus = e.value[0].id
			},

			// 节点变化后 （并非已经选择完毕）
			onnodeclick(node) {
				// console.log(JSON.stringify(node))
			},

			// 整体选择完成以后
			onchange(e) {
				const value = e.detail.value
				this.province = value[0].text
				this.city = value[1].text
				this.area = value[2].text
				this.areaCode = value[2].value
			},



			// 省市区数据树生成
			get_city_tree() {
				let res = []
				if (cityRows.length) {
					// 递归生成
					res = this.handleTree(cityRows)
				}
				return res
			},


			handleTree(data, parent_code = null) {
				let res = []

				let keys = {
					id: 'code',
					pid: 'parent_code',
					children: 'children',

					text: 'name',
					value: 'code'
				}

				let oneItemDEMO = {
					text: '',
					value: '',
					children: []
				}
				let oneItem = {}

				// 循环
				for (let index in data) {
					// 判断
					if (parent_code === null) {
						// 顶级菜单 - 省
						if (!data[index].hasOwnProperty(keys.pid) || data[index][keys.pid] == parent_code) {
							// 不存在parent_code，或者已匹配
							oneItem = JSON.parse(JSON.stringify(oneItemDEMO))
							oneItem.text = data[index][keys.text]
							oneItem.value = data[index][keys.value]

							// 递归下去
							oneItem.children = this.handleTree(data, data[index][keys.id])
							res.push(oneItem)

						} else {
							// 匹配不到，跳过
						}

					} else {
						// 非顶级菜单 - 市、区、街道
						if (data[index].hasOwnProperty(keys.pid) && data[index][keys.pid] == parent_code) {
							// 已匹配
							oneItem = JSON.parse(JSON.stringify(oneItemDEMO))
							oneItem.text = data[index][keys.text]
							oneItem.value = data[index][keys.value]

							// 递归下去
							oneItem.children = this.handleTree(data, data[index][keys.id])
							res.push(oneItem)

						} else {
							// 匹配不到，跳过
						}

					}

				}
				return res
			},

			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					// const result = await this.uploadFilePromise(lists[i].url)
					this.$http.urlFileUpload({
						files: [{
							path: lists[i].url
						}], // 必填 临时文件路径 格式: [{path: "图片地址"}]
						// data:"向服务器传递的参数", //可不填
						name: "file", //默认 file
					}).then(res => {
						console.log(res);
						if (res.code == 200) {
							let item = this[`fileList${event.name}`][fileListLen]
							this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
								status: 'success',
								message: '',
								url: res.data.url
							}))
							fileListLen++
						}
					})
				}
			},
			uploadFilePromise(url) {
				this.$http.urlFileUpload({
					files: [{
						path: url
					}], // 必填 临时文件路径 格式: [{path: "图片地址"}]
					// data:"向服务器传递的参数", //可不填
					name: "file", //默认 file
				}).then(res => {
					console.log(res);
					if (res.code == 200) {
						return res.data.url
					}
				})
			},

			closeIsShow() {
				this.isShowStartTime = false
				this.isShowEndTime = false
			},
			confirmStart(e) {
				this.periodTimeList[this.idx].beginTime = e.value
				this.closeIsShow()
			},
			confirmEnd(e) {
				this.periodTimeList[this.idx].endTime = e.value
				this.closeIsShow()
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},


		}
	}
</script>

<style lang="less">
	page {
		background: #FAFAFA;
	}

	.addGasStation {
		padding: 20rpx 24rpx;
		padding-bottom: 200rpx;

		.addGasStationForm {
			width: 702rpx;
			background: #FFFFFF;
			border-radius: 14rpx 14rpx 14rpx 14rpx;
			box-sizing: border-box;
			padding: 30rpx 20rpx;

			.formItemTitle {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;

				text {
					color: #FF0000;
					font-size: 28rpx;
					margin-right: 10rpx;
				}

				.title {
					font-size: 28rpx;
					color: #333333;
				}
			}

			.formItemValue {
				background: #FAF7F6;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				border: 2rpx solid #E3CEC6;
				padding: 20rpx 50rpx;
				box-sizing: border-box;
				display: flex;
				align-items: center;

				.ipt {
					font-size: 24rpx;
					flex: 1;
				}

				.downIcon {
					width: 22rpx;
					height: 11rpx;
				}
			}

			.addBtn {
				margin-left: 22rpx;
				width: 155rpx;
				height: 63rpx;
				background: #FAF7F6;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				border: 2rpx dashed #FF4502;
				font-size: 24rpx;
				color: #FF4502;
				text-align: center;
				line-height: 63rpx;
				margin-left: auto;
			}
		}

		.formItem {
			margin-bottom: 30rpx;
		}

	}

	.saveBtn {
		position: fixed;
		width: 702rpx;
		height: 100rpx;
		background: linear-gradient(90deg, #FF4502 0%, #FF8903 100%);
		border-radius: 50rpx 50rpx 50rpx 50rpx;
		text-align: center;
		line-height: 100rpx;
		font-weight: bold;
		font-size: 32rpx;
		color: #FFFFFF;
		left: 50%;
		bottom: 50rpx;
		transform: translateX(-50%);
		z-index: 999;
	}

	.formItemValueBox {
		display: flex;
		align-items: center;

		.text {
			text-align: right;
			font-size: 28rpx;
			color: #333333;
			width: 120rpx;
			margin-right: 14rpx;
		}
	}
</style>