<template>
	<view class="container">
		<page-title>周报录入</page-title>

		<view class="cards-list">
			<view class="card only-card">
				<!-- 项目名称 -->
				<view class="card-item first-card-item">
					<view class="card-item-name">项目名称</view>
					<view class="card-item-input">{{pageForm.subName || "--"}}</view>
				</view>

				<!-- 主体单位 -->
				<view class="card-item">
					<view class="card-item-name">主体单位</view>
					<view class="card-item-input">{{pageForm.UnitName || "--"}}</view>
				</view>

				<!-- 录入周期 -->
				<view class="card-item">
					<view class="card-item-name">录入周期</view>
					<view class="card-item-input">{{editTime || "--"}}</view>
				</view>

				<!-- 当前阶段 -->
				<!-- <view class="card-item">
					<view class="card-item-name">当前阶段</view>
					<view class="card-item-name flex" @click="subPlanOpen()">
						<view v-if="pageForm.subPlanId" class="card-item-input">{{pageForm.subPlanId}}</view>
						<view v-else class="remind-text">请选择阶段</view>
						<u-icon name="arrow-right" color="#343437" size="16" customStyle="margin:auto 0 auto 10rpx"></u-icon>
					</view>
				</view> -->

				<!-- 当前阶段内容 -->
				<!-- <view class="card-item">
					<view class="card-item-name">当前阶段内容</view>
				</view>
				<view class="card-item">
					<u--textarea class="card-item-textarea" v-model="pageForm.content" disabled></u--textarea>
				</view> -->

				<!-- 项目进展情况 -->
				<view class="card-item">
					<view class="card-item-name">项目进展情况<span class="must-input">*</span></view>
				</view>
				<view class="card-item">
					<u--textarea class="card-item-textarea" v-model="pageForm.content" :disabled="banSubmit"></u--textarea>
				</view>

				<!-- 项目延期原因 -->
				<view class="card-item">
					<view class="card-item-name">项目延期原因</view>
				</view>
				<view class="card-item">
					<u--textarea class="card-item-textarea" v-model="pageForm.reason" :disabled="banSubmit"></u--textarea>
				</view>

				<!-- 进度 -->
				<view class="card-item">
					<view class="card-item-name">进度<span class="must-input">*</span></view>
					<view class="card-item-name flex">
						<input type="number" v-model="pageForm.numBl" class="card-item-input" placeholder="填写进度"
							placeholder-style="color: #D8D8D8" maxlength="20" :disabled="banSubmit" />
						<view class="card-item-unit">%</view>
					</view>
				</view>

				<!-- 附件（照片） -->
				<view class="card-item flex-align-start">
					<view class="card-item-name" style="min-width: 156rpx;">图片附件</view>
					<u-upload :fileList="uploadListPhoto" @afterRead="afterReadPhoto" @delete="delFilePhoto"
						uploadIcon="plus"></u-upload>
				</view>

				<!-- 附件（视频） -->
				<view class="card-item flex-align-start">
					<view class="card-item-name" style="min-width: 156rpx;">视频附件</view>
					<u-upload :fileList="uploadListVideo" @afterRead="afterReadVideo" @delete="delFileVideo"
						@onVideoClick="videoClick" name="file" uploadIcon="plus" accept="video"></u-upload>
				</view>

				<!-- 附件（文件） -->
				<view class="card-item flex-align-start">
					<view class="card-item-name" style="min-width: 156rpx;">其他附件</view>
					<view class="upload-file-area">
						<view class="upload-file-name" v-for="(item,index) in uploadListFile" :key="index"
							@click="showFile('pdf',item.url)">
							{{item.fileName}}
						</view>
					</view>
				</view>
			</view>

			<view class="confirm-btn" :class="banSubmit?'ban-submit':''" @click="confirmParams()">确定</view>
		</view>

		<!-- 当前阶段 -->
		<u-picker :show="subPlanShow" :columns="subPlanList" @confirm="subPlanClose" @cancel="subPlanClose"
			@close="subPlanClose" closeOnClickOverlay></u-picker>
	</view>
</template>

