<template>
	<view class="content">
		<VNavigationBar style="position: relative;z-index: 99;" homeHeaderPaddingTop="0" backgroundColor="#fff"
			title-color="#000" title="工作汇报"></VNavigationBar>
		<view class="container">
			<view class="box_">
				<view class="title_">
					<text style="color: red;">*</text>
					汇报主题
				</view>
				<u--input placeholder="请输入" border="surround" v-model="report.reportTopic"></u--input>
				<view class="x_"></view>
				<view class="" @click="show =! show">
					<text class="h_">汇报时间：</text>
					{{ formatDateTimeToMinute(report.reportTime) }}
				</view>
				<view class="x_"></view>
				<view class="d_s" @click="isShowReportTo = true">
					<text class="h_">汇报给：{{ reportTosStr }}</text>
					<view class="j_">+</view>
				</view>
				<view class="x_"></view>
				<view class="title_">
					<text style="color: red;">*</text>
					汇报内容
				</view>
				<!-- <u--textarea v-if="type != 'look'" v-model="report.reportContent" placeholder="请输入内容"></u--textarea> -->
				<textarea maxlength="-1" auto-height v-model="report.reportContent" placeholder="请输入内容"></textarea>
				<!-- <view class="x_"></view> -->
				<view class="d_b" @click="handleUpload" v-if="type != 'look'">
					<view class="">附件</view>
					<view class="lan_">上传附件
						<image src="/static/imgs/add.png" mode=""></image>
					</view>
				</view>
				<u-upload ref="uploadRef" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1"
					multiple :maxCount="10" v-show="fileList1.length > 0">
				</u-upload>
				<view class="hui_box" v-if="fileList1.length == 0">
					<image src="/static/imgs/wod.png" mode=""></image>
					<view class="">
						<view class="big_">附件格式pdf/jpg/png</view>
						<view class="sm_">100KB</view>
					</view>
				</view>
				<view class="anniu" @click="onSubmit" v-if="type != 'look'">
					{{ buttonTitle}}
				</view>
			</view>
		</view>

		<u-datetime-picker :show="show" @cancel="show = false" @confirm="selectReportTime" v-model="report.reportTime"
			mode="datetime"></u-datetime-picker>

		<qianziyu-select :show="isShowReportTo" type="checkbox" name="nickname" :dataLists="reportToList"
			:showSearch=false @cancel="isShowReportTo = false" :checkboxData="report.reportTos"
			@submit="onReportToSubmit" popupTitle='汇报对象选择' @update:checkboxData="report.reportTos = $event">
		</qianziyu-select>
	</view>
</template>

