<template>
	<view class="content">
		<view id="header">
			<view :class="isFinish?'':'select'" @click="change('unfinish')">未完成</view>
			<view :class="!isFinish?'':'select'" @click="change('finish')">已完成</view>
		</view>
		<scroll-view scroll-y :style="{height:s_height+'px'}" @scrolltolower="getMore">
			<view class="item" v-for="item in tasks">
				<view class="image" @click="finish(item)">
					<image :src="item.endDate?'../../static/images/finish.png':'../../static/images/unfinish.png'"
						mode="widthFix"></image>
				</view>
				<view class="taskdetail" :style="{width:t_width+'px'}" @click="detail(item)">
					<text style="margin-right: 10px; ">{{item.name}}</text>
				</view>
				<view v-if="type!=='assigned'" class="image" @click="important(item)">
					<image mode="widthFix"
						:src="item.important?'../../static/images/zhongyao.png':'../../static/images/buzhongyao.png'">
					</image>
				</view>
			</view>
		</scroll-view>
		<view id="bottom">
			<button class="btnSuggest" type="primary" v-if="type==='today'" @click="()=>{leftPop=true}">建议</button>
			<button class="btnAdd" type='primary' v-if="type!=='assigned'" @click="()=>{addPop=true}">+</button>
		</view>
		<u-popup :show="leftPop" mode="left" :closeable="true" @open="leftOpen()" @close="leftClose"
			:closeOnClickOverlay="false">
			<view solt class="leftPop">
				<scroll-view scroll-y="true" :style="{height:s_height+'px'}" @scrolltolower="getSuggest()">
					<view v-for="item in personTasks">
						<u-cell :title="item.name">
							<u-icon slot="right-icon" name="plus" @click="addToday(item)"></u-icon>
						</u-cell>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<u-popup :show="addPop" mode="bottom" :closeOnClickOverlay="false">
			<view class="addPop">
				<u--input placeholder="请输入任务名称" v-model="taskName" style="margin-top: 50px;"></u--input>
				<view style="display: flex;">
					<u-button type="error" @click="()=>{addPop=false}">关闭</u-button>
					<u-button type="primary" @click="addTask">新增</u-button>
				</view>
			</view>
		</u-popup>
		<u-popup :show="personDetail" mode="bottom" @open="personOpen" @close="personClose" :closeable="true">
			<view class="detail">
				<scroll-view scroll-y="true" :style="{height:s_height+'px'}">
					<uni-group title="任务名称">
						<u-row customStyle="height:100rpx">
							<u-col span="1">
								<view class="image" @click="finish(currTask)">
									<image
										:src="currTask.endDate?'../../static/images/finish.png':'../../static/images/unfinish.png'"
										mode="widthFix"></image>
								</view>
							</u-col>
							<u-col span="9">
								<u--input @change="saveTask" border="surround" style="margin-right: 10px; "
									v-model="currTask.name"></u--input>

							</u-col>
							<u-col span="1">
								<view class="image" @click="important(currTask)">
									<image mode="widthFix"
										:src="currTask.important?'../../static/images/zhongyao.png':'../../static/images/buzhongyao.png'">
									</image>
								</view>
							</u-col>
							<u-col span="1">
								<u-icon size="26px" name="trash" color="red" @click="deleteTask"></u-icon>
							</u-col>
						</u-row>
						<u-row customStyle="height:70rpx">
							<u-col span="1">
								<view class="image">
									<u-icon name="heart-fill" size="26px" :color="currTask.todayId?'red':'blue'">
									</u-icon>
								</view>
							</u-col>
							<u-col span="10">
								<u-text margin="0px 0px 0px 20px"
									:text="currTask.todayId==null?'添加到“今日任务”':'已添加到“今日任务”'"
									:color="currTask.todayId?'red':'blue'" @click="addToday(currTask)"></u-text>
							</u-col>
							<u-col span="1">
								<u-icon v-if="currTask.todayId" size="26px" name="trash" color="red"
									@click="deleteToday"></u-icon>
							</u-col>
						</u-row>
					</uni-group>
					<uni-group title="任务步骤">
						<view v-for="step in taskSteps">
							<u-row customStyle="border-bottom:1rpx solid lightgrey;height:80rpx">
								<u-col span="1">
									<image style="width: 26px;"
										:src="step.endTime?'../../static/images/finish.png':'../../static/images/unfinish.png'"
										mode="widthFix" @click="finishStep(step)"></image>
								</u-col>
								<u-col span="10">
									<u-text :decoration="step.endTime?'line-through':'none'" :text="step.name">
									</u-text>
								</u-col>
								<u-col span="1" align="center" textAlign="right">
									<u-icon name="trash" color="red" size="26px" @click="deleteStep(step)"></u-icon>
								</u-col>
							</u-row>
						</view>
						<u-input placeholder="请输入步骤名称" border="bottom" v-model="stepName">
							<template slot="suffix">
								<u-icon name="plus" color="blue" size="26px" @click="addStep"></u-icon>
							</template>
						</u-input>

					</uni-group>
					<uni-group title="任务详情">
						<u-textarea placeholder="请输入任务详情" v-model="currTask.content" @input="saveTask"></u-textarea>
					</uni-group>
					<uni-group title="日期安排">
						<u-input placeholder="请选择计划日期" v-model="taskDate" disabled>
							<template slot="suffix">
								<u-icon name="calendar" size="26px" color="blue" @click="()=>{calendar=true}"></u-icon>
							</template>
						</u-input>
						<u-calendar :show="calendar" mode="multiple" maxCount="2" @confirm="dateConfirm"
							:defaultDate="defaultDate" monthNum="13" :minDate="minDate" @close="()=>{calendar=false}">
						</u-calendar>
					</uni-group>
					<uni-group title="工时">
						<u-input type="number" placeholder="请输入工时" border="bottom" v-model="currTask.manhours"
							@change="saveTask"></u-input>
					</uni-group>
					<uni-group title="附加文件">
						<u-text text="上传文件" prefixIcon="attach" @click="fileOpen" margin="0rpx 0rpx 30rpx 0rpx">
						</u-text>
						<u-row v-for="item in fileList" customStyle="margin-top:5px">
							<u-col span="11">
								<u-text :text="item.fileOriginName" color="blue" @click="downFile(item)"></u-text>
							</u-col>
							<u-col span="1">
								<u-icon name="trash" color="red" size="26px" @click="deleteFile(item)"></u-icon>
							</u-col>
						</u-row>
					</uni-group>
					<u-button text="确定" type="primary" @click="personClose"></u-button>
					<u-popup :show="fileType" mode="bottom" @close="fileClose">
						<view
							style="height: 200px;width:100%;display: flex;flex-direction: column; align-items: center;">
							<u-text text="上传图片" color="blue" size="30" @click="uploadImage"></u-text>
							<u-text text="上传文件" color="blue" size="30" @click="uploadFile"></u-text>
						</view>
					</u-popup>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import taskManage from '../../api/taskManage.js'
	import env from '../../utils/js/env.js'
	import {
		debounce
	} from 'lodash'
	export default {
		data() {
			return {
				type: "",
				isFinish: false,
				pageNo: 1,
				pageSize: 20,
				s_height: 0,
				t_width: 0,
				tasks: [],
				currTask: {},
				leftPop: false,
				personTasks: [],
				addPop: false,
				taskName: "",
				sugPgNo: 1,
				personDetail: false,
				assignedDetail: false,
				taskSteps: [],
				stepName: "",
				taskDate: "",
				calendar: false,
				minDate: "",
				defaultDate: [],
				saveTask: {},
				fileList: [],
				fileType: false,
			}
		},
		onLoad(options) {
			this.type = options.type;
			this.setTitle(this.type);
			this.getDate();
		},
		onReady() {
			let that = this
			uni.getSystemInfo({
				success(res) {
					that.t_width = res.windowWidth - 82;

					const w_height = res.windowHeight;
					var query = uni.createSelectorQuery();
					query.select('#header').boundingClientRect();
					query.select('#bottom').boundingClientRect();
					query.exec(function(res) {
						that.s_height = w_height - res[0].height - res[1].height;
					})
				}
			})
		},
		created() {
			let _this = this
			this.saveTask = debounce(function() {
				taskManage.taskEdit(_this.currTask)
			}, 2000)
		},
		methods: {
			setTitle(type) {
				let titleText = ""
				switch (type) {
					case "today": {
						titleText = "今日任务";
						break;
					}
					case "important": {
						titleText = "重要任务";
						break;
					}
					case "plan": {
						titleText = "计划内";
						break;
					}
					// case "assigned": {
					// 	titleText = "已分配给我";
					// 	break;
					// }
					case "task": {
						titleText = "任务";
						break;
					}
					default: {
						titleText = "其他任务";
					}
				}
				uni.setNavigationBarTitle({
					title: titleText
				})
			},

			change(e) {
				if (e === 'unfinish' && !this.isFinish) {
					return;
				}
				if (e === 'finish' && this.isFinish) {
					return;
				}
				this.pageNo = 1;
				this.isFinish = !this.isFinish;
				this.getDate();
			},

			getDate() {
				let data = {
					taskType: this.type,
					isFinish: this.isFinish,
					pageNo: this.pageNo,
					pageSize: this.pageSize
				}

				taskManage.getTask(data).then(res => {
					if (res.data.success) {
						this.tasks = res.data.data.records;
					}
				})
			},

			getMore() {
				let data = {
					taskType: this.type,
					isFinish: this.isFinish,
					pageNo: this.pageNo + 1,
					pageSize: this.pageSize
				}

				taskManage.getTask(data).then(res => {
					if (res.data.success) {
						if (res.data.data.records.length == 0) {
							uni.showToast({
								title: "没有更多的数据~~",
								mask: true,
								icon: 'none',
								position: "bottom"
							})
							return;
						}

						this.pageNo += 1;
						this.tasks = this.tasks.concat(res.data.data.records);
					}
				})
			},

			finish(task) {
				let _this = this;
				let data = null;
				// if (this.type === "assigned") {
				// 	data = {
				// 		projectTaskId: task.id,
				// 		taskId: task.personTaskId,
				// 	}
				// } else {
				data = {
					taskId: task.id,
					projectTaskId: task.projectTaskId,
				}
				// }

				if (this.isFinish) {
					taskManage.taskUnFinish(data).then(res => {
						if (res.data.success) {
							_this.removeItem(_this.tasks, task)
						}
					})
				} else {
					taskManage.taskFinish(data).then(res => {
						if (res.data.success) {
							_this.removeItem(_this.tasks, task)
						}
					})
				}
				this.currTask = {};
				this.personDetail = false;
				this.assignedDetail = false;
			},

			important(task) {
				let data = {
					id: task.id,
					important: !task.important,
				}
				taskManage.changeImportant(data).then((res) => {
					if (res.data.success) {
						task.important = !task.important
						if (this.type === "important" && !task.important) {
							this.removeItem(this.tasks, task);
						}
					}
				})
			},

			detail(item) {
				this.currTask = item;
				if (this.type === "assigned") {
					this.assignedDetail = true;
				} else {
					this.personDetail = true;
				}
			},

			leftOpen() {
				let data = {
					pageNo: this.sugPgNo,
					pageSize: 30,
				}
				taskManage.getSuggest(data).then(res => {
					if (res.data.success) {
						this.personTasks = res.data.data.records;
					}
				})
			},

			getSuggest() {
				let data = {
					pageNo: this.sugPgNo + 1,
					pageSize: 30,
				}
				taskManage.getSuggest(data).then(res => {
					if (res.data.success) {
						if (res.data.data.records.length === 0) {
							uni.showToast({
								title: "没有更多数据",
								mask: true,
								icon: "none"
							});
							return;
						}
						this.personTasks = this.personTasks.concat(res.data.data.records);
						this.sugPgNo += 1;
					}
				})
			},

			leftClose() {
				this.currTask = {};
				this.sugPgNo = 1;
				this.leftPop = false;
			},

			addToday(task) {
				let data = {
					taskId: task.id,
					sort: 100,
				}
				taskManage.addToday(data).then((res) => {
					if (res.data.success) {
						this.removeItem(this.personTasks, task)
						task.todayId = res.data.data
						if (!this.isFinish && this.leftPop) {
							this.tasks.unshift(task)
						}
					}
				})
			},

			addClose() {
				this.currTask = {};
				this.addPop = false;
			},

			addTask() {
				if (this.taskName.trim() === "") {
					uni.showToast({
						title: "请输入任务名称",
						mask: true,
						icon: "none"
					});
					return;
				}

				//今日任务添加任务，同时添加到今日任务
				if (this.type === "today") {
					let data = {
						name: this.taskName,
						important: false,
						sort: 100,
					}
					taskManage.addTodayTask(data).then((res) => {
						if (res.data.success) {
							if (!this.isFinish) {
								this.tasks.unshift(res.data.data)
							}
							this.taskName = ''
						}
					})
				} else {
					let data = null;
					if (this.type === "important") {
						data = {
							name: this.taskName,
							important: true,
							sort: 100,
						}
					} else if (this.type === "plan") {
						let currTime = new Date()
						let strDate = currTime.getFullYear() + '/' + (currTime.getMonth() + 1) + '/' + currTime.getDate()
						data = {
							name: this.taskName,
							estimatedStartDate: strDate,
							estimatedEndDate: strDate,
							important: false,
							sort: 100,
						}
					} else {
						data = {
							name: this.taskName,
							important: false,
							sort: 100,
						}
					}

					taskManage.addTask(data).then((res) => {
						if (res.data.success) {
							if (!this.isFinish) {
								this.tasks.unshift(res.data.data);
							}
							this.taskName = "";
						}
					})
				}
			},

			personOpen() {
				if (this.currTask.estimatedStartDate != null) {
					let begin = ""
					let end = ""
					if (this.currTask.estimatedStartDate.indexOf(
							' ') > 0) {
						begin = this.currTask.estimatedStartDate.substring(0, this.currTask.estimatedStartDate.indexOf(
							' '))
						end = this.currTask.estimatedEndDate.substring(0, this.currTask.estimatedEndDate.indexOf(' '))
					} else {
						begin = this.currTask.estimatedStartDate
						end = this.currTask.estimatedEndDate
					}
					this.taskDate = begin + '~' + end
					this.defaultDate = [begin, end]
				}
				let currDate = new Date()
				this.minDate = (currDate.getFullYear() - 1) + "-12-27"

				taskManage.getTaskStep(this.currTask.id).then((res) => {
					if (res.data.success) {
						this.taskSteps = res.data.data
					}
				})

				this.getFile();
			},

			getFile() {
				taskManage.getFile(this.currTask.id).then((res) => {
					if (res.data.success) {
						this.fileList = res.data.data
					}
				})
			},

			personClose() {
				this.personDetail = false;
				this.taskDate = "";
			},

			deleteToday() {
				let _this = this
				uni.showModal({
					title: "今日任务删除",
					content: "是否确认从今日任务删除？",
					showCancel: true,
					success(e) {
						if (e.confirm) {
							let data = [{
								id: _this.currTask.todayId,
							}, ]
							taskManage.deleteToday(data).then((res) => {
								if (res.data.success) {
									_this.currTask.todayId = null
									if (_this.type === "today") {
										_this.removeItem(_this.tasks, _this.currTask);
										_this.personDetail = false;
									}
								}
							})
						}
					}
				})
			},

			deleteTask() {
				let _this = this;
				uni.showModal({
					content: "是否确认删除当前任务？",
					success(e) {
						if (e.cancel) {
							return
						}

						let data = [{
							id: _this.currTask.id
						}]
						taskManage.deleteTask(data).then((res) => {
							if (res.data.success) {
								_this.removeItem(_this.tasks, _this.currTask)
								_this.currTask = {};
								_this.taskInfo = {};
								_this.personDetail = false;
								_this.taskDate = "";
							}
						})
					}
				})

			},

			finishStep(step) {
				let data = {
					id: step.id,
				}
				if (step.endTime == null) {
					taskManage.stepFinish(data).then((res) => {
						if (res.data.success) {
							step.endTime = res.data.data
						}
					})
				} else {
					taskManage.stepUnFinish(data).then((res) => {
						if (res.data.success) {
							step.endTime = null
						}
					})
				}
			},

			addStep() {
				if (this.stepName.trim() === "") {
					uni.showToast({
						title: "请输入步骤名称",
						mask: true,
						icon: "none"
					});

					return;
				}
				let data = {
					taskId: this.currTask.id,
					name: this.stepName,
					sort: 100,
				}
				taskManage.addStep(data).then((res) => {
					if (res.data.success) {
						this.taskSteps.push(res.data.data)
					}
				})
				this.stepName = ''
			},

			deleteStep(step) {
				let data = [{
					id: step.id,
				}, ]
				taskManage.deleteStep(data).then((res) => {
					if (res.data.success) {
						this.removeItem(this.taskSteps, step)
					}
				})
			},

			dateConfirm(e) {
				this.defaultDate = e;
				this.calendar = false;
				this.taskDate = e[0] + '~' + e[1];

				this.currTask.estimatedStartDate = e[0];
				this.currTask.estimatedEndDate = e[1];

				this.saveTask();
			},

			fileOpen() {
				this.fileType = true
			},

			fileClose() {
				this.fileType = false
			},

			uploadImage() {
				let _this = this;
				const token = uni.getStorageSync("token")
				console.log(token);
				uni.chooseImage({
					sizeType: ["original", "compressed"],
					success: function(e) {
						for (var i = 0; i < e.tempFiles.length; i++) {
							uni.uploadFile({
								url: env.baseUrl + "/task/mp/uploadimage",
								filePath: e.tempFiles[i].path,
								name: 'file',
								formData: {
									"taskId": _this.currTask.id,
								},
								header: {
									"Authorization": "Bearer " + token,
									"Content-Type": "multipart/form-data"
								},
								success: (res) => {
									_this.getFile()
									_this.fileType = false
								}
							})
						}
					}
				})
			},

			uploadFile() {
				let _this = this;
				const token = uni.getStorageSync("token")
				wx.chooseMessageFile({
					success: function(e) {
						for (var i = 0; i < e.tempFiles.length; i++) {
							uni.uploadFile({
								url: env.baseUrl + "/task/mp/upload",
								filePath: e.tempFiles[i].path,
								name: 'file',
								formData: {
									"taskId": _this.currTask.id,
									"fileName": e.tempFiles[i].name
								},
								header: {
									"Authorization": "Bearer " + token,
									"Content-Type": "multipart/form-data"
								},
								success: (res) => {
									_this.getFile()
									_this.fileType = false
								}
							})
						}
					}
				})
			},

			downFile(e) {
				let parts = e.fileOriginName.split(".");
				let filetype = parts[parts.length - 1];
				let documentType = ["doc", "xls", "ppt", "pdf", "docx", "xlsx", "pptx"]
				let imageType = ["png", "jpg", "jpeg", "gif"]
				if (!documentType.find(function(value) {
						return value == filetype
					}) && !imageType.find(function(value) {
						return value == filetype
					})) {
					uni.showModal({
						content: "小程序暂时不支持该类型文件，请到其他版本应用中查看",
						showCancel: false
					})

					return;
				}

				let _this = this;
				const token = uni.getStorageSync("token")
				uni.request({
					url: env.baseUrl + "/task/file/download",
					data: {
						fileId: e.fileId
					},
					header: {
						"Authorization": "Bearer " + token,
					},
					method: "GET",
					responseType: "arraybuffer",
					success(res) {
						const fs = wx.getFileSystemManager();
						fs.writeFile({
							filePath: wx.env.USER_DATA_PATH + "/" + e.fileOriginName,
							data: res.data,
							encoding: "binary",
							success(s) {
								if (imageType.find(function(value) {
										return value == filetype
									})) {
									uni.previewImage({
										urls: [wx.env.USER_DATA_PATH + "/" + e.fileOriginName]
									})
								} else {
									uni.openDocument({
										filePath: wx.env.USER_DATA_PATH + "/" + e.fileOriginName,
										showMenu: true
									})
								}
							}
						})
					}
				})
			},

			deleteFile(e) {
				taskManage.deleteFile(e.id, e.fileId).then((res) => {
					if (res.data.success) {
						this.removeItem(this.fileList, e)
					}
				})
			},
		}
	}
</script>

<style>
	page {
		height: 100%;
	}

	.content {
		width: 100%;
		height: 100%;
	}

	#header {
		height: 70upx;
		display: flex;
		align-items: flex-end;
		border-bottom: #C0C0C0 solid 5upx;
	}

	#header view {
		height: 50upx;
		font-family: 粗体;
		padding: 0upx 20upx 0upx 20upx;
		margin-bottom: -5upx;
	}

	.select {
		font-weight: bolder;
		font-size: 35upx;
		color: #00aaff;
		border-bottom: #00aaff solid 5upx;
	}

	.item {
		border-bottom: #ececec solid 1upx;
		display: flex;
		align-items: center;
		padding: 10px 10px 10px 10px;
	}

	.image {
		width: 26px;
		height: 26px;
	}

	.image image {
		width: 100%;
		height: 100%;
	}

	.taskdetail {
		margin-left: 20px;
		margin-right: 10px;
	}

	.taskdetail text {
		font-size: 30upx;
	}

	#bottom {
		height: 60upx;
		display: flex;
		justify-content: flex-end;
	}

	.btnSuggest {
		width: 100upx;
		height: 50upx;
		line-height: 50upx;
		border-radius: 25upx;
		padding: 0upx;
		font-size: 25upx;
	}

	.btnAdd {
		width: 50upx;
		height: 50upx;
		line-height: 50upx;
		border-radius: 25upx;
		padding: 0upx;
		font-size: 50upx;
	}

	.leftPop {
		width: 80vw;
		padding-top: 5vh;
		padding-left: 20rpx;
		padding-right: 40rpx;
	}

	.addPop {
		height: 200rpx;
		padding: 20rpx;
	}

	.detail {
		padding-top: 5vh;
		padding-left: 20rpx;
		padding-right: 20rpx;
	}
</style>
