<template>
	<view class="page">
		<view class="step_num">
			<view class="step step1">完善维修记录</view>
			<view class="step step2">添加维修备件</view>
		</view>
		<view class="item " @click="onShowDatePicker(1)">
			<view class="itemname redMi">实际开工时间</view>
			<view class="itemtext">
				<view >
					<input class="iteminput InputRightMargin" disabled placeholder="请选择时间" :value='recordInfo.startTime'/>
					<img src="../../static/img/dateIcon.png" class="dateIcon" />
				</view>
			</view>
		</view>
		<view class="item item_line" @click="onShowDatePicker(2)">
			<view class="itemname redMi">实际完工时间</view>
			<view class="itemtext">
				<view >
					<input class="iteminput InputRightMargin" disabled placeholder="请选择时间" :value='recordInfo.endTime'/>
					<img src="../../static/img/dateIcon.png" class="dateIcon" />
				</view>
			</view>
		</view>
		
		<view class="item">
			<view class="itemname redMi">故障类型</view>
			<view class="itemtext">
				<input class="iteminput InputRightMargin" disabled placeholder="请选择"  @click="showSinglePickerType" v-model="recordInfo.typeName"/>
				<uni-icons type="arrowright" class="myarrowright" style="right: 0px;"></uni-icons>
			</view>
		</view>
		<!-- <view class="item " @click="onShowDatePicker(3)">
			<view class="itemname">设备停机时间</view>
			<view class="itemtext">
				<view >
					<input class="iteminput InputRightMargin" disabled placeholder="请选择时间" :value='recordInfo.offTime'/>
					<img src="../../static/img/dateIcon.png" class="dateIcon" />
				</view>
			</view>
		</view> -->
		<view class="item ">
			<view class="itemname">停机时长</view>
			<view class="itemtext">
				<input class="iteminput timeRightMargin" type="number" placeholder="请输入停机时长" v-model="recordInfo.offHour" @change="infoChange()"/>
				<view class="itemunit">小时</view>
			</view>
		</view>
		<view class="item item_line">
			<view class="itemname redMi">使用情况</view>
			<view class="itemtext">
				<input class="iteminput InputRightMargin" disabled placeholder="请选择"  @click="showSinglePicker" v-model="recordInfo.usageName"/>
				<uni-icons type="arrowright" class="myarrowright" style="right: 0px;"></uni-icons>
			</view>
		</view>
		<view class="item item_line item_textarea">
			<view class="itemname redMi">故障原因</view>
			<textarea class="textarea" placeholder="请输入故障原因" v-model="recordInfo.cause" @change="infoChange()"></textarea>
		</view>
		<view class="item item_line item_textarea">
			<view class="itemname redMi">维修方案</view>
			<textarea class="textarea" placeholder="请输入维修方案" v-model="recordInfo.solution" @change="infoChange()"></textarea>
		</view>
		<view class="item ">
			<view class="itemname">维修工时</view>
			<view class="itemtext">
				<input class="iteminput timeRightMargin" type="number" placeholder="请输入工时" v-model="recordInfo.manHour" @change="infoChange()"/>
				<view class="itemunit">小时</view>
			</view>
		</view>
		<view class="item ">
			<view class="itemname">工时费</view>
			<view class="itemtext">
				<input class="iteminput timeRightMargin" type="number" placeholder="请输入工时费" v-model="recordInfo.manHourCost" @change="infoChange()"/>
				<view class="itemunit">元</view>
			</view>
		</view>
		<view class="item item_line">
			<view class="itemname">维修费用</view>
			<view class="itemtext">
				<input class="iteminput InputRightMargin" type="number" placeholder="请输入价格" v-model="recordInfo.cost" disabled/>
				<view class="itemunit" >元</view>
			</view>
		</view>
		<view class="photo_container item_line">
			<view class="pzqd">维修照片</view>
			<view class="photo_out">
				<view class="imgwrap" v-for="(items,index) in imgsrc_list_local" :key="index">
					<view class="myimgBox" @click="reUpload(index)">
						<view class="img">
							<img class="uploadimg" :src="items" />
							<view class="cxsc">重新上传</view>
						</view>
					</view>
					<img src="../../static/img/delete.png" class="deleteimg" @click="deleteImg(index)" />
				</view>
				<view class="imgwrap" @click="chooseImg()" >
					<view class="myimgBox">
						<view class="img upload_btn">
							<img src="../../static/img/uploadimg.png" />
							<view class="sctp">上传图片</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="fixMargin"></view>
		<view class="fixBottom">
			<button type="primary" plain="true"  style="width: 90%; background: #fff;" @click="toNext()">下一步</button>
		</view>
		<mx-datepicker type="datetime" :value="value_time" :show="showPicker" @confirm="onSelected" @cancel="onSelected"></mx-datepicker>
		<mpvue-picker themeColor="#007AFF" ref="mpvuePicker" mode="selector" :deepLength="deepLength"
		 @onConfirm="pickerConfirm" :pickerValueArray="usageArray"></mpvue-picker>
		<mpvue-picker themeColor="#007AFF" ref="mpvuePicker2" mode="selector" :deepLength="deepLength"
		  @onConfirm="pickerConfirmType" :pickerValueArray="typeArray"></mpvue-picker>
		  
		<view class="goHome" @click='goMain("repairDealInfo")'>
		 	<img src="../../static/img/gohome.png">
		</view>
	</view>
</template>

<script>
	import { dataToTime } from '@/common/tools.js'
	import { getCurrentTime } from '@/common/tools.js'
	import { getCurrentDateTime } from '@/common/tools.js'
	import {
		mapState,
		mapMutations
	} from 'vuex'
	
	import {
		config
	} from '../../request/js/config.js'
	import mpvuePicker from '@/components/mpvue-picker/mpvuePicker.vue';
	import mxDatepicker from '@/components/mx-datepicker/mx-datepicker.vue'
	import uniIcons from "@/components/uni-icons/uni-icons.vue"
	export default {
		components: {
			mxDatepicker,mpvuePicker,
			uniIcons
		},
			computed: {
            // ...mapState(['repairRecordList']),
            ...mapState(['partList']),
        },
		data() {
			return {
				config:config,
				imgsrc_list: [],
				imgsrc_list_local: [],
				showPicker: false,
				time_index:'',   
				value_time:'',
				id: '',
				sparePartsCost: 0,
				recordId:'',
				typeArray:[],
				usageArray :[],
				deepLength:1,
				recordInfo:{},
				from:""
			}
		},
		onLoad(option) {
			var _this = this;
			this.id = option.id;
			this.sparePartsCost = option.sparePartsCost?option.sparePartsCost:0;
			this.from=option.from;
			if (this.id == undefined) {
				uni.reLaunch({
					url: 'eqRepair'
				});
				return false;
			}
			//重置下。
			this.recordId = option.recordId;
			if(this.from==undefined){
			this.setpartList([]);
				this.$http.request({
					url: '/apis/repairEvent/getRecordDetailByEventId',
					params: {eventId:this.id},
				}).then(res => {
					if (res.data.code == 0) {
						if(res.data.recordDetail){
							this.recordInfo = res.data.recordDetail.recordInfo;
							
							for(var i=0;i<res.data.recordDetail.repairRecordImage.length;i++){
								this.imgsrc_list.push(res.data.recordDetail.repairRecordImage[i].filePath);
								this.imgsrc_list_local.push(config.imgURL+res.data.recordDetail.repairRecordImage[i].filePath);
							}
							
							var list= _this.formaterData(res.data.recordDetail.mapList);
							_this.setpartList(list);
							uni.setStorage({
							    key: 'repairDealInfo',
							    data: {
									info:_this.recordInfo,
									imgsrc_list:_this.imgsrc_list,
									imgsrc_list_local:_this.imgsrc_list_local
								},
							    success: function () {
							    }
							});
						}
					
					}
				}).catch(err => {
					console.log(err)
					uni.showToast({
						title: '获取信息失败',
						duration: 2000,
						icon:"none"
					});
				});
			}else{
			// 	console.log(this.partList)
			// 	//返回。就回显
				uni.getStorage({
					key: 'repairDealInfo',
					success: function (res) {
						var session = res.data;
						_this.recordInfo = session.info||{};
						_this.imgsrc_list = session.imgsrc_list||[];
						_this.imgsrc_list_local = session.imgsrc_list_local||[];
					}
				});
			}
			//初始化获取 任务等级数据字典。
			this.$http.request({
				 url: '/apis/dict/getDictsByType',
				 params: {
				   type: 'device_malfunction'
				 },
			}).then(res=>{
				if(res.statusCode == '200'){
					var useType = res.data.datas;
					for (let i = 0; i < useType.length; i++) {
					    var myVal=
					    	{
					    		'label': useType[i].name,
					    		'value': useType[i].id
					    	}
					    _this.typeArray.push(myVal);
					}
					if(!_this.recordInfo.type){
						_this.recordInfo.type = useType[0].id;
						_this.recordInfo.typeName = useType[0].name;
						_this.infoChange();
					}
				}
			}).catch(err=>{
				console.log(err);
			});
			
			this.$http.request({
			  url: '/apis/dict/getDictsByType',
			  params: {
			    type: "device_status"
			  },
			}).then(res=>{
				if(res.statusCode == '200'){
					var useType = res.data.datas;
					for (let i = 0; i < useType.length; i++) {
					    var myVal=
					    	{
					    		'label': useType[i].name,
					    		'value': useType[i].id
					    	}
					    _this.usageArray.push(myVal);
					}
					if(!_this.recordInfo.usage){
						_this.recordInfo.usage = useType[0].id;
						_this.recordInfo.usageName = useType[0].name;
						_this.infoChange();
					}
				}
			}).catch(err=>{
			});
		},
		watch: {
			recordInfo:{
				handler(newV){					
					if(newV){
						this.recordInfo.cost = Number(this.recordInfo.manHourCost) +Number(this.sparePartsCost)
					}
				},
				deep: true
			}
		},
		methods: {
			...mapMutations(['setrepairRecordList','setpartList']),
			//列表数据格式化
			formaterData(data) {
				var resData = [];
				data.forEach((vals, index) => {
					var combineJSON = {
						id: vals.partId,
						title: vals.name,
						amount:vals.amount,//数量
						price:vals.price,//单价
						titleNumber:"["+vals.code+"]",
						checked:false,
						contentList: [{
								id: 1,
								isDouble: true,
								labelName: '规格型号',
								labelContent: vals.type
							},
							{
								id: 2,
								isDouble: true,
								labelName: '库位',
								labelContent: vals.facilityName
							},
							{
								id: 3,
								isDouble: true,
								labelName: '设备类型',
								labelContent: vals.typeName
							}
						],
					}
					resData.push(combineJSON);
				});
				return resData;
			},
			pickerConfirmType(e){
				this.recordInfo.type= e.value[0];
				this.recordInfo.typeName = e.label;
				this.infoChange();
				this.$forceUpdate();
			},
			pickerConfirm(e){
				this.recordInfo.usage = e.value[0]; 
				this.recordInfo.usageName = e.label;
				this.infoChange();
				this.$forceUpdate();
			},
			showSinglePicker() {
				this.pickerValueDefault = [0];
				this.$refs.mpvuePicker.show();
			},
			showSinglePickerType() {
				this.pickerValueDefault = [0];
				this.$refs.mpvuePicker2.show();
			},
			toNext() {
				if(!this.recordInfo.startTime){
					uni.showToast({
						    title: '请选择实际开工时间',
						    duration: 2000,
							icon:"none"
						});
					return false;
				}
				if(!this.recordInfo.endTime){
					uni.showToast({
						    title: '请选择实际完工时间',
						    duration: 2000,
							icon:"none"
						});
					return false;
				}
				if(dataToTime(this.recordInfo.endTime)<=dataToTime(this.recordInfo.startTime)) {
					uni.showToast({
						    title: '开始时间不能大于结束时间',
						    duration: 2000,
							icon:"none"
						});
					return false;
				}
				if(!this.recordInfo.cause){
					uni.showToast({
						    title: '请填写故障原因',
						    duration: 2000,
							icon:"none"
						});
					return false;
				}
				if(!this.recordInfo.solution){
					uni.showToast({
						    title: '请填写维修方案',
						    duration: 2000,
							icon:"none"
						});
					return false;
				}
				if(this.recordId){
					console.log(this.sparePartsCost)
					uni.navigateTo({
						url: "repairStep2?id=" + this.id+"&recordId="+this.recordId+"&sparePartsCost="+this.sparePartsCost
					});
				}else{
					uni.navigateTo({
						url: "repairStep2?id=" + this.id+"&sparePartsCost="+this.sparePartsCost
					});
				}
				
			},
			infoChange:function(){
				//保存当前修改信息
				var repairDealInfo =  uni.getStorageSync('repairDealInfo');
				if(!repairDealInfo){
					repairDealInfo = {}
				}
				repairDealInfo.info = this.recordInfo;
				uni.setStorage({
				    key: 'repairDealInfo',
				    data: repairDealInfo,
				    success: function () {
				    }
				});
			},
			onShowDatePicker(n) { //显示
				this.time_index=n;
				if(n==1){
					this.value_time=this.recordInfo.startTime;
				}else if(n==2){
					this.value_time=this.recordInfo.endTime;
				}else if(n==3){
					this.value_time=this.recordInfo.offTime;
				}
				this.showPicker = true;
			},
			onSelected(e) { //选择
				this.showPicker = false;
				if (e) {
					if(this.time_index==1){
						this.recordInfo.startTime = e.value+":00";
					}else if(this.time_index==2){
						this.recordInfo.endTime = e.value+":00";
					}else if(this.time_index==3){
						this.recordInfo.offTime = e.value+":00";
					}
					this.infoChange();
				}
			},
			//上传
			chooseImg() {
				this.uploadImg();
			},
			//重新上传
			reUpload(index) {
				this.uploadImg(index);
			},
			uploadImg(indexnum) {
				var _this = this;
				//#ifdef APP-PLUS
				var count_ = 9;
				//#endif
				//#ifndef APP-PLUS
				var count_ = 1;
				//#endif
				if (indexnum != undefined) {
					count_ = 1;
				}
				uni.chooseImage({
					count: count_,
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						//#ifdef APP-PLUS
						let imgs = chooseImageRes.tempFilePaths.map((value, index) => {
							return {
								name: "file" + (index + 1), //注意这一行，uni的hello的示例中，这里为key名+index，这样是无法和使用一个固定key名接多个文件的php接口对接上的改为数组下标形式的字符串就解决这个问题了。其效果等同于在html页面上多个同name文件域同时提交表单。  
								uri: value
							}
						});
						uni.uploadFile({
							url: config.baseURL + '/apis/file/uploadMulti', //接口地址
							files: imgs,
							fileType: "image",
							name: 'files',
							success: (uploadFileRes) => {
								var arr = [];
								for (var i = 0; i < JSON.parse(uploadFileRes.data).result.length; i++) {
									arr.push(JSON.parse(uploadFileRes.data).result[i].filePath);
								}
								if (indexnum != undefined) { //是重新上传
									_this.imgsrc_list[indexnum] = arr[0]
									_this.imgsrc_list_local[indexnum] = chooseImageRes.tempFilePaths[0]
								} else {
									_this.imgsrc_list = _this.imgsrc_list.concat(arr);
									_this.imgsrc_list_local = _this.imgsrc_list_local.concat(chooseImageRes.tempFilePaths);

								}
								_this.$forceUpdate();
								var repairDealInfo =  uni.getStorageSync('repairDealInfo');
								if(!repairDealInfo){
									repairDealInfo = {}
								}
								repairDealInfo.imgsrc_list = _this.imgsrc_list;;
								repairDealInfo.imgsrc_list_local = _this.imgsrc_list_local;
								uni.setStorage({
								    key: 'repairDealInfo',
								    data: repairDealInfo,
								    success: function () {
								    }
								});
							},
							fail:function(){
								uni.showToast({
									title: '上传图片失败',
									duration: 2000,
									icon:"none"
								});
							}
						});
						//#endif
						//#ifndef APP-PLUS
						uni.uploadFile({
							url: config.baseURL + '/apis/file/upload', //接口地址
							filePath: tempFilePaths[0],
							fileType: "image",
							name: 'file',
							success: (uploadFileRes) => {
								var arr = [];
								if (indexnum != undefined) { //是重新上传
									_this.imgsrc_list[indexnum] =JSON.parse(uploadFileRes.data).filePath;
									_this.imgsrc_list_local[indexnum] = chooseImageRes.tempFilePaths[0];
								} else {
									_this.imgsrc_list.push(JSON.parse(uploadFileRes.data).filePath)
									_this.imgsrc_list_local.push(chooseImageRes.tempFilePaths)
								}
								_this.$forceUpdate();
								var repairDealInfo =  uni.getStorageSync('repairDealInfo');
								if(!repairDealInfo){
									repairDealInfo = {}
								}
								repairDealInfo.imgsrc_list = _this.imgsrc_list;;
								repairDealInfo.imgsrc_list_local = _this.imgsrc_list_local;
								uni.setStorage({
								    key: 'repairDealInfo',
								    data: repairDealInfo,
								    success: function () {
								    }
								});
							},
							fail:function(){
								uni.showToast({
									title: '上传图片失败',
									duration: 2000,
									icon:"none"
								});
							}
							
						});
						//#endif
					}
				});
			},
			//删除图片
			deleteImg(index) {
				this.imgsrc_list.splice(index, 1);
				this.imgsrc_list_local.splice(index, 1);
				this.$forceUpdate();
				var repairDealInfo =  uni.getStorageSync('repairDealInfo');
				repairDealInfo.imgsrc_list = this.imgsrc_list;
				repairDealInfo.imgsrc_list_local = this.imgsrc_list_local;
				uni.setStorage({
				    key: 'repairDealInfo',
				    data: repairDealInfo,
				    success: function () {
				    }
				});
			}
		},
		onBackPress(options) { //取消默认的返回事件.用来返回上一页时重新加载页面，删除本地缓存的巡检操作
			// if (options.from === 'backButton' || options.from === 'backbutton' || options.from === 'navigateBack') {
			// 	uni.redirectTo({
			// 		url: "patrolDetail?id=" + this.id
			// 	});
			// 	return true;

			// }

		},
	}
</script>

<style scoped>
	
	.step_num {
		display: flex;
		flex-direction: row;
		justify-content: center;
		width: 100%;
		height: 80upx;
		background-color: #fff;
		padding-right: 48upx;
		box-sizing: border-box;
		margin-bottom: 20upx;
	}

	.step {
		position: relative;
		font-size: 28upx;
		line-height: 80upx;
		padding-left: 30upx;
		float: left;
	}

	.step:before {
		position: absolute;
		left: 0px;
		content: '1';
		border: 1px solid #000;
		width: 28upx;
		height: 28upx;
		box-sizing: border-box;
		line-height: 28upx;
		border-radius: 200upx;
		font-size: 20upx;
		text-align: center;
		top: 26upx;
	}

	.step:after {
		position: absolute;
		content: '';
		width: 60upx;
		height: 2upx;
		background-color: #000;
		top: 40upx;
		left: 200upx;
	}

	.step2 {
		margin-left: 64upx;
		color: #828282;
	}

	.step2:before {
		content: '2';
		border: 2upx solid #828282;
	}

	.step2:after{
		background-color: transparent;
	}
	.itemunit{
		position: absolute;
		right: 0;
		top: 0;
		height: 92upx;
		line-height: 92upx;
		color: #999;
		font-size: 26upx;
	}

</style>
