<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">{{editMonth || "--"}}</view>
				</view>

				<!-- 当月实际投资 -->
				<view class="card-item">
					<view class="card-item-name" style="min-width: 192rpx;">当月实际投资</view>

					<view class="card-item-input" v-if="!beforeTime">暂不可填写 </view>
					<view class="card-item-name flex" v-else>
						<input type="number" v-model="pageForm.amt" class="card-item-input" placeholder="填写金额"
							placeholder-style="color: #D8D8D8" maxlength="20" :disabled="!checkedit || banSubmit" />
						<view class="card-item-unit">万元 </view>
					</view>
				</view>

				<!-- 当月入统资金 -->
				<view class="card-item">
					<view class="card-item-name" style="min-width: 192rpx;">当月入统资金</view>

					<view v-if="!beforeTime" class="card-item-input">暂不可填写 </view>
					<view v-else class="card-item-name flex">
						<input type="number" v-model="pageForm.amtRt" class="card-item-input" placeholder="填写金额"
							placeholder-style="color: #D8D8D8" maxlength="20" :disabled="!checkedit || banSubmit" />
						<view class="card-item-unit">万元 </view>
					</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.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="!checkedit || banSubmit" />
						<view class="card-item-unit">%</view>
					</view>
				</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="!checkedit || banSubmit"></u--textarea>
				</view>

				<!-- 下月预测投资金额 -->
				<view class="card-item">
					<view class="card-item-name" style="min-width: 256rpx;">下月预测投资金额</view>

					<view class="card-item-name flex">
						<input type="number" v-model="pageForm.amtLast" class="card-item-input" placeholder="填写金额"
							placeholder-style="color: #D8D8D8" maxlength="20" :disabled="!checkedit || banSubmit" />
						<view class="card-item-unit" style="min-width: 128rpx;">（万元）</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" name="file"
						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 v-if="checkedit" class="confirm-btn" :class="banSubmit?'ban-submit':''" @click="confirmParams()">确定</view>
		</view>
	</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 {
		getMonthlyById,
		saveMonthly
	} from "@/api/work/weeklyAndMonthly.js"

	// 是否可编辑
	let checkedit = ref(false)

	// 是否可编辑月份
	let beforeTime = ref(true)

	// 正在编辑的月份
	let editMonth = ref(null)

	let pageForm = ref({
		year: null,
		beginDate: null,
		subId: null,
		subName: null,
		UnitName: null,
		amtRt: null,
		content: null,
		numBl: null,
		content: null,
		amtLast: null,
		reason: 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"
	}

	// ====================获取数据
	function getMonthlyDetail(sendParams) {
		let beginDateTempY = sendParams.kj_month.replace("年", "-")
		let timeFormat = beginDateTempY.replace("月", "-") + "01"

		pageForm.value.beginDate = timeFormat;
		pageForm.value.year = sendParams.year;

		let params = {
			subId: sendParams.subId,
			startDate: timeFormat,
			year: sendParams.year,
			kjMonth: sendParams.kj_month
		}

		getMonthlyById(params).then(res => {
			checkedit.value = res.data.checkedit === "1";
			pageForm.value.subName = res.data.subName;
			pageForm.value.UnitName = res.data.UnitName;
			pageForm.value.subId = res.data.subId;
			pageForm.value.numBl = res.data.numBl;
			pageForm.value.amt = res.data.amt;
			pageForm.value.content = res.data.content;
			pageForm.value.amtLast = res.data.amtLast;
			pageForm.value.reason = res.data.reason;
			pageForm.value.amtRt = res.data.amtRt;
			judgeBeforeTime(res.data.check);
			conbineFileList(res.data.listFile);
		})
	}

	// 组合附件数据
	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
	}

	// 判断是否能填写金额
	function judgeBeforeTime(check) {
		// check  1 可以编辑，0不可编辑
		if (check === "0") {
			return beforeTime.value = false;
		}

		const D = new Date();
		// 比较月份
		let pageMonth = Number(editMonth.value.slice(5, 7));
		let month = D.getMonth() + 1;

		// 控制当月
		let day = D.getDate();
		if (pageMonth === month && day < 25) {
			return beforeTime.value = false;
		}
		beforeTime.value = true;
	}

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

	// 上传文件操作
	async function afterReadPhoto(event) {
		if (!checkedit.value) return uni.showToast({
			title: "无操作权限",
			icon: "error",
			duration: 2000
		})

		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);
			// let resultObj = JSON.parse(result);

			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 (!checkedit.value) return uni.showToast({
			title: "无操作权限",
			icon: "error",
			duration: 2000
		})

		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)
		}
	}

	// 上传文件操作--视频
	async function afterReadVideo(event) {
		if (!checkedit.value) return uni.showToast({
			title: "无操作权限",
			icon: "error",
			duration: 2000
		})

		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 resultObj = JSON.parse(result);

			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 (!checkedit.value) return uni.showToast({
			title: "无操作权限",
			icon: "error",
			duration: 2000
		})

		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.numBl ?? '') === '') || ((pageForm.value.content ?? '') === '')) {
			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);
					isSubmit.value = true;
					saveMonthly(params).then(res => {
						isSubmit.value = false;
						banSubmit.value = true;
						if (res.code === 200) {
							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) => {
		editMonth.value = options.kj_month;
		getMonthlyDetail(options);
		if (options.amtRt) {
			pageForm.value.amtRt = options.amtRt;
		}
	})
</script>

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