<template>
	<view class="page">
		<mpvue-picker themeColor="#007AFF" ref="mpvuePicker" mode="selector" :deepLength="deepLength"
		 @onConfirm="pickerConfirm" :pickerValueArray="task_type"></mpvue-picker>
		 <mpvue-picker themeColor="#007AFF" ref="mpvuePickerLevel" mode="selector" :deepLength="deepLength"
		  @onConfirm="pickerConfirmLevel" :pickerValueArray="task_level"></mpvue-picker>
		<view class="item item_line">
			<view class="itemname redMi">任务主题</view>
			<view class="itemtext">
				<input class="iteminput" placeholder="请输入任务主题"  v-model="taskInfo.title" @change='dataChange'/>
			</view>
		</view>
		<view class="item">
			<view class="itemname redMi">任务类型</view>
			<view class="itemtext">
				<input class="iteminput InputRightMargin" disabled placeholder="请选择"  @click="showSinglePicker(1)" :value="taskInfo.taskTypeName"/>
				<uni-icons type="arrowright" class="myarrowright" style="right: 0px;"></uni-icons>
			</view>
		</view>
		<view class="item">
			<view class="itemname redMi">任务等级</view>
			<view class="itemtext">
				<input class="iteminput InputRightMargin" disabled placeholder="请选择"  @click="showSinglePicker(2)" :value="taskInfo.taskLevelName"/>
				<uni-icons type="arrowright" class="myarrowright" style="right: 0px;"></uni-icons>
			</view>
		</view>
		<view class="item item_line" @click="onShowDatePicker">
			<view class="itemname redMi">要求完成时间</view>
			<view class="itemtext">
				<view >
					<input class="iteminput InputRightMargin" disabled placeholder="请选择" :value='taskInfo.expireDate'/>
					<img src="../../static/img/dateIcon.png" class="dateIcon" />
				</view>
			</view>
		</view>
		
		<view class="item item_line item_textarea">
			<view class="itemname">详细描述</view>
			<textarea class="textarea" placeholder="请详细描述" v-model="taskInfo.detail" @change='dataChange'></textarea>
		</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="item">
			<view class="itemname redMi">责任人</view>
			<view class="itemtext" @click="selectPeople1()" >
				<input class="iteminput InputRightMargin" disabled placeholder="请选择责任人" :value='zrr.name'/>
				<img src="../../static/img/personlistIcon.png" class="dateIcon" />
			</view>
		</view>
		<view class="item item_line">
			<view class="itemname">抄送人</view>
			<view class="itemtext" @click="selectPeople2()" >
				<input class="iteminput InputRightMargin" disabled placeholder="请选择抄送人" :value="formatCsrName(targetList)"/>
				<img src="../../static/img/personlistIcon.png" class="dateIcon" />
			</view>
		</view>
		<view class="fixMargin"></view>
		<view class="fixBottom">
			<view class="uni-flex uni-row">
				<view style="-webkit-flex:1;flex: 1;">
					<button type="primary" plain="true"  style="width: 90%; background: #fff;" @click="goAddRepair('zc')">暂存</button>
				</view>
				<view style="-webkit-flex:1;flex: 1;">
					<button type="primary"  style="width: 90%;"  @click="goAddRepair('tj')">确认提交</button>
				</view>
			</view>
		</view>
		<mx-datepicker type="datetime" :value="taskInfo.expireDate" :show="showPicker" @confirm="onSelected" @cancel="onSelected"></mx-datepicker>
		<view class="goHome" @click='goMain("taskInfo")'>
			<img src="../../static/img/gohome.png">
		</view>
		<view class="mysearchlist" style="z-index: 10000;">
			<chooseUserSingle ref="mysearchlist" 
				:showsearch.sync="show_search_user1"
				:itemInfo_.sync="search_value_user1">
			</chooseUserSingle>
		</view>
		<view class="mysearchlist" style="z-index: 10000;">
			<chooseUserMulti ref="mysearchlist" 
				:showsearch.sync="show_search_user2"
				:itemInfo_.sync="search_value_user2">
			</chooseUserMulti>
		</view>
	</view>
</template>

<script>
	import {
		config
	} from '../../request/js/config.js'
	import chooseUserSingle from '@/components/xinsoft-search-list/chooseUserSingle.vue';
	import chooseUserMulti from '@/components/xinsoft-search-list/chooseUserMulti.vue'
	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,chooseUserSingle,chooseUserMulti
		},
		data() {
			return {
				config:config,
				task_level:[],
				task_type:[],
				imgsrc_list: [],
				imgsrc_list_local: [],
				showPicker: false,
				deepLength:1,
				taskInfo:{
					title:"",
					expireDate:'',
					detail:'',
					taskTypeName:'',
					taskType:'',
					taskLevelName:'',
					taskLevel:''
				},
				zrr:{},
				csr:[],
				id:'',
				targetList: [],
				show_search_user1:false,
				search_value_user1:"",
				show_search_user2:false,
				search_value_user2:"",
			}
		},
		onLoad(option) {
			var _this = this;
			this.id = option.id||'';
			
			//如果是编辑，就根据接口获取数据，
			if(option.id){
				this.$http.request({
					url: '/apis/taskMain/detail',
					params: {
					   id:option.id
					},
				}).then(res => {
					if (res.data.code == 0) {
						_this.taskInfo = res.data.taskMain;
						res.data.ccIdList.forEach((vals,index)=>{
							var json = {
								userId:vals.id,
								name:vals.name
							}
							this.targetList.push(json);
						});
						var heldPerson = res.data.heldPerson
						this.zrr = {
							userId:heldPerson.employeeId,
							name:heldPerson.userName
						}
						for(var i=0;i<res.data.initFileList.length;i++){
							this.imgsrc_list.push(res.data.initFileList[i].filePath);
							this.imgsrc_list_local.push(config.imgURL+res.data.initFileList[i].filePath);
						}
						uni.setStorage({
						    key: 'taskInfo',
						    data: {
								info:this.taskInfo,
								imgsrc_list:this.imgsrc_list,
								imgsrc_list_local:this.imgsrc_list_local,
								targetList:this.targetList,
								zrr:this.zrr,
							},
						    success: function () {

						    }
						});
					}
				}).catch(err => {
					uni.showToast({
						title: '获取信息失败',
						icon: 'none',
						duration: 2000
					});
				});
			}else{
				uni.getStorage({
					key: 'taskInfo',
					success: function (res) {
						_this.taskInfo = res.data.info||{};
						_this.imgsrc_list = res.data.imgsrc_list||[];
						_this.imgsrc_list_local = res.data.imgsrc_list_local||[];
						_this.zrr = res.data.zrr||{};
						_this.targetList = res.data.targetList||[];
					}
				});
			}
			//初始化获取 任务等级数据字典。
			this.$http.request({
			  url: '/apis/dict/getDictsByType',
			  params: {
			    type: 'task_level'
			  },
			}).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.task_level.push(myVal);
					}
				}
			}).catch(err=>{
				console.log(err);
			});
			//初始化获取 任务类型数据字典。
			this.$http.request({
			  url: '/apis/dict/getDictsByType',
			  params: {
			    type: 'task_type'
			  },
			}).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.task_type.push(myVal);
					}
				}
			}).catch(err=>{
				console.log(err);
			});
		},
		watch:{
			search_value_user1(newv){
				let obj = {userId: newv.userId, name: newv.NAME};
				this.zrr = obj;
				var taskInfo =  uni.getStorageSync('taskInfo');
				if(!taskInfo){
					taskInfo = {}
				}
				taskInfo.zrr = this.zrr
				uni.setStorage({
					key: 'taskInfo',
					data: taskInfo,
					success: function () {
					}
				});
	
			},
			search_value_user2(newv){
				var detail = [];
				newv.forEach(item=>{
					let obj = {userId: item.userId, name: item.NAME};
					detail.push(obj);
				})
				if(newv.length>0){
					var taskInfo =  uni.getStorageSync('taskInfo');
					if(!taskInfo){
						taskInfo = {}
					}
					this.targetList=detail
					taskInfo.targetList = this.targetList
					uni.setStorage({
					    key: 'taskInfo',
					    data: taskInfo,
					    success: function () {
					    }
					});
					}
				}
		},
		methods: {
			selectPeople1(){
				this.show_search_user1=true;
				// uni.navigateTo({
				//     url: "selectPeople?flag="+flag
				// });
			},
			selectPeople2(data){
				this.show_search_user2=true;
			},
			formatCsrName(data){
				var returnName = '';
				for(var i=0;i<data.length;i++){
					if(i == 3){
						returnName += data[i].name+'等等';
						 break;
					}else{
						returnName += data[i].name+','
					}
				}
				returnName = returnName.substring(0,returnName.length-1);
				return returnName;
			},
			pickerConfirm(e){
				//任务类型
				this.taskInfo.taskTypeName = e.label;
				this.taskInfo.taskType = e.value[0];  
				this.dataChange();
			},
			pickerConfirmLevel(e){
				//任务等级
				this.taskInfo.taskLevelName = e.label;
				this.taskInfo.taskLevel = e.value[0];  
			},
			showSinglePicker(index) {
				if(index == 1){
					//任务类型
					this.pickerValueArray = this.task_type;
					this.pickerValueDefault = [0]
					this.$refs.mpvuePicker.show()
				}else{
					//任务等级
					this.pickerValueArray = this.task_level;
					this.pickerValueDefault = [0]
					this.$refs.mpvuePickerLevel.show()
				}
			},
			onShowDatePicker() { //显示
				this.showPicker = true;
			},
			onSelected(e) { //选择
				this.showPicker = false;
				var _this = this;
				if (e) {
					this.taskInfo.expireDate = e.value+':00';
				}
				var taskInfo =  uni.getStorageSync('taskInfo');
				if(!taskInfo){
					taskInfo = {}
				}
				taskInfo.info = this.taskInfo;
				uni.setStorage({
				    key: 'taskInfo',
				    data: taskInfo,
				    success: function () {

				    }
				});
			},
			dataChange:function(){
				var taskInfo =  uni.getStorageSync('taskInfo');
				if(!taskInfo){
					taskInfo = {}
				}
				taskInfo.info = this.taskInfo;
				uni.setStorage({
				    key: 'taskInfo',
				    data: taskInfo,
				    success: function () {

				    }
				});
			},
			//上传
			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 taskInfo =  uni.getStorageSync('taskInfo');
								if(!taskInfo){
									taskInfo = {}
								}
								taskInfo.imgsrc_list = _this.imgsrc_list;;
								taskInfo.imgsrc_list_local = _this.imgsrc_list_local;
								uni.setStorage({
								    key: 'taskInfo',
								    data: taskInfo,
								    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 taskInfo =  uni.getStorageSync('taskInfo');
								if(!taskInfo){
									taskInfo = {}
								}
								taskInfo.imgsrc_list = _this.imgsrc_list;;
								taskInfo.imgsrc_list_local = _this.imgsrc_list_local;
								uni.setStorage({
								    key: 'taskInfo',
								    data: taskInfo,
								    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 taskInfo =  uni.getStorageSync('taskInfo');
				if(!taskInfo){
					taskInfo = {}
				}
				taskInfo.imgsrc_list = this.imgsrc_list;;
				taskInfo.imgsrc_list_local = this.imgsrc_list_local;
				uni.setStorage({
				    key: 'taskInfo',
				    data: taskInfo,
				    success: function () {

				    }
				});
			},
			//点击暂存和确认提交 需要进行的操作。
			goAddRepair(flag){
				if(flag == 'tj'){
					//提交进行的操作
					var url = '/apis/taskMain/save'
				}else if(flag == 'zc'){
					//暂存进行的操作。
					var url = '/apis/taskMain/saveTS'
				}
				var _this = this;
				//在这里是抄送人数据。
				var carbonCopyRecipients = []
				if(this.targetList.length>0){
					this.targetList.forEach((vals,index)=>{
						carbonCopyRecipients.push(vals.userId);
					});
				}
				if(!(this.taskInfo && this.taskInfo.title)){
					uni.showToast({
						    title: '请填写任务主题',
						    duration: 2000,
							icon:"none"
						});
					return false;
				}
				if(!(this.taskInfo && this.taskInfo.taskType)){
					uni.showToast({
						    title: '请选择任务类型',
						    duration: 2000,
							icon:"none"
						});
					return false;
				}
				if(!(this.taskInfo && this.taskInfo.taskLevel)){
					uni.showToast({
						    title: '请选择任务等级',
						    duration: 2000,
							icon:"none"
						});
					return false;
				}
				if(!(this.taskInfo && this.taskInfo.expireDate)){
					uni.showToast({
						    title: '请选择要求完成时间',
						    duration: 2000,
							icon:"none"
						});
					return false;
				}
				if(!(this.zrr && this.zrr.userId)){
					uni.showToast({
						    title: '请选择责任人',
						    duration: 2000,
							icon:"none"
						});
					return false;
				}
				//调取接口进行保存。
				this.$http.request({
				  url: url,
				  params:{
					  title:this.taskInfo.title,
					  taskType:this.taskInfo.taskType,
					  taskLevel:this.taskInfo.taskLevel,
					  expireDate:this.taskInfo.expireDate,
					  detail:this.taskInfo.detail,
					  ccList:carbonCopyRecipients, // 逗号隔开。
					  heldPerson:this.zrr.userId,
					  taglocationappearanceImage:this.imgsrc_list,
					  id:this.taskInfo.id||''
				  }
				}).then(res=>{
					if(res.data.code == 0){
						uni.removeStorageSync('taskInfo');
						uni.showToast({
							title: '操作成功',
							duration: 	1000,
							icon:"none"
						});
						setTimeout( function(){
							uni.navigateTo({
								url: "task"
							});
						},1000)
					}
				}).catch(err=>{
					uni.showToast({
						title: '操作失败',
						duration: 	2000,
						icon:"none"
					});
				});
			}
		},
		onBackPress(options) { //取消默认的返回事件.用来返回上一页时重新加载页面，删除本地缓存的巡检操作
			uni.removeStorageSync('taskInfo');
			uni.navigateTo({
				url: "task"
			});
			return true;

		},
	}
</script>

