<template>
	<div style="width: 100%; height: 100%; padding: 10px; box-sizing: border-box" v-loading="loading">
		<div class="intPage">
			<div class="tit">H5页面说明上传后台</div>
			<div>
				<div>请选择ai探究中心课程</div>
				<el-select v-model="id" @change="cutCourse" placeholder="请选择">
					<el-option
					v-for="item in courseList"
					:key="item.id"
					:label="item.name"
					:value="item.id">
					</el-option>
				</el-select>
				<!-- <el-input v-model.trim="id" placeholder="请输入内容"></el-input> -->
			</div>
			<div>
				<div>请输入使用说明</div>
				<editor-bar
					class="addEditor"
					style="margin: 0"
					placeholder="请输入"
					v-model="inData.content"
					@change="change"
				></editor-bar>
			</div>
			<div>
				<div>请上传附件(只能上传pdf)</div>
				<button style="position: relative;padding: 1px 10px;box-sizing: border-box;">
					上传
					<input
						type="file"
						accept="PDF"
						style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;opacity: 0;"
						multiple="multiple"
						@change="beforeUpload1($event)"
					/>
				</button>
				
			</div>
			<div style="display: flex;flex-direction: column;gap: 10px;">
				<div style="display: flex;gap: 30px;" v-for="(i,ind) in inData.file" :key="ind">
					<span>{{ i.name }}</span>
					<span style="color: red;cursor: pointer;" @click="delFile(ind)">删除</span>
				</div>
			</div>
			<div>
				<el-button type="primary" @click="uploadCon">提交</el-button>
			</div>
		</div>
	</div>
</template>

<script>
import EditorBar from "./wangEnduit";
import { addOp, updateinst,selectAiExp } from "@/api/user";
import { mapGetters } from "vuex";

export default {
	name: "instUpdata",
	computed: {
		...mapGetters(["userid"])
	},
	components:{
		EditorBar
	},
	data() {
		return {
			id: "",
			inData: {
				userid: this.userid,
				content: "",
				file: [],
			},
			loading:false,
			courseList:[],
			progress: 0,
			proVisible: false,
		};
	},
	mounted(){
		this.getData()
	},
	methods: {
		cutCourse(val){
			console.log('val',val);
			this.inData = {
				userid: this.userid,
				content: "",
				file: [],
			}
			let data = this.courseList.filter(e=> e.id == val)[0]
			console.log('data',data);
			if (data.inst) {				
				this.inData.content = JSON.parse(data.inst).content
				this.inData.file = JSON.parse(data.inst).file
			}
		},
		getData(){
			this.loading = true;
			let params = {
				cl:1
			};
			selectAiExp(params)
				.then(async (res) => {
					console.log(res);
                    this.courseList = res.data[1]
                    this.loading = false;
				})
				.catch((error) => {
                    this.loading = false;
					console.error("请求失败，错误信息：", error);
				});
		},
		change(val) {
			
			// this.$forceUpdate();

			console.log(val);
		},
		delFile(ind){
			this.inData.file.splice(ind,1)
		},
		addImg(e) {
			var el = e.currentTarget;
			console.log(el);
			el.getElementsByTagName("input")[0].click();
			e.target.value = "";
		},
		uploadCon() {
			if (!this.id) return this.$message.error("上传课程id");

			let params = {
				idL: this.id,
				con: JSON.stringify(this.inData),
			};			
			console.log("params", params);
			updateinst(params)
				.then(async (response) => {
					if (response) {
						console.log("response", response);

						await addOp({
							uid: this.userid,
							cid: "",
							type: "user_op",
							content: `修改了${this.id}课程说明`,
						});
						this.$message({
							type: "success",
							message: "修改成功",
						});
						this.getData()
						this.id = "";
						this.inData = {
							userid: this.userid,
							content: "",
							file: [],
						};
					}
				})
				.catch((error) => {
					console.error("请求失败，错误信息：", error);
				});
		},
		beforeUpload(event) {
			// const loading = this.openLoading();
			// var file = "";

			// for (let cfindex = 0; cfindex < event.target.files.length; cfindex++) {
			console.log("event.target.files", event.target.files);
			var file = event.target.files[0];
			var credentials = {
				accessKeyId: "AKIATLPEDU37QV5CHLMH",
				secretAccessKey: "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",
			}; //秘钥形式的登录上传
			window.AWS.config.update(credentials);
			window.AWS.config.region = "cn-northwest-1"; //设置区域

			var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
			var imgA = [
				"png",
				"jpg",
				"jpeg",
				"bmp",
				"gif",
				"webp",
				"psd",
				"svg",
				"tiff",
			];
			if (
				imgA.indexOf(file.name.split(".")[file.name.split(".").length - 1]) ==
				-1
			) {
				this.$message.error("图片格式错误");
				return;
			}
			// this.imgLoading = true;
			var _this = this;

			// this.inputShow = false;
			// this.progress = 0;
			this.proVisible = true;
			// this.isFinishSize = 0;
			// this.isAllSize = (file.size / 1024 / 1024).toFixed(2);
			_this.$forceUpdate();

			if (file) {
				var params = {
					Key:
						file.name.split(".")[0] +
						new Date().getTime() +
						"." +
						file.name.split(".")[file.name.split(".").length - 1],
					ContentType: file.type,
					Body: file,
					"Access-Control-Allow-Credentials": "*",
					ACL: "public-read",
				}; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
				var options = {
					partSize: 2048 * 1024 * 1024,
					queueSize: 2,
					leavePartsOnError: true,
				};
				bucket
					.upload(params, options)
					.on("httpUploadProgress", function () {
						//这里可以写进度条
						// _this.progress = parseInt((evt.loaded / evt.total) * 100);
						// _this.isFinishSize = (evt.loaded / 1024 / 1024).toFixed(2);
						_this.$forceUpdate();
					})
					.send(function (err, data) {
						// _this.imgLoading = false;
						// loading.close();
						// _this.progress = 100;
						// _this.isFinishSize = _this.isAllSize;
						_this.$forceUpdate();
						setTimeout(() => {
							_this.proVisible = false;
							_this.$forceUpdate();
						}, 1000);
						// _this.inputShow = true;

						if (err) {
							_this.$message.error("上传失败");
						} else {
							let quill = _this.$refs.myQuillEditor.quill;
							// 如果上传成功
							let length = quill.getSelection().index;
							// 插入图片  res.url为服务器返回的图片地址
							quill.insertEmbed(length, "image", data.Location);
							// 调整光标到最后
							quill.setSelection(length + 1);
							// if (!res) {
							//   // 获取光标所在位置
							// } else {
							//   this.$message.error("图片插入失败");
							// }
							// loading动画消失
							this.quillUpdateImg = false;

							// _this.recordData.recordImg.push(data.Location);
							_this.$forceUpdate();

							// console.log(_this.checkJson);
							// console.log(data.Location);
						}
					});
			}
			// }

			// var file = event.target.files[0];
		},
		onEditorChange({ html }) {
			//内容改变事件
			// console.log("---内容改变事件---");
			this.inData.content = html;
			// console.log(html);
		},
		async beforeUpload1(event) {
			var files = Array.from(event.target.files);
			console.log("上传文件列表:", files);

			if (files.length === 0) {
				this.$message.warning("请选择文件");
				return;
			}

			// 检查文件格式
			var photoA = ["PDF"];
			var invalidFiles = files.filter((file) => {
				var extension = file.name.split(".")[file.name.split(".").length - 1].toLocaleUpperCase();
				return photoA.indexOf(extension) === -1;
			});

			if (invalidFiles.length > 0) {
				this.$message.error("请只上传PDF格式文件!");
				return;
			}

			// AWS配置
			var credentials = {
				accessKeyId: "AKIATLPEDU37QV5CHLMH",
				secretAccessKey: "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",
			};
			window.AWS.config.update(credentials);
			window.AWS.config.region = "cn-northwest-1";

			var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } });
			var _this = this;

			var uploadedCount = 0;
			var failedFiles = [];

			// 顺序上传每个文件
			for (let i = 0; i < files.length; i++) {
				let file = files[i];

				try {
					var result = await new Promise((resolve, reject) => {
						var params = {
							Key:
								file.name.split(".")[0] +
								new Date().getTime() +
								"_" +
								i + // 添加索引避免重复
								"." +
								file.name.split(".")[file.name.split(".").length - 1],
							ContentType: file.type,
							Body: file,
							"Access-Control-Allow-Credentials": "*",
							ACL: "public-read",
						};

						var options = {
							partSize: 1024 * 1024 * 1024,
							queueSize: 2,
							leavePartsOnError: true,
						};

						bucket
							.upload(params, options)
							.on("httpUploadProgress", function (progress) {
								// 显示单个文件的上传进度
								console.log(
									`文件 ${file.name} 上传进度: ${(
										(progress.loaded / progress.total) *
										100
									).toFixed(2)}%`
								);
							})
							.send(function (err, data) {
								if (err) {
									reject(err);
								} else {
									resolve(data);
								}
							});
					});
                    console.log('result',result);
                    
					_this.inData.file.push({
                        name:files[i].name,
                        url:result.Location,
                    });
					uploadedCount++;
					console.log(`文件 ${file.name} 上传成功:`, result.Location);
				} catch (error) {
					console.error(`文件 ${file.name} 上传失败:`, error);
					failedFiles.push({
						fileName: file.name,
						error: error.message,
					});
				}
			}

			// 显示最终结果
			if (uploadedCount > 0) {
				this.$message.success(`成功上传 ${uploadedCount} 个文件`);
			}

			if (failedFiles.length > 0) {
				this.$message.error(`${failedFiles.length} 个文件上传失败`);
				console.error("失败的文件:", failedFiles);
			}
		},
	},
};
</script>

<style scoped>
.intPage {
	display: flex;
	flex-direction: column;
	gap: 15px;
	padding: 20px 10%;
	box-sizing: border-box;
	width: 100%;
	height: 100%;
	overflow: auto;
	background: #fff;
	border-radius: 8px;
}
.tit {
	font-size: 25px;
	font-weight: 600;
	text-align: center;
}
.editer {
	width: 100%;
}
.editer >>> .ql-align-center {
	text-align: center !important;
}
.editer >>> .ql-editor {
	height: 300px;
}
/* .editer >>> .el-picker-panel__icon-btn {
  button {
    padding: 10px 20px !important;
  }
} */
.avatar-uploader {
	opacity: 0;
	height: 0;
	margin: 0 20px;
}
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}
.addEditor >>> .text {
  height: auto;
  min-height: 200px;
}

.addEditor >>> .w-e-text-container {
  min-height: 100px;
}
</style>