<script setup>
	import config from '@/config.js'

	import {
		ref
	} from 'vue'

	import {
		onLoad
	} from "@dcloudio/uni-app"

	import {
		uploadFilePromise
	} from "@/utils/request_new.js"

	import {
		getWeeklyById,
		saveWeekly
	} from "@/api/work/weeklyAndMonthly.js"

	let editTime = ref(null)

	let pageForm = ref({
		year: null,
		beginDate: null,
		endDate: null,
		subId: null,
		subName: null,
		UnitName: null,
		subPlanId: null,
		content: null,
		reason: null,
		numBl: null,
		listFile: [],
	})

	let fileTypeCode = {
		0: "dir",
		1: "txt",
		2: "doc",
		3: "docx",
		4: "xls",
		5: "xlsx",
		6: "ppt",
		7: "pptx",
		8: "pdf",
		9: "swf",
		101: "jpg",
		102: "image",
		103: "jpeg",
		104: "bmp",
		105: "gif",
		201: "avi",
		202: "wmv",
		202: "flv",
		203: "video"
	}

	// 当前阶段
	let subPlanShow = ref(false)
	let subPlanList = ref([])
	let subPlanContentList = ref([])

	function subPlanOpen() {
		subPlanShow.value = true
	}

	function subPlanClose(e) {
		if (e) {
			pageForm.value.subPlanId = e.value[0]
			pageForm.value.content = subPlanContentList.value.find(item => item.time === e.value[0]).content
		}
		subPlanShow.value = false
	}

	function parseDate(date, year) {
		pageForm.value.year = year;
		const index = date.indexOf("至")
		pageForm.value.beginDate = date.substring(0, index)
		pageForm.value.endDate = date.substring(index + 1)
	}

	// 获取数据
	function getWeeklyDetail(sendParams) {
		let params = {
			subId: sendParams.subId,
			startDate: sendParams.startDate,
			year: sendParams.year
		}

		getWeeklyById(params).then(res => {
			pageForm.value.subName = res.data.subName;
			pageForm.value.UnitName = res.data.UnitName;
			pageForm.value.subId = res.data.subId;
			pageForm.value.numBl = res.data.weekInfo.numBl;
			pageForm.value.content = res.data.weekInfo.content;
			pageForm.value.reason = res.data.weekInfo.reason;
			// combinePlanList(res.data.subPlanList)
			// showHavingData(sendParams)
			conbineFileList(res.data.listFile)
		})
	}

	function combinePlanList(list) {
		let subPlanListItem = []
		let subPlanContentListTemp = []
		for (let i in list) {
			let showName = `${list[i].beginDate}至${list[i].endDate}`;
			let content = list[i].content;
			let id = list[i].id;
			subPlanListItem.push(showName)
			subPlanContentListTemp.push({
				id,
				content,
				time: showName,
			})
		}
		subPlanList.value.push(subPlanListItem)
		subPlanContentList.value = subPlanContentListTemp
	}

	// 展示已有数据
	function showHavingData(data) {
		// pageForm.value.numBl = data.num_bl
		if (data.sub_plan_id) {
			let statuItem = subPlanContentList.value.find(item => item.id === data.sub_plan_id)
			if (statuItem) {
				pageForm.value.content = statuItem.content;
				pageForm.value.subPlanId = statuItem.time
			}
		}
	}

	// 组合附件数据
	function conbineFileList(list) {
		// 添加上传成功标识
		const statusList = list.map(item => {
			let orginal = {
				...item
			}

			return Object.assign(
				orginal, {
					status: 'success'
				})
		})

		// 照片附件
		let listPhoto = statusList.filter(item => ['101', '102', '103', '104', '105'].includes(item.fileType))
		uploadListPhoto.value = listPhoto

		// 视频附件
		let listVideo = statusList.filter(item => ['202', '203'].includes(item.fileType));
		uploadListVideo.value = listVideo;

		// 其他附件
		let exceptPhotoList = statusList.filter(item => !listPhoto.includes(item));
		uploadListFile.value = exceptPhotoList.filter(item => !listVideo.includes(item));

		// 上传数据
		const dataList = list.map(item => {
			let orginal = {
				...item
			}
			return {
				id: orginal.id,
				fileName: orginal.fileName,
				fileType: orginal.fileType,
				fileAddre: orginal.fileAddre
			}
		})
		pageForm.value.listFile = dataList

		// 备份初始数据
		listFileOrginal = dataList
	}

	// ====================附件上传
	let listFileOrginal = [] //原始数据--备份比较用
	let uploadListPhoto = ref([]) //上传列表--图片
	let uploadListVideo = ref([]) //上传列表--视频
	let uploadListFile = ref([]) //上传列表--文件

	// 上传文件操作
	async function afterReadPhoto(event) {
		if (banSubmit.value) return

		let lists = [].concat(event.file); //文件内容
		let fileListLen = uploadListPhoto.value.length; //数量

		lists.map((item) => {
			uploadListPhoto.value.push({
				...item,
				status: 'uploading',
				message: '上传中'
			})
		})

		for (let i = 0; i < lists.length; i++) {
			const resultObj = await uploadFilePromise(lists[i].url);
			// console.log(resultObj);

			let fileItem = {
				fileName: resultObj.data.resultList[0].name,
				fileType: resultObj.data.resultList[0].ftype,
				fileAddre: resultObj.data.resultList[0].id
			}
			pageForm.value.listFile.push(fileItem)

			// 上传地址
			const serverAddress = uni.getStorageSync("serverAddress");
			const baseUrlIp = serverAddress ? serverAddress : config.baseUrl;
			const preViewUrl = baseUrlIp + "/projects//static/file/";

			// =================取消上传中状态

			// 文件
			let item = uploadListPhoto.value[fileListLen]
			// 文件类型
			let type = fileTypeCode[resultObj.data.resultList[0].ftype]

			uploadListPhoto.value.splice(fileListLen, 1, Object.assign(item, {
				status: 'success',
				message: '',
				url: preViewUrl + resultObj.data.resultList[0].id + "/showfile",
				id: resultObj.data.resultList[0].id,
				preView: preViewUrl + resultObj.data.resultList[0].id + "/showfile",
				// type
			}))

			fileListLen++
		}
	}

	// 删除文件
	function delFilePhoto(event) {
		if (banSubmit.value) return

		// 从渲染列表里移除
		uploadListPhoto.value.splice(event.index, 1);

		// 从文件里删除或标记
		let delFileIndex = pageForm.value.listFile.findIndex(item => item.fileAddre === event.file.fileAddre || item
			.fileAddre ===
			event.file.id);

		let delFile = pageForm.value.listFile[delFileIndex];

		// 是否是已经上传的文件
		if (delFile && delFile.id) {
			// 已保存
			delFile.logicDeleteFlag = 1
		} else {
			pageForm.value.listFile.splice(delFileIndex, 1)
		}
	}

	function waterMarkShow(event) {

		return uni.navigateTo({
			url: `/pages/weekly/media/index?url=${event.url}&time=${event.createTime}`
		})
	}

	// 上传文件操作--视频
	async function afterReadVideo(event) {
		if (banSubmit.value) return

		let lists = [].concat(event.file); //文件内容
		let fileListLen = uploadListVideo.value.length; //数量

		lists.map((item) => {
			uploadListVideo.value.push({
				...item,
				status: 'uploading',
				message: '上传中'
			})
		})

		for (let i = 0; i < lists.length; i++) {
			const resultObj = await uploadFilePromise(lists[i].url);

			let fileItem = {
				fileName: resultObj.data.resultList[0].name,
				fileType: resultObj.data.resultList[0].ftype,
				fileAddre: resultObj.data.resultList[0].id
			}
			pageForm.value.listFile.push(fileItem)

			// 上传地址
			const serverAddress = uni.getStorageSync("serverAddress");
			const baseUrlIp = serverAddress ? serverAddress : config.baseUrl;
			const preViewUrl = baseUrlIp + "/projects//static/file/";

			// =================取消上传中状态

			// 文件
			let item = uploadListVideo.value[fileListLen]
			// 文件类型
			let type = fileTypeCode[resultObj.data.resultList[0].ftype]

			uploadListVideo.value.splice(fileListLen, 1, Object.assign(item, {
				status: 'success',
				message: '',
				url: preViewUrl + resultObj.data.resultList[0].id + "/showfile",
				id: resultObj.data.resultList[0].id,
				preView: preViewUrl + resultObj.data.resultList[0].id + "/showfile",
				// type
			}))

			fileListLen++
		}
	}

	// 删除文件--视频
	function delFileVideo(event) {
		if (banSubmit.value) return

		uploadListVideo.value.splice(event.index, 1);

		// 从文件里删除或标记
		let delFileIndex = pageForm.value.listFile.findIndex(item => item.fileAddre === event.file.fileAddre || item
			.fileAddre ===
			event.file.id);

		let delFile = pageForm.value.listFile[delFileIndex];

		// 是否是已经上传的文件
		if (delFile && delFile.id) {
			// 已保存
			delFile.logicDeleteFlag = 1
		} else {
			pageForm.value.listFile.splice(delFileIndex, 1)
		}
	}

	// 播放文件--视频
	function videoClick(event) {
		showFile(event.fileType, event.url)
	}

	// 文件预览
	function showFile(type, filePath) {
		uni.navigateTo({
			url: `/pages/projectInfo/media/index?type=${type}&filePath=${filePath}`
		})
	}

	//====================提交数据
	let banSubmit = ref(false);
	let isSubmit = ref(false);

	// 提交操作
	function confirmParams() {
		// 禁止提交
		if (banSubmit.value || isSubmit.value) return;

		// 检查必填项
		if (((pageForm.value.content ?? '') === '') || ((pageForm.value.numBl ?? '') === '')) {
			return uni.showModal({
				title: '请检查',
				content: '进度与项目进展情况为必填项。',
				showCancel: false
			})
		}

		// 确认提交
		uni.showModal({
			title: "保存确认",
			content: "确定要保存该周报录入吗?",
			success: function(res) {
				if (res.confirm) {
					let params = Object.assign({}, pageForm.value)
					delete(params.UnitName)
					delete(params.subName)
					let subPlanIdItem = subPlanContentList.value.find(item => item.time === params.subPlanId)
					params.subPlanId = subPlanIdItem ? subPlanIdItem.id : null
					isSubmit.value = true;
					saveWeekly(params).then(res => {
						if (res.code === 200) {
							isSubmit.value = false;
							banSubmit.value = true;
							uni.showToast({
								title: "保存成功",
								icon: "success",
								duration: 2000
							})
						}
					}).catch(() => {
						isSubmit.value = false;
						uni.showToast({
							title: "保存失败",
							icon: "error",
							duration: 2000
						})
					})
				} else if (res.cancel) {
					uni.showToast({
						title: "取消保存",
						icon: "none",
						duration: 2000,
					})
				}
			},
		})
	}

	onLoad((options) => {
		editTime.value = options.kj_month
		parseDate(options.kj_month, options.year)
		getWeeklyDetail(options)
	})
</script>

<style lang="scss" scoped>
	.must-input {
		color: #f00;
	}
</style>