<!-- 新增任务 -->
<template>
	<div class='addTask'>
		<div>
			<el-form :model="taskForm" :rules="rules" ref="taskForm" label-width="120px" class="demo-ruleForm">
				<el-row :gutter="10">
					<el-col :span="8">
						<el-form-item label="任务名称" prop="title">
							<el-input v-model="taskForm.title"></el-input>
						</el-form-item>
						<!--<el-form-item label="小组名称" prop="taskGroupName">-->
							<!--<el-input v-model="taskForm.taskGroupName"></el-input>-->
						<!--</el-form-item>-->
						<el-form-item label="组长" prop="executor">
							<el-select style="width: 100%;" v-model="taskForm.executor" placeholder="请选择组长">
								<el-option
												v-for="item in leaderOptions"
												:key="item.id"
												:label="item.username"
												:value="item.id">
									<span style="display: inline-block;width: 70px;">{{item.username}}</span>
									<span>({{personStatusName(item.status)}})</span>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="发布者">
							<span>{{announcer}}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="任务开始时间" prop="stateTime">
							<el-date-picker :editable="false"  value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期" v-model="taskForm.stateTime" style="width: 100%;"></el-date-picker>
						</el-form-item>
						<el-form-item label="组员">
							<!--prop="crewList"-->
							<el-select style="width: 100%;" v-model="taskForm.crewList" multiple placeholder="请选择组员">
								<el-option
												v-for="item in memberOptions"
												:key="item.id"
												:label="item.username"
												:value="item.id">
									<span style="display: inline-block;width: 70px;">{{item.username}}</span>
									<span>({{personStatusName(item.status)}})</span>
								</el-option>
							</el-select>
						</el-form-item>

					</el-col>
					<el-col :span="8">
						<el-form-item label="预计完成时间" prop="completeTime">
							<el-date-picker :editable="false" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期" v-model="taskForm.completeTime" style="width: 100%;"></el-date-picker>
						</el-form-item>
						<el-form-item label="任务量(天)" prop="workload">
							<el-input onkeyup="this.value=this.value.replace(/[^\d.]/g,'')" v-model="taskForm.workload"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<div style="padding: 10px 35px;">
					<div style="padding: 10px 0px;font-size: 14px;">任务内容</div>
					<editor-bar v-model="content" :isClear="isClear" @change="change"></editor-bar>
				</div>
				<div class="upload-container">
					<div class="upload-file" style="margin-left: 35px;">
						<el-upload
										class="upload-demo"
										ref="upload"
										action="https://jsonplaceholder.typicode.com/posts/"
										:http-request="handleChange"
										:on-remove="handleRemove"
										:on-exceed="handleExceed"
										:before-upload="beforeAvatarUpload"
										:file-list="fileList"
										:auto-load="false"
										:limit="5">
							<el-button size="small" @click="submitUpload">添加附件</el-button>
							<!--<button>添加附件</button>-->
							<div slot="tip">最多只能上传5个文件，否则请上传压缩包！</div>
						</el-upload>
					</div>
				</div>
			</el-form>
		</div>
		<div style="text-align: center;margin-top: 30px;">
			<el-button type="primary" @click="submitForm('taskForm','unpublished')">保存</el-button>
			<el-button style="margin-left: 50px;margin-right: 40px;" type="primary" @click="submitForm('taskForm', 'ongoing')">发布</el-button>
			<!--<el-button @click="resetForm('taskForm')">重置</el-button>-->
		</div>
	</div>
</template>

<script>
	//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
	//例如：import 《组件名称》 from '《组件路径》';
	import EditorBar from '../components/taskEditer'
	export default {
		name: "AddTask",
//import引入的组件需要注入到对象中才能使用
		components: { EditorBar },
		data () {
			let stateTimeVal = (rule, value, callback) => {
				if (!value) {
					return callback(new Error('任务开始时间不能为空'));
				}
				if (this.taskForm.completeTime !== '') {
					if (new Date(value).getTime() > new Date(this.taskForm.completeTime).getTime()) {
						callback(new Error('任务开始时间不能超过预计完成时间'));
					} else {
						callback();
					}
				} else {
					callback();
				}
			};
			let completeVal = (rule, value, callback) => {
				if (!value) {
					return callback(new Error('预计完成时间为空'));
				}
				if (this.taskForm.stateTime !== '') {
					if (new Date(value).getTime() < new Date(this.taskForm.stateTime).getTime()) {
						callback(new Error('预计完成时间不能小于任务开始时间'));
					} else {
						callback();
					}
				} else {
					callback();
				}
			};
//这里存放数据
			return {
				taskForm: {
					title: '',
					publisher: '',
					stateTime: '',
					completeTime: '',
					workload: '',
					executor: '',
					crewList: [],
					attachment: [],
					pworkload: 1,
					status: '',
					workCoefficient: 0,
					workloadCount: 1
				},
				announcer: '',
				rules: {
					title: [
						{ required: true, message: '请输入任务名称', trigger: 'blur' },
					],
					stateTime: [
						{ required: true, validator: stateTimeVal, trigger: 'blur' },
						// { type: 'string', required: true, message: '请选择任务开始时间', trigger: 'change' }
					],
					completeTime: [
						{ required: true, validator: completeVal, trigger: 'blur' }
						// { type: 'string', required: true, message: '请选择预计完成时间', trigger: 'change' }
					],
					executor: [
						{ required: true, message: '请选择组长', trigger: 'change' }
					],
					crewList: [
						{ type: 'array', required: true, message: '请选择组员', trigger: 'change' },
					],
					workload: [
						{ required: true, message: '请输入任务量', trigger: 'blur' },
					]
				},
				leaderOptions: [],
				memberOptions: [],
				content: '',
				isClear: false,
				fileList: [], // 文件列表
				attachmentsArr: [], // 存储多个附件对象
				userLoginData: ''
			};
		},
//监听属性 类似于data概念
		computed: {
		},
//监控data中的数据变化
		watch: {},
//方法集合
		methods: {
			getUserById(val) {
				this.$axios.getUserById(val).then((res) => {
					console.log(res)
					if (res.request.status === 200) {
						if (res.data.length === 0 && (JSON.stringify(this.$store.getters.getSuperior.superior) !== '{}' && JSON.stringify(this.$store.getters.getSuperior.superior) !== undefined)) {
							let data = this.$store.getters.getSuperior.superior.crewList;
							if (data.findIndex(item => item.id === this.userLoginData.id) > -1) {
								this.leaderOptions = data;
								this.memberOptions = data;
							} else {
								data.push(JSON.parse(JSON.stringify(this.userLoginData)));
								console.log(data)
								// let data2 = Array.from(new Set(data));
								let data2 = []
								let obj = {};
								for (let i = 0; i < data.length; i++) {
									if (!obj[data[i].id]) {
										data2.push(data[i]);
										obj[data[i].id] = true;
									}
								}
								this.leaderOptions = data2;
								this.memberOptions = data2;
							}
						} else if (res.data.length > 0 && (JSON.stringify(this.$store.getters.getSuperior.superior) === '{}' || JSON.stringify(this.$store.getters.getSuperior.superior) === undefined)) {
							let data = res.data;
							if (data.findIndex(item => item.id === this.userLoginData.id) > -1) {
								this.leaderOptions = data;
								this.memberOptions = data;
							} else {
								data.push(JSON.parse(JSON.stringify(this.userLoginData)));
								// let data2 = Array.from(new Set(data));
								let data2 = []
								let obj = {};
								for (let i = 0; i < data.length; i++) {
									if (!obj[data[i].id]) {
										data2.push(data[i]);
										obj[data[i].id] = true;
									}
								}
								this.leaderOptions = data2;
								this.memberOptions = data2;
							}
						} else if (res.data.length > 0 && (JSON.stringify(this.$store.getters.getSuperior.superior) !== '{}' && JSON.stringify(this.$store.getters.getSuperior.superior) !== undefined)) {
							let arr1 = res.data;
							let arr2 = this.$store.getters.getSuperior.superior.crewList;
							arr1.push(...arr2);
							if (arr1.findIndex(item => item.id === this.userLoginData.id) > -1) {
								// let arr3 = Array.from(new Set(arr1));
								// let arr3 = [...new Set(arr1)];
								let arr3 = []
								let obj = {};
								for (let i = 0; i < arr1.length; i++) {
									if (!obj[arr1[i].id]) {
										arr3.push(arr1[i]);
										obj[arr1[i].id] = true;
									}
								}
								this.leaderOptions = arr3;
								this.memberOptions = arr3;
							} else {
								arr1.push(JSON.parse(JSON.stringify(this.userLoginData)));
								// let arr3 = Array.from(new Set(arr1));
								// let arr3 =  [...new Set(arr1)]
								let arr3 = []
								let obj = {};
								for (let i = 0; i < arr1.length; i++) {
									if (!obj[arr1[i].id]) {
										arr3.push(arr1[i]);
										obj[arr1[i].id] = true;
									}
								}
								this.leaderOptions = arr3;
								this.memberOptions = arr3;
							}
						}
					}
				})
			},
			change(val) {
				// console.log(val)
			},
			submitForm(formName, sta) {
				// alert(this.content);
				this.$refs[formName].validate((valid) => {
					if (valid) {
						// console.log(JSON.stringify(this.$store.getters.getSuperior.superior));
						if (JSON.stringify(this.$store.getters.getSuperior.superior) !== '{}' && JSON.stringify(this.$store.getters.getSuperior.superior) !== undefined) {
							if (new Date(this.taskForm.stateTime).getTime() < new Date(this.$store.getters.getSuperior.superior.stateTime).getTime()) {
								this.$message({
									message: `当前任务开始时间不能早于${this.$store.getters.getSuperior.superior.stateTime}`,
									type: 'warning'
								});
								return false;
							}
							if (new Date(this.taskForm.completeTime).getTime() > new Date(this.$store.getters.getSuperior.superior.completeTime).getTime()) {
								this.$message({
									message: `当前预计完成时间不能超过${this.$store.getters.getSuperior.superior.completeTime}`,
									type: 'warning'
								});
								return false;
							}
							this.$axios.putFindWorkload(this.$store.getters.getSuperior.superior.id).then((res) => {
								console.log(res)
								if (res.status === 200) {
									if (parseInt(this.taskForm.workload) > parseInt(res.data)) {
										this.$alert(`当前总任务量为${res.data}，请重新评估任务量`, '任务量提示', {
											confirmButtonText: '确定'});
										return false;
									} else {
										this.postTaskData(formName, sta);
									}
								}
							})
						} else {
							this.postTaskData(formName, sta);
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			postTaskData(formName, sta) {
				console.log(this.taskForm);
				let data = JSON.parse(JSON.stringify(this.taskForm));
				let arr = [];
				this.attachmentsArr.forEach((v, i) => {
					arr.push(v.id);
				})
				console.log(arr)
				if (new Date(data.stateTime).getTime() > new Date(data.completeTime).getTime()) {
					this.$message({
						message: '任务开始时间不能大于预计完成时间',
						type: 'warning'
					});
					return false;
				}
				data.workCoefficient = 0;
				data.content = this.content;
				data.pworkload = 1;
				data.attachment = arr;
				data.status = sta;
				data.endTime = '';
				data.workload = Number(data.workload);
				data.workloadCount = 1;
				if (JSON.stringify(this.$store.getters.getSuperior.superior) !== '{}' && JSON.stringify(this.$store.getters.getSuperior.superior) !== undefined) {
					data.superiorId = this.$store.getters.getSuperior.superior.id;
				}
				let obj = {
					"remarks": "",
					"userId": this.userLoginData.id,
					'work': data
				}
				this.$axios.postAddTask(obj).then((res) => {
					console.log(res)
					if (res.request.status === 200) {
						if (res.data.id !== undefined) {
							this.$store.commit('changeSuperior', {
								superior: {}
							})
							let tip;
							if(sta === 'going') {
								tip = '新增任务';
							} else {
								tip = '保存任务';
							}
							this.$message({
								message: tip + '成功!',
								type: 'success'
							});
							this.$refs[formName].resetFields();
							this.content = '';
							this.$router.push({name: 'viewTask'});
						}
					}
				})
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
			submitUpload() {
				// this.$refs.uploaad.submit();
			},
			handleExceed (files, fileList) { //  最多上传5个附件，多出时提示
				this.$message.warning(`最多只能上传 5 个文件`);
			},
			handleRemove (file, fileList) { // 删除附件
				let arr = JSON.parse(JSON.stringify(this.attachmentsArr));
				arr.splice(arr.findIndex(item => item.name === file.name), 1);
				this.attachmentsArr = arr;
				console.log(this.attachmentsArr);
				// for (let i = 0; i < arr; i++) {
					// if (file.name === this.attachmentsArr[a].name) {
					// 	console.log(22222)
					// 	this.attachmentsArr.splice(a, 1);
					// }
				// }
			},
			beforeAvatarUpload(file) { // 文件上传大小限制
				let isLt2M = file.size / 1024 / 1024 < 300;
				if (!isLt2M) {
					this.$message({
						message: '文件上传大小不能超过300M',
						type: 'warning'
					})
				}
				return isLt2M
			},
			handleChange (files) { // 文件上传
				let Obj = {
					"fileId": "",
					"name": "",
					"suffix": "",
					"time": "",
					"type": "",
					"uploader": ""
				}
				// console.log(files)
				let form = new FormData();
				form.append('file', files.file);
				this.$axios.postUpload(form).then(res => {
					console.log(res)
					if (res.status === 200) {
						Obj.fileId = res.data.id;
						this.$message({
							message: '附件上传成功!',
							type: 'success'
						});
						Obj.uploader = this.userLoginData.id;
						Obj.name = files.file.name;
						Obj.type = 'init';

						let index = files.file.name.indexOf('.');
						let s = files.file.name.substring(index + 1);
						Obj.suffix = s;

						let time = new Date();
						let y = time.getFullYear();
						let m = time.getMonth() + 1;
						m = m < 10?'0' + m:m;
						let d = time.getDate();
						d = d < 10?'0' + d:d;
						let h = time.getHours();
						h = h < 10?'0' + h:h;
						let mm = time.getMinutes();
						mm = mm < 10?'0' + mm:mm;
						let ss = time.getSeconds();
						ss = ss < 10?'0' + ss:ss;
						Obj.time = `${y}-${m}-${d} ${h}:${mm}:${ss}`;
						// let newObj = {
						// 	attachment: Obj
						// }
						console.log(Obj)
						this.$axios.postAttachmentOneByOne(Obj).then((res) => {
							console.log(res)
							if (res.status === 200) {
								let data = {
									id: res.data.id,
									name: Obj.name
								}
								this.attachmentsArr.push(data)
							}
						})
						// this.attachmentsArr.push(Obj); // 把多个附件添加到一个数组中，留到把附件添加到所属工作中时使用
						console.log(this.attachmentsArr);

					}
				})
			},
			personStatusName(val) {
				let name = '';
				if (val === '0') {
					name = '空闲';
				} else if (val === '1') {
					name = '正常';
				} else {
					name = '忙碌';
				}
				return name;
			}
		},
//生命周期 - 创建完成（可以访问当前this实例）
		created () {

		},
//生命周期 - 挂载完成（可以访问DOM元素）
		mounted () {
			this.taskForm.stateTime = this.$common.timeYMDHMSFilter(new Date());
			console.log(this.$store.getters.getLoginData.loginData)
			if (this.$store.getters.getLoginData.loginData !== undefined) {
				this.userLoginData = this.$store.getters.getLoginData.loginData;
			} else {
				this.userLoginData = JSON.parse(this.$Base64.decode(localStorage.getItem('login')));
			}
			this.announcer = this.userLoginData.username;
			this.taskForm.publisher = this.userLoginData.id;
			let that = this;
			setTimeout(function () {
				that.getUserById(that.userLoginData.id);
			}, 200)
		},
		beforeCreate () {
		}, //生命周期 - 创建之前
		beforeMount () {
		}, //生命周期 - 挂载之前
		beforeUpdate () {
		}, //生命周期 - 更新之前
		updated () {
		}, //生命周期 - 更新之后
		beforeDestroy () {
		}, //生命周期 - 销毁之前
		destroyed () {
			this.$store.commit('changeSuperior', {
				superior: {}
			})
		}, //生命周期 - 销毁完成
		activated () {
		}, //如果页面有keep-alive缓存功能，这个函数会触发
	}
</script>
<style scoped>
	.addTask{
		height: 99%;
		padding: 10px 30px;
		/*border: 1px solid #000;*/
	}

	/deep/ .text {
		width: 100%;
		height: 800px;
		background: #ffffff;
		color: #000;
		/*padding: 0.119792rem 0 0 0.234375rem;*/
		/*margin: 0.208333rem auto;*/
	}
</style>
