<!-- 未发布任务修改 -->
<template>
	<div class='unpublishedTask'>
		<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.id" placeholder="请选择组长">
								<el-option
												v-for="item in leaderOptions"
												:key="item.id"
												:label="item.username"
												:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="发布者">
							<span>{{taskForm.publisher.username}}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="任务开始时间" prop="stateTime">
							<el-date-picker value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :picker-options="startOption" 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">
								</el-option>
							</el-select>
						</el-form-item>

					</el-col>
					<el-col :span="8">
						<el-form-item label="预计完成时间" prop="completeTime">
							<el-date-picker value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :picker-options="completeOption" 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="taskForm.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')">发布</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: "unpublishedTask",
//import引入的组件需要注入到对象中才能使用
		components: { EditorBar },
		data () {
//这里存放数据
			return {
				taskForm: {
					title: '',
					publisher: '',
					stateTime: '',
					completeTime: '',
					workload: '',
					executor: '',
					crewList: [],
					attachment: [],
					pworkload: 1,
					status: '',
					workCoefficient: 0,
					workloadCount: 1,
					content: ''
				},
				announcer: '',
				startOption: {
					// disabledDate: time => {
					// 	if (this.taskForm.completeTime) {
					// 		return (
					// 			time.getTime() > new Date(this.taskForm.completeTime).getTime()
					// 		)
					// 	} else {
					// 		// 不能大于当前日期
					// 		return time.getTime() > Date.now()
					// 	}
					// }
				},
				completeOption: {
					// disabledDate: time => {
					// 	if (this.taskForm.startTime) {
					// 		return (
					// 			time.getTime() > Date.now() ||
					// 			time.getTime() < new Date(this.taskForm.startTime).getTime() + 8.64e7 // 加- 8.64e7则表示包当天
					// 		)
					// 	} else {
					// 		return time.getTime() < Date.now()
					// 	}
					// }
				},
				rules: {
					title: [
						{ required: true, message: '请输入任务名称', trigger: 'blur' },
					],
					stateTime: [
						{ type: 'string', required: true, message: '请选择任务开始时间', trigger: 'change' }
					],
					completeTime: [
						{ 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: [
					{label: '李四', value: '李四'},{label: '王五', value: '王五'},{label: '赵六', value: '赵六'},
				],
				memberOptions: [
					{label: '李四', value: '李四'},{label: '王五', value: '王五'},{label: '赵六', value: '赵六'},
					{label: '周七', value: '周七'},{label: '刘八', value: '刘八'},{label: '陈九', value: '陈九'},
				],
				content: '',
				isClear: false,
				fileList: [], // 文件列表
				attachmentsArr: [], // 存储多个附件对象
				userLoginData: '',
				detailData:'',
			};
		},
//监听属性 类似于data概念
		computed: {},
//监控data中的数据变化
		watch: {},
//方法集合
		methods: {
			getUserById(val) {
				this.$axios.getUserById(val).then((res) => {
					console.log(res)
					if (res.request.status === 200) {
						this.leaderOptions = res.data;
						this.memberOptions = res.data;
					}
				})
			},
			getDetailsTask(val) {
				this.$axios.getWorkDetails(val).then((res) => {
					console.log(res)
					if (res.request.status === 200) {
						this.taskForm = res.data;
						this.fileList = res.data.attachment;
						res.data.attachment.forEach((v,i) => {
							let obj = {
								id: v.id,
								name: v.name
							}
							this.attachmentsArr.push(obj)
						})
						let arr = [];
						res.data.crewList.forEach((v,i)=> {
							arr.push(v.id);
						})
						this.taskForm.crewList = arr;
					}
				})
			},
			change(val) {
				console.log(val)
			},
			saveForm(formName) {
				alert(this.content);
				this.$refs[formName].validate((valid) => {
					if (valid) {
						alert('submit!');
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			submitForm(formName) {
				// alert(this.content);
				this.$refs[formName].validate((valid) => {
					if (valid) {
						console.log(this.taskForm);
						let data = JSON.parse(JSON.stringify(this.taskForm));
						data.status = 'ongoing';
						data.publisher = this.taskForm.publisher.id;
						data.executor = this.taskForm.executor.id;
						let arr = [];
						this.attachmentsArr.forEach((v, i) => {
							arr.push(v.id);
						})
						console.log(arr)
						data.attachment = arr;
						let obj = {
							"remarks": "",
							"userId": this.userLoginData.id,
							'work': data
						}
						console.log(obj);
						this.$axios.putTaskUnpushToGoing(obj).then((res) => {
							console.log(res);
							if (res.request.status === 200) {
								if (res.data.id !== undefined) {
									this.$message({
										message: '发布任务成功!',
										type: 'success'
									});
									this.$refs[formName].resetFields();
									this.$router.push({name: 'viewTask'});
								}
							}
						})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
			submitUpload() {
				// this.$refs.uploaad.submit();
			},
			handleExceed (files, fileList) { //  最多上传5个附件，多出时提示
				this.$message.warning(`最多只能上传 5 个文件`);
			},
			handleRemove (file, fileList) { // 删除附件
				// for (let a = 0; a < this.attachmentsArr; a++) {
				// 	if (file.name === this.attachmentsArr[a].name) {
				// 		this.attachmentsArr.splice(a, 1);
				// 	}
				// }
				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);
			},
			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}`;
						// this.attachmentsArr.push(Obj); // 把多个附件添加到一个数组中，留到把附件添加到所属工作中时使用
						// console.log(this.attachmentsArr);
						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)
							}
						})
						console.log(this.attachmentsArr);
					}
				})
			},
		},
//生命周期 - 创建完成（可以访问当前this实例）
		created () {

		},
//生命周期 - 挂载完成（可以访问DOM元素）
		mounted () {
			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.detailData = JSON.parse(this.$Base64.decode(localStorage.getItem('unpublished')));
			// this.announcer = this.userLoginData.username;
			// this.taskForm.publisher = this.userLoginData.id;
			let that = this;
			setTimeout(function () {
				that.getUserById(that.userLoginData.id);
				that.getDetailsTask(that.detailData.workId);
			}, 200)
		},
		beforeCreate () {
		}, //生命周期 - 创建之前
		beforeMount () {
		}, //生命周期 - 挂载之前
		beforeUpdate () {
		}, //生命周期 - 更新之前
		updated () {
		}, //生命周期 - 更新之后
		beforeDestroy () {
		}, //生命周期 - 销毁之前
		destroyed () {
		}, //生命周期 - 销毁完成
		activated () {
		}, //如果页面有keep-alive缓存功能，这个函数会触发
	}
</script>
<style scoped>
	.unpublishedTask{
		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>