<script>
	import request from "@/utils/request";
	import {
		formatDateTimeToMinute
	} from "@/utils/utils";
	import upload from "@/utils/upload";
	import config from "@/config";
	import VNavigationBar from "@/components/VNavigationBar.vue";

	export default {
		data() {
			return {
				titles: "汇报",
				List: [],
				show: false,
				status: 'loading',
				value: '',
				type: '',
				value1: Number(new Date()),
				value2: '',
				show1: false,
				report: {
					reportTopic: '',
					reportContent: '',
					reportTime: formatDateTimeToMinute(new Date()),
					reportTos: [],
					servicePackageId: "weixiu",
				},
				isShowReportTo: false,
				reportToList: [],
				reportTosStr: null,
				fileList1: [],
				buttonTitle: "保存",
				baseImageUrl: config.imagesUrl,
			}
		},
		components: {
			VNavigationBar
		},
		async onLoad(data) {
			await this.getReportTo(); // 等待 getReportTo 执行完成
			if (data.id) {
				this.type = 'look'
				this.buttonTitle = "修改"
				console.log(data.id)
				this.getWorkReport(data.id)
			}
		},
		methods: {
			formatDateTimeToMinute,
			cancelShow() {
				this.show = !this.show
			},
			async getReportTo() {
				await request({
					url: '/admin-api/work/report/queryReportTo',
					method: 'get',
					params: {
						dictType: "repair_report_role"
					}
				}).then(res => {
					this.reportToList = res.data
				})
			},
			onReportToSubmit(selectedData) {
				this.isShowReportTo = false
				this.report.reportTos = selectedData
				this.reportTosStr = selectedData.map(item => item.nickname).join(',')
			},
			selectReportTime(e) {
				this.report.reportTime = formatDateTimeToMinute(e.value)
				this.show = false
			},

			// 上传相关方法
			handleUpload() {
				// 通过 ref 获取 u-upload 组件实例，并调用其上传方法
				this.$refs.uploadRef.chooseFile();
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					upload({
						url: '/admin-api/common/upload',
						filePath: url,
					}).then((res) => {
						resolve(res.data.url);
						this.forceRefreshFiles(); // 强制刷新文件列表
					})
				});
			},
			/** 表单提交 */
			onSubmit() {
				//校验
				const isValid = this.checkForm()
				if (!isValid) {
					return
				}
				//将文件转为字符串
				this.report.filePath = this.fileList1
					.map(item => item.url.replace(/^https?:\/\/[^/]+\/minio\//, '')) // 去除域名和 minio/
					.join(',');

				this.report.reportTos = this.report.reportTos.map(item => item.id)
				let url = '/admin-api/work/report/create'
				let method = 'post'
				if (this.report.id) {
					url = '/admin-api/work/report/update'
					method = 'put'
				}
				request({
					url: url,
					method: method,
					data: this.report
				}).then(res => {
					if (res.code === 200) {
						uni.showToast({
							title: '提交成功',
							icon: 'none',
							duration: 2000
						});
						setTimeout(() => {
							// 在跳回之前刷新页面
							uni.navigateBack()
						}, 2000);
					}
				})
			},
			/** 校验 */
			checkForm() {
				if (this.report.reportTos.length === 0) {
					if (!this.report.reportTopic) {
						uni.showToast({
							title: '请输入汇报主题',
							icon: 'none',
							duration: 2000
						});
						return false
					}

					uni.showToast({
						title: '请选择汇报对象',
						icon: 'none',
						duration: 2000
					});
					return false
				}

				if (!this.report.reportContent) {
					uni.showToast({
						title: '请输入汇报内容',
						icon: 'none',
						duration: 2000
					});
					return false
				}
				return true
			},
			/** 获取汇报对象 */
			async getWorkReport(id) {
				await request({
					url: '/admin-api/work/report/get?id=' + id,
					method: 'get'
				}).then(res => {
					this.report = res.data
					// 根据 ID 数组查找对应的数据，并赋值给 report.reportTos
					this.report.reportTos = this.reportToList.filter(item => res.data.reportTos.includes(item
						.id));
					// 文件路径处理
					if (this.report.filePath) {
						const paths = this.report.filePath.split(',');
						this.fileList1 = paths.map(path => {
							// 如果是 http 开头，说明是完整路径，直接用
							if (/^https?:\/\//.test(path)) {
								return {
									url: path,
									status: 'success'
								};
							} else {
								// 否则拼接 baseImageUrl（你 config.imagesUrl 中的前缀）
								return {
									url: this.baseImageUrl + path,
									status: 'success'
								};
							}
						});
					}
					/* this.reportTosStr = this.report.reportTos.map(item => item.nickname).join(',')
					console.log('当前选择的汇报对象', this.reportTosStr)
					if (res.data.filePath) {
						this.fileList1 = res.data.filePath.split(',').map(item => {
							return {
								url: this.baseImageUrl + "/" + item
							}
						})
					} */
				})
			},
			pageBack() {
				uni.navigateBack({
					delta: 1 // delta值为1时表示返回的页面层数
				});
			},
		},
	}
</script>

<style scoped lang="scss">
	.content {
		width: 100%;
		box-sizing: border-box;
		// padding-top: 200rpx;
		background: #f4f5f6;
		height: 100vh;
		overflow-y: auto;
		display: flex;
		flex-direction: column;
	}

	.container {
		background: #f4f5f6;
		box-sizing: border-box;
		padding: 30rpx;
	}

	.box_ {
		width: 100%;
		background: #fff;
		box-sizing: border-box;
		padding: 30rpx;
	}

	.title_ {
		font-size: 28rpx;
		color: #101A3E;
		margin-bottom: 10px;
	}

	.x_ {
		width: 100%;
		height: 2rpx;
		background: #f4f5f6;
		margin: 30rpx 0rpx;
	}

	.h_ {
		font-size: 28rpx;
		color: #8D90A6;
	}

	.d_s {
		display: flex;
		align-items: center;
	}

	.j_ {
		width: 40rpx;
		height: 40rpx;
		background: #D9E0EC;
		display: flex;
		align-items: center;
		color: #fff;
		line-height: 40rpx;
		justify-content: center;
	}

	.d_b {
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
		padding: 30rpx 0rpx;
		border-top: 2rpx solid #F5F6F9;
		font-size: 28rpx;
		color: #8D90A6;

	}

	.telnum {
		font-size: 24rpx;
		color: #366FFF;
	}

	.lan_ {
		font-size: 28rpx;
		color: #327DFB;
		display: flex;
		align-items: center;

		image {
			width: 36rpx;
			height: 36rpx;
			margin-left: 15rpx;
		}
	}

	.hui_box {
		width: 100%;
		background: #F5F6F9;
		border-radius: 16rpx;
		box-sizing: border-box;
		padding: 30rpx;
		display: flex;
		align-items: center;

		image {
			width: 90rpx;
			height: 90rpx;
			margin-right: 15rpx;
		}
	}

	.big_ {
		font-size: 28rpx;
		color: #101A3E;
	}

	.sm_ {
		font-size: 22rpx;
		color: #8D90A6;
	}

	.anniu {
		width: 622rpx;
		height: 78rpx;
		border: 2rpx solid #0174F6;
		border-radius: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #0174F6;
		margin-top: 200rpx;
	}
</style>