<template>
	<view class="content">
		<view class="title-box">
			<view class="title">
				<view class="title">价格采集</view>
			</view>
		</view>
		
		<view class="container-box">
			<view class="container">
				<view class="info-box">
					<!-- <view>
						<u-cell title="经度" :value="position.longitude"></u-cell>
						<u-cell title="纬度" :value="position.latitude"></u-cell>
					</view> -->
					<view>
					<u-cell title="站点名称" v-if="isSelfPriceMonitor" :value="monitor.name"></u-cell>
					<u-cell title="站点名称" v-if="!isSelfPriceMonitor" :value="monitor.name" :is-link="true" @click="show = true"></u-cell>
					<u-cell title="详细地址" :value="monitor.address"></u-cell>
					<u-cell title="价格采集人" :value="monitor.userName"></u-cell>
					<u-cell title="市州" :value="monitor.sysOrgName"></u-cell>
					<u-cell title="联系方式" :value="monitor.userPhone"></u-cell>
					<u-cell title="采集时间" :value="nowDate"></u-cell>
				</view>
				</view>
				<view class="price">
					<view class="title">价格信息</view>
					<view class="item-table">
						<view class="center title-1">粮食品类: 原粮</view>
						<u-row class="row">
							<u-col :span="4">
								<view class="center">品种</view>
							</u-col>
							<u-col :span="8">
								<view class="center">收购价</view>
							</u-col>
						</u-row>
						<u-row v-for="(item, index) in price1" :key="index" class="row">
							<u-col :span="4">
								<view class="center">{{item.name}}</view>
							</u-col>
							<u-col :span="8">
								<view class="center"><u-input v-model.number="item.price"></u-input></view>
							</u-col>
						</u-row>
					</view>

					<view class="item-table">
						<view class="center title-1">粮食品类: 储备粮</view>
						<u-row class="row">
							<u-col :span="4">
								<view class="center">品种</view>
							</u-col>
							<u-col :span="4">
								<view class="center">出库价</view>
							</u-col>
							<u-col :span="4">
								<view class="center">入库价</view>
							</u-col>
						</u-row>
						<u-row v-for="(item, index) in price2" :key="index" class="row">
							<u-col :span="4">
								<view class="center">{{item.name}}</view>
							</u-col>
							<u-col :span="4">
								<view class="center m-l-2"><u-input v-model.number="item.price1"></u-input></view>
							</u-col>
							<u-col :span="4">
								<view class="center m-l-2"><u-input v-model.number="item.price2"></u-input></view>
							</u-col>
						</u-row>
					</view>
					
					<view class="item-table">
						<view class="center">粮食品类: 成品粮</view>
						<u-row class="row">
							<u-col :span="4">
								<view class="center">品种</view>
							</u-col>
							<u-col :span="4">
								<view class="center">批发价</view>
							</u-col>
							<u-col :span="4">
								<view class="center">零售价</view>
							</u-col>
						</u-row>
						<u-row v-for="(item, index) in price3" :key="index" class="row">
							<u-col :span="4">
								<view class="center">{{item.name}}</view>
							</u-col>
							<u-col :span="4">
								<view class="center m-l-2"><u-input v-model.number="item.price1"></u-input></view>
							</u-col>
							<u-col :span="4">
								<view class="center m-l-2"><u-input v-model.number="item.price2"></u-input></view>
							</u-col>
						</u-row>
					</view>
					
					<view class="item-table">
						<view class="center">粮食品类: 杂粮</view>
						<u-row class="row">
							<u-col :span="4">
								<view class="center">品种</view>
							</u-col>
							<u-col :span="4">
								<view class="center">批发价</view>
							</u-col>
							<u-col :span="4">
								<view class="center">零售价</view>
							</u-col>
						</u-row>
						<u-row v-for="(item, index) in price4" :key="index" class="row">
							<u-col :span="4">
								<view class="center">{{item.name}}</view>
							</u-col>
							<u-col :span="4">
								<view class="center m-l-2"><u-input v-model.number="item.price1"></u-input></view>
							</u-col>
							<u-col :span="4">
								<view class="center m-l-2"><u-input v-model.number="item.price2"></u-input></view>
							</u-col>
						</u-row>
					</view>
					
					<view class="remark">
						<u--textarea v-model="remark" placeholder="备注：本周/日采集数据与上周/日采集数据作对比价格超出5%，需要填写备注"></u--textarea>
					</view>
				</view>
				<view class="btns">
				<u-button text="上传" type="primary" class="btn-upload" @click="upload"></u-button>
			</view>
		</view>
		</view>
		<u-action-sheet 
			:actions="allMonitor" 
			:closeOnClickOverlay="true" 
			:closeOnClickAction="true"
			title="选择站点"
			:show="show"
			@select="chooseMonitor"
			@close="show = false">
		</u-action-sheet>
	</view>
</template>

<script>
	
	import { getMonitorInfoByPoint, getMonitorInfo, addCollect } from '@/api/collect'
	import { dateFormat } from '@/utils/dates'
	import { clone } from '@/utils/common'
	
	const DEFAULT_MONITOR = {
		name: '',
		address: '',
		userName: '',
		sysOrgName: '',
		userPhone: '',
		
	}
	
	const PURCHASE_PRICE = 1 // 收购价
	const INBOUND_PRICE = 2// 入库价
	const OUTBOUND_PRICE = 3 // 出库价
	const EX_FACTORY_PRICE = 4 // 出厂价
	const WHOLESALE_PRICE = 5 // 批发价
	const RETAIL_PRICE = 6 // 零售价
	
	export default {
		data() {
			return {
				showTips: false,
				loadingMsg: '',
				position: {
					longitude: null, // 经度
					latitude: null, // 纬度
				},
				price1: [
					{
						name: '小麦',
						firstLevel: 1,
						secondLevel: 11,
						threeLevel: 0,
						price: null,
					},
					{
						name: '青稞',
						firstLevel: 1,
						secondLevel: 12,
						threeLevel: 0,
						price: null,
					},
					{
						name: '油菜籽',
						firstLevel: 1,
						secondLevel: 13,
						threeLevel: 0,
						price: null,
					},
				],
				price2: [
					{
						name: '省储小麦',
						firstLevel: 4,
						secondLevel: 41,
						threeLevel: 0,
						price1: null,
						price2: null,
					},
					{
						name: '省储青稞',
						firstLevel: 4,
						secondLevel: 42,
						threeLevel: 0,
						price1: null,
						price2: null,
					},
					{
						name: '省储菜籽油',
						firstLevel: 4,
						secondLevel: 43,
						threeLevel: 0,
						price1: null,
						price2: null,
					},
				],
				price3: [
					{
						name: '一级菜籽油',
						firstLevel: 3,
						secondLevel: 31,
						threeLevel: 311,
						price1: null,
						price2: null,
					},
					{
						name: '三级菜籽油',
						firstLevel: 3,
						secondLevel: 31,
						threeLevel: 312,
						price1: null,
						price2: null,
					},
					{
						name: '小榨菜籽油',
						firstLevel: 3,
						secondLevel: 31,
						threeLevel: 313,
						price1: null,
						price2: null,
					},
					{
						name: '特一粉',
						firstLevel: 3,
						secondLevel: 32,
						threeLevel: 321,
						price1: null,
						price2: null,
					},
					{
						name: '牛肉面粉',
						firstLevel: 3,
						secondLevel: 32,
						threeLevel: 322,
						price1: null,
						price2: null,
					},
					{
						name: '一级长粒粳米',
						firstLevel: 3,
						secondLevel: 33,
						threeLevel: 331,
						price1: null,
						price2: null,
					},
					{
						name: '一级圆粒粳米',
						firstLevel: 3,
						secondLevel: 33,
						threeLevel: 332,
						price1: null,
						price2: null,
					},
				],
				price4: [
					{
						name: '黄豆',
						firstLevel: 2,
						secondLevel: 21,
						threeLevel: 0,
						price1: null,
						price2: null,
					},
					{
						name: '玉米面',
						firstLevel: 2,
						secondLevel: 22,
						threeLevel: 0,
						price1: null,
						price2: null,
					},
					{
						name: '小米',
						firstLevel: 2,
						secondLevel: 23,
						threeLevel: 0,
						price1: null,
						price2: null,
					},
				],
				monitor: DEFAULT_MONITOR,
				allMonitor: [],
				userId: null,
				nowDate: null,
				isSelfPriceMonitor: false,
				show: false,
				remark: null,
			}
		},
		mounted() {
			uni.showModal({
				content: '上报需要获取当前设备定位信息,是否允许?',
				confirmText: '允许',
				cancelText: '不允许',
				success: (ret) => {
					if(ret.confirm)
						this.getPosition()
					else 
						uni.redirectTo({
							url: '/pages/collectionList/index'
						})
				},
				fail: () => {
					uni.redirectTo({
						url: '/pages/collectionList/index'
					})
				}
			})
		},
		methods: {
			doGetPosition() {
				return new Promise((resolve, reject) => {
					uni.getLocation({
						altitude: true,
						isHighAccuracy: true,
						success: (ret) => {
							resolve(ret)
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
				
				// for debug
				// return Promise.resolve({
				// 	longitude: 40.7124,
				// 	latitude: -74.006,
				// })
			},
			getPosition() {
				this.loadingMsg = '正在获取定位'
				uni.showLoading({
					title: this.loadingMsg,
					mask: true
				})
				this.doGetPosition()
					.then(ret => {
						this.position.latitude = ret.latitude
						this.position.longitude = ret.longitude
					}).then(_ => {
						// 请求所有站点数据
						return getMonitorInfo().then(resp => {
							console.log('所有站点', resp);
							const all = resp.data
						
							this.allMonitor = all.map(d => {
								const ret = {
									... d,
									disabled: d.locationSwitch == 1
								}
								if(ret.disabled) {
									ret.subname = '该站点必须实地采集'
								}
								return ret
							})
						})
					}).then(_ => {
						if(this.allMonitor.length <= 0) {
							return Promise.reject('你没有可用的检测点')
						}else {
							this.userId = this.allMonitor[0].userId
							return Promise.resolve()
						}
					}).then(_ => {
						// 请求检测点
						return getMonitorInfoByPoint({
							userId: this.userId,
							point: `POINT(${this.position.latitude} ${this.position.longitude})`
							// point: `POINT(1 ${this.position.latitude})`
						}).then(resp => {
							console.log('最近站点', resp);
							if(resp.data.status === 'error') {
								uni.showToast({
									icon: 'error',
									title: resp.data.message
								})
								this.monitor = DEFAULT_MONITOR
								this.isSelfPriceMonitor = false
								return 
							}else {
								const data = this.allMonitor.find(d => d.id === resp.data.id)
								if(data) {
									this.monitor = data
									this.isSelfPriceMonitor = true
								}else {
									uni.showToast({
										icon: 'error',
										title: '最近站点数据异常'
									})
									this.monitor = DEFAULT_MONITOR
									this.isSelfPriceMonitor = false
									return 
								}
							}
						})
					}).then(_ => {
						this.nowDate = dateFormat(new Date())
					}).catch(err => {
						console.log(err);
						uni.showToast({
							title: err
						})
					})
			},
			chooseMonitor(m) {
				this.monitor = m
			},
			calPrice(rawData, dataList, priceType1, priceType2) {
				const temp1 = clone(rawData)
				const temp2 = clone(rawData)
				delete temp1.name
				delete temp2.name
				temp1.priceType = priceType1
				temp2.priceType = priceType2
				temp1.price = rawData.price1
				temp2.price = rawData.price2
				delete temp1.price1
				delete temp1.price2
				delete temp2.price1
				delete temp2.price2
				dataList.push(temp1)
				dataList.push(temp2)
			},
			upload() {
				if(this.monitor === DEFAULT_MONITOR) {
					uni.showToast({
						title: '请选择监测点',
						icon: "error"
					})
					return
				}
				const dataList = []
				this.price1.forEach(d => {
					const temp = clone(d)
					delete temp.name
					temp.priceType = PURCHASE_PRICE
					dataList.push(temp)
				})
				this.price2.forEach(d => {
					this.calPrice(d, dataList, OUTBOUND_PRICE, INBOUND_PRICE)
				})
				this.price3.forEach(d => {
					this.calPrice(d, dataList, WHOLESALE_PRICE, RETAIL_PRICE)
				})
				this.price4.forEach(d => {
					this.calPrice(d, dataList, WHOLESALE_PRICE, RETAIL_PRICE)
				})
				const data = {
					type: 0, // 移动端
					priceMonitorId: this.monitor.id,
					userCollectId: this.monitor.userId,
					userId: this.monitor.userId,
					isSelfPriceMonitor: this.isSelfPriceMonitor ? 1 : 0,  // 是否实地采集， 0 否  1 是
					userCollectName: this.monitor.userName,
					userCollectPhone: this.monitor.userPhone,
					userCollectDate: this.nowDate,
					remark: this.remark,
					categoryAddParamList: dataList,
					point: `${this.position.longitude},${this.position.latitude}`
				}
				console.log(data);
				addCollect(data).then(resp => {
					console.log('保存上报', resp);
					if(resp.code == 200) {
						uni.showToast({
							title: '保存成功',
							icon: 'success',
							mask: true,
							duration: 1_500,
						})
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/collectionList/index'
							})
						}, 1_500)
					}else {
						uni.showToast({
							title: resp.msg,
							icon: 'error',
						})
					}
				})
			},
			getPositionErrMessage(errCode) {
				console.log('定位失败', errCode);
				let message;
				switch (errCode) {
					case '1505004':
						message = '获取定位失败,请开启定位权限';
						break;
					case '1505005':
						message = '获取定位失败,请开启高经度定位权限';
						break;
					case '1505021':
						message = '获取定位失败,请重试';
						break;
					case '1505022':
						message = '获取定位失败,设备不支持当前类型定位';
						break;
					case '1505023':
						message = '获取定位失败,设备不支持逆地理编码';
						break;
					case '1505024':
						message = '获取定位失败,请开启设备的定位功能';
						break;
					case '1505025':
						message = '获取定位失败,逆地理编码捕获失败';
						break;
					case '1505026':
						message = '获取定位失败,捕获定位失败';
						break;
					default:
						message = '获取定位失败'
				}
				return message
			}
		}
	}
</script>

<style lang="scss" scoped>
	
.container{
	background-color: #fff;
	border-radius: 24rpx;
	
	.info-box{
		padding: 0 30rpx;
	}
}

.price {
	// margin: 5px;
	// padding-bottom: 70px;
	.title {
		position: relative;
		margin: 10px;
		display: inline-flex;
		justify-content: center;
		align-items: flex-end;
		font-weight: bold;
		z-index: 1;
		
		&::after{
			content: "";
			position: absolute;
			width: 80%;
			height: 20rpx;
			background: url(@/static/bg-item-title.png) top center no-repeat;
			background-size: 100% 100%;
			z-index: -1;
		}
	}
	.title-1 {
		position: relative;
		margin: 10px 0;
		padding: 20rpx 0;
		padding-left: 30rpx;
		display: flex;
		align-items: center;
		background-color: #f4f4f4;
		font-weight: bold;
		z-index: 1;
		
		&::after{
			content: "";
			position: absolute;
			left: 0;
			margin-right: 20rpx;
			width: 12rpx;
			height: 30rpx;
			background: linear-gradient(0deg,#48d9f4 0%,#29a1ff 100%);
			border-radius: 24rpx;
			z-index: -1;
		}
	}

	.row {
		margin-top: 5px;
	}

	.center {
		text-align: center;
	}

	.m-l-2 {
		margin-left: 2px;
	}
	
	.remark{
		margin: 20rpx;
	}
	
}
.btns {
	margin-bottom: 20px;
	width: 100%;
	height: 50px;
	.btn-upload {
		width: 80%;
		margin-bottom: 10px;
	}
}

::v-deep{
	.u-cell__body{
		padding: 20rpx 0!important;
	}
}
</style>