<template>
		<view class="add">
			<!-- 设备信息 -->
			<view class="main">
				<u--form labelPosition="left" labelAlign="center" :model="task" ref="form1" >
					<u-form-item label="任务名称" prop="task.name" labelWidth="auto" borderBottom ref="item1" >
					<u--input v-model="task.name" border="none" placeholder="请输入任务名称"></u--input>
					</u-form-item>
					<u-form-item
							label="盘点维度"
							prop="task.dimension"
							borderBottom
							@click="showDimension = true; "
							labelWidth="auto"
							ref="item1"
					>
						<u--input
								v-model="task.dimension"
								disabled
								disabledColor="#ffffff"
								placeholder="请选择盘点维度"
								border="none"
						></u--input>
						<u-icon
								slot="right"
								name="arrow-right"
						></u-icon>
					</u-form-item>
					
					<view v-show="task.dimensionId == 0">
						
						<u-form-item
								label="盘点部门"
								prop="task.dept"
								borderBottom
								@click="deptMethod"
								labelWidth="auto"
								ref="item1"
						>
							<u--input
									v-model="task.dept"
									disabled
									disabledColor="#ffffff"
									placeholder="请选择盘点部门"
									border="none"
							></u--input>
							<u-icon
									slot="right"
									name="arrow-right"
							></u-icon>
						</u-form-item>
					</view>
					<view v-show="task.dimensionId == 2">
						<u-form-item
								label="盘点人员"
								prop="task.user"
								borderBottom
								@click="userMethod"
								labelWidth="auto"
								ref="item1"
						>
							<u--input
									v-model="task.user"
									disabled
									disabledColor="#ffffff"
									placeholder="请选择盘点人员"
									border="none"
							></u--input>
							<u-icon
									slot="right"
									name="arrow-right"
							></u-icon>
						</u-form-item>
					</view>
					<u-form-item label="截止日期" prop="task.lastTime" 
					labelWidth="auto" @click="datePickShow = true; " borderBottom ref="item1" >
						<u--input
								v-model="task.lastTime"
								disabled
								disabledColor="#ffffff"
								placeholder="请选择截止日期"
								border="none"
						></u--input>
						<u-icon
								slot="right"
								name="arrow-right"
						></u-icon>
						<u-datetime-picker
						        :show="datePickShow"
						        v-model="pickerTime"
						        mode="date"
								:closeOnClickOverlay="true"
								@close="datePickShow = false"
								@cancel="datePickShow = false"
								@confirm="dateConfirm"
						></u-datetime-picker>
					</u-form-item>
						<u-form-item label="任务照片" prop="task.photo" labelWidth="auto" borderBottom ref="item1" >
							<u-upload
								:fileList="fileList1"
								@afterRead="afterRead"
								@delete="deletePic"
								name="1"
								multiple
								:maxCount="1"
								:previewFullImage="true"
							></u-upload>
						</u-form-item>
						<u-form-item label="任务说明" prop="task.remark" labelWidth="auto" borderBottom ref="item1" >
							<u--textarea v-model="task.remark" placeholder="请输入任务说明" ></u--textarea>
						</u-form-item>
						
						<u-form-item
								label="盘点管理员"
								prop="task.pdManage"
								borderBottom
								@click="showPdManage = true; "
								labelWidth="auto"
								ref="item1"
						>
							<u--input
									v-model="task.pdManage"
									disabled
									disabledColor="#ffffff"
									placeholder="请选择盘点管理员"
									border="none"
							></u--input>
							<u-icon
									slot="right"
									name="arrow-right"
							></u-icon>
						</u-form-item>
						<!-- <u-form-item label="盘点管理员" labelWidth="auto" borderBottom ref="item1" >
							{{pdManage}}
						</u-form-item> -->
				</u--form>
				<u-action-sheet
						:show="showPdManage"
						:actions="pdManageActions"
						title="请选择盘点管理员"
						@close="showPdManage = false"
						@select="pdManageSelect"
				>
				</u-action-sheet>
				<u-action-sheet
						:show="showDimension"
						:actions="dimensionActions"
						title="请选择盘点维度"
						@close="showDimension = false"
						@select="dimensionSelect"
				>
				</u-action-sheet>
				<qianziyu-select
					:show="showDept" 
					type="checkbox"
					popupTitle="选择部门" 
					name="name" 
					:dataLists="deptActions" 
					placeholder="输入名称搜索"
					@cancel="showDept=false" 
					@search="" 
					@submit="deptSelect"
				>
				</qianziyu-select>
				<qianziyu-select
					:show="showUser" 
					type="checkbox"
					popupTitle="选择人员" 
					name="name" 
					:dataLists="userActions" 
					placeholder="输入名称搜索"
					@cancel="showUser=false" 
					@search="" 
					@submit="userSelect"
				>
				</qianziyu-select>
			</view>
			
			<view class="submit" >
				<u-button type="primary" @click="submit" text="提 交"></u-button>
			</view>
			<view class="submit" >
				<u-button type="primary" text="结 束" @click="toEnd"></u-button>
			</view>
			
			
			
			<view >
				<u-modal @confirm="end" @cancel="endClose" showCancelButton="true" :show="endShow">确定结束[{{task.name}}]任务的发布？</u-modal>
			</view>
		</view>
</template>

<script>
	// import qianziyu-select from "@/commponents/qianziyu-select/qianziyu-select.vue"
	export default { 
		
		data() {
			return {
				show: true,
				task: {
					publishId: null,
					name:'',
					dimension:'',
					dimensionId: null,
					dept:'',
					deptId:null,
					office:'',
					officeId: null,
					user:'',
					userPeopleId: null,
					lastTime: '',
					remark:'',
					picUrl:'',
					deptIds:[],
					userPeopleIds:[],
					pdManage: '',
					pdManageId: null
				},
				pickerTime: Number(new Date()),
				datePickShow: false,
				showDimension: false,
				dimensionActions: [
					{
						name: '部门',
						value: 0
					},
					// {
					// 	name: '科室',
					// 	value: 1
					// },
					{
						name: '人员',
						value: 2
					}
				],
				showDept: false,
				deptActions: [
				],
				showOffice: false,
				officeActions: [
				],
				showUser: false,
				userActions: [
				],
				showPdManage: false,
				pdManageActions: [
				],
				fileList1:[],
				endShow: false
			}
		},
		
		onLoad: function(options){
			let data = JSON.parse(options.publish);
			this.task.publishId = data.id;
			this.task.name = data.name;
			this.task.lastTime = data.enableTime;
			
			this.getPdManage();
			this.getDept();
			this.getUsers();
		},
		
		created() {
		},
		filters: {
		},
		
		methods: {
			// 1.1扫码
			scan() {
				var that = this;
				uni.scanCode({
					success: function(res) {
						console.log(res.result);
						that.getdeviceinfo(res.result)
					}
				})
			},
			async getdeviceinfo(id) {
				const { data:res } = await this.$http('/getdeviceinfo', {
					id: id
				});
				if(res.code) return
				console.log(res.data)
				this.show=true;
			},
			async getDept() {
				const { data:res } = await this.$http('/deptListPublish', {publishId: this.task.publishId});
				if(res.code) return
				this.deptActions = [];
				for (var i = 0; i < res.data.length; i++) {
					this.deptActions.push({
						name: res.data[i].deptName,
						value: res.data[i].id
					})
				}
			},
			async getUsers() {
				const { data:res } = await this.$http('/peopleListPublish', {publishId: this.task.publishId});
				if(res.code) return
				this.userActions = [];
				for (var i = 0; i < res.data.length; i++) {
					this.userActions.push({
						// name: res.data[i].deptName+" - "+res.data[i].ksName+" - "+res.data[i].nickName,
						name: res.data[i].deptName+" - "+res.data[i].nickName,
						value: res.data[i].id
					})
				}
			},
			async getPdManage() {
				const { data:res } = await this.$http('/getPdManage', {});
				if(res.code) return
				this.pdManageActions = [];
				for (var i = 0; i < res.data.length; i++) {
					this.pdManageActions.push({
						name: res.data[i].nickName,
						value: res.data[i].id
					})
				}
			},
			reset(){
				this.task.name = '';
				this.task.dimension='';
				this.task.dimensionId=null;
				this.task.remark='';
				this.task.picUrl='';
				this.fileList1=[];
				this.resetSecondSelect();
			},
			resetSecondSelect(){
				this.task.dept='';
				this.task.deptId=null;
				this.task.office='';
				this.task.officeId= null;
				this.task.user='';
				this.task.userPeopleId= null;
				this.task.deptIds = [];
				this.task.userPeopleIds = [];
			},
			dimensionSelect(e) {
				this.task.dimension = e.name
				this.task.dimensionId = e.value
				this.$refs.form1.validateField('task.dimension')
				this.resetSecondSelect();
			},
			deptMethod(){
				this.showDept = true;
			},
			officeMethod(){
				this.showOffice = true;
			},
			userMethod(){
				this.showUser = true;
			},
			deptSelect(e) {
				// this.task.dept = e.name
				// this.task.deptId = e.value
				// this.$refs.form1.validateField('task.dept')
				var nameArr = [];var valueArr = [];
				for (var i = 0; i < e.length; i++) {
					nameArr.push(e[i].name);
					valueArr.push(e[i].value);
				}
				this.task.dept = nameArr.join(",")
				this.task.deptIds = valueArr;
				this.showDept = false;
			},
			userSelect(e) {
				// this.task.user = e.name
				// this.task.userPeopleId = e.value
				// this.$refs.form1.validateField('task.user')
				var nameArr = [];var valueArr = [];
				for (var i = 0; i < e.length; i++) {
					nameArr.push(e[i].name);
					valueArr.push(e[i].value);
				}
				this.task.user = nameArr.join(",")
				this.task.userPeopleIds = valueArr;
				this.showUser = false;
			},
			pdManageSelect(e){
				this.task.pdManage = e.name
				this.task.pdManageId = e.value
				this.$refs.form1.validateField('task.pdManage')
			},
			submit(){
				let flag = true;
				if(this.task.dimensionId==null || this.task.name==null || this.task.name=='' ){
					flag = false;
				}
				if(this.task.dimensionId == 0 && !this.task.deptIds){
					flag = false;
				}
				if(this.task.dimensionId == 2 && !this.task.userPeopleIds){
					flag = false;
				}
				// if(this.fileList1.length == 0){
				// 	flag = false;
				// }
				if(!flag) return uni.showToast({
					title: '请补充任务内容',
					icon: 'error'
				})
				
				if(this.fileList1.length > 0){
					console.log(this.fileList1)
					let url = [];
					for (var i = 0; i < this.fileList1.length; i++) {
						url.push(this.fileList1[i].url)
					}
					this.task.picUrl = url.join(",");
				}
				this.addTask();
				
			},
			async addTask(){
				const { data:res } = await this.$http('/addTask', this.task);
				if(res.code == 0){
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});
					this.reset();
				}
				
			},
			// 删除图片
			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)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					const token = uni.getStorageSync("token");
					let a = uni.uploadFile({
						url: this.BASE_URL+'/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							"Authorization":"Bearer " + token,
						},
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								let data = JSON.parse(res.data)
								console.log(data)
								resolve(data.fileName)
							}, 1000)
						}
					});
				})
			},
			dateConfirm(e){
				const timeFormat = uni.$u.timeFormat
				console.log(timeFormat(e.value, 'yyyy-mm-dd'))
				this.datePickShow = false;
				this.task.lastTime = timeFormat(e.value, 'yyyy-mm-dd');
			},
			endClose() {
			  this.endShow = false
			},
			toEnd(){
				this.endShow = true
			},
			async end(){
				const { data:res } = await this.$http('/endAdd', {publishId: this.task.publishId});
				if(res.code) return
				uni.navigateBack({ delta: 1 });
				// uni.redirectTo({
				//    url:'add_list'
				// })
				uni.showToast({
					title: "执行成功",
					icon: 'success'
				})
				this.endShow = false
			}
		}
	}
</script>

<style lang="scss">
	
	.submit{
		margin: 1vh 2.667vw;
	}
	.add {
		background: #f6f6f6;
		padding: 2.667vw;
		height: 100vh;
		.main {
			background: #ffffff;
			margin-bottom: 2.667vw;
			padding: 2vw;
			border-radius: 8px;
			
			.u-form-item__body__right{
				padding-left: 20vw;
			}
			.u-button{
				border: none !important;
				padding: 0 !important;
				justify-content: flex-start;
			}
		}
	}
	.u-popup{
		.title{
			margin: 1vh 0 0 0;
			text-align: center;	
		}
		.u-button{
			justify-content: center !important;
		}
		.u-checkbox{
			margin-bottom: 16px;
		}
	}
</style>