<template>
	<view class="add">
		<view class="share flexB">
			<view class="share_title">
				<text>第{{ params.season ? params.season : userInfo.season }}届大卫博士创业</text>
				<text v-if="type">{{ type == 1 ? '密训营' : '实战营' }}</text>
				<text v-else>{{ userInfo.season_type == 1 ? '密训营' : '实战营' }}</text>
			</view>
			<view class="flexS">
				<image src="../../static/imgs/color.png" @click="changeColor"></image>
				<view class="share_btn" @click="shareBtn">分享</view>
			</view>
			<view class="note_color" v-if="showColor">
				<image src="../../static/imgs/color_bg.png"></image>
				<view class="color_change">
					<view class="color_intr">
						<text>便签颜色</text>
						<text style="font-size:20rpx;color:#999;">（重要程度）</text>
					</view>
					<view class="colors">
						<view @click="choose(0)"><image :src="params.level == 0 ? '../../static/imgs/red_active.png' : '../../static/imgs/red.png'"></image></view>
						<view @click="choose(1)"><image :src="params.level == 1 ? '../../static/imgs/blue_active.png' : '../../static/imgs/blue.png'"></image></view>
						<view @click="choose(2)"><image :src="params.level == 2 ? '../../static/imgs/green_active.png' : '../../static/imgs/green.png'"></image></view>
					</view>
				</view>
			</view>
		</view>
		<view class="edit_note">
			<input type="text" placeholder="请输入便签标题(点击编辑)" placeholder-style="font-size:36rpx;font-weight:bold;color:#333;" v-model="params.title" maxlength="16" />
			<view class="icon" @click="format">
				<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold"></view>
				<view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic"></view>
				<view :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian" data-name="underline"></view>
				<view :class="formats.align === 'left' ? 'ql-active' : ''" class="iconfont icon-zuoduiqi" data-name="align" data-value="left"></view>
				<view :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi" data-name="align" data-value="center"></view>
				<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi" data-name="align" data-value="right"></view>
				<view :class="formats.align === 'justify' ? 'ql-active' : ''" class="iconfont icon-zuoyouduiqi" data-name="align" data-value="justify"></view>
			</view>
			<editor id="editor" class="ql-container" placeholder="此时此刻你想写点什么呢..." @ready="onEditorReady" @input="getText" @statuschange="onStatusChange"></editor>
		</view>
		<view class="add_btn" @click.stop="showBtn = !showBtn">
			<view class="add_btn_active" v-if="showBtn == true">
				<image src="../../static/imgs/add__btn_active.png" class="active_btn"></image>
				<view class="opera flexCC"><image src="../../static/imgs/add_img.png" style="margin-top:15rpx;" @click="insertImage"></image></view>
			</view>
			<image src="../../static/imgs/add.png" v-else></image>
		</view>
		<view class="bottom">
			<view class="flexCC" @click="skipNote(0)">保存</view>
			<view class="flexCC" @click="skipNote(1)">发布</view>
		</view>
		<view class="long_img flexCC" v-if="showImg">
			<view class="flexCC">
				<view class="img_box">
					<text class="iconfont iconguanbi" @click="showImg = false"></text>
					<image :src="longImage" @click="imgPreview" mode="aspectFit"></image>
				</view>
				<view class="img_btn" @click="saveImg">保存图片</view>
			</view>
		</view>
	</view>
</template>

<script>
import { upLoad, addNote, showNote, getLongImg } from '../../api/note.js';
import request from '../../utiils/request.js';
import { base64src } from '../../utiils/base64src.js';
export default {
	data() {
		return {
			formats: {}, //editor样式
			showBtn: false,
			showColor: false, //显示便签颜色
			showImg: false, //是否显示长图
			type: '', //实战营还是实训营
			userInfo: '', //用户信息
			params: {
				id: '', //便签id
				title: '', //便签标题
				content: '', //便签内容带标签
				level: 0, //便签重要程度
				cover_url: '', //封面图片
				summary: '', //便签简介
				body: '' //便签内容纯文本
			},
			longImage: '' //保存的长图
		};
	},
	onLoad(options) {
		if (options.id) {
			this.params.id = options.id;
			this.type = options.type;
		}
	},
	onShow() {
		this.userInfo = uni.getStorageSync('userInfo');
	},
	methods: {
		//点击长图放大
		imgPreview() {
			uni.previewImage({
				cur: this.longImage,
				urls: [this.longImage]
			});
		},
		//保存图片按钮
		saveImg() {
			uni.saveImageToPhotosAlbum({
				filePath: this.longImage,
				success: res => {
					uni.showModal({
						content: '保存图片成功',
						showCancel: false
					});
					this.showImg = false;
				},
				fail: err => {
					if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
						uni.showModal({
							title: '提示',
							content: '您好,请先授权，再保存此图片。',
							showCancel: false,
							success: res => {
								if (res.confirm) {
									uni.openSetting({
										success: res => {
											console.log(res);
											if (res.authSetting['scope.writePhotosAlbum']) {
												uni.showModal({
													content: '请重新长按保存图片',
													showCancel: false
												});
											} else {
												uni.showModal({
													content: '您拒绝了保存到相册权限',
													showCancel: false
												});
											}
										},
										fail: err => {
											uni.showModal({
												content: '手动打开相册权限失败',
												showCancel: false
											});
										}
									});
								}
							}
						});
					}
				},
				complete() {
					uni.hideLoading();
				}
			});
		},
		// 修改便签样式
		format(e) {
			let { name, value } = e.target.dataset;
			if (!name) return;
			this.editorCtx.format(name, value);
		},
		onStatusChange(e) {
			const formats = e.detail;
			this.formats = formats;
		},
		/*
		 * 初始化编辑器 如果有内容回显，没有内容显示为空
		 */
		onEditorReady() {
			let that = this;
			uni.createSelectorQuery()
				.select('#editor')
				.context(res => {
					console.log(res.context);
					this.editorCtx = res.context;
					if (!res) return;
					//便签列表进来回显
					if (this.params.id) {
						showNote({ id: this.params.id }).then(res => {
							if (res.code == 200) {
								this.params = res.data;
								this.editorCtx.setContents({
									html: res.data.content,
									success: res => {
										console.log('渲染成功');
									},
									fail: res => {
										console.log('渲染失败');
									}
								});
							} else {
								uni.showModal({
									content: res.message || '获取内容失败',
									showCancel: false
								});
							}
						});
					}
				})
				.exec();
		},
		toJSON() {},
		/*
		 * 获取编辑器内容输入的内容
		 */
		getText(e) {
			let ops = e.target.delta.ops;
			let img = ops.map(i => {
				if (i.insert.image) {
					return i.insert.image;
				}
			});
			let img1 = img.filter(i => {
				return i != undefined;
			});
			this.params.cover_url = img1[0] ? img1[0] : '';
			this.params.summary = e.detail.text.substring(0, 40) + '...';
			this.params.content = e.detail.html;
			this.params.body = e.detail.text;
		},
		//打开标签选择页面
		changeColor() {
			this.showColor = !this.showColor;
		},
		//选择标签颜色
		choose(tabType) {
			this.params.level = tabType;
			this.showColor = false;
		},

		/*
		 * 新建、修改标签
		 * @params id 当修改是带着id，添加时不带
		 * @params title 便签标题
		 * @params content 便签内容
		 * @params level 便签重要级
		 * @params cover_url 封面
		 * @params summary 便签简介
		 * @params status 便签状态
		 * desc isShare 是否点击了分享按钮
		 */
		skipNote(type, isShare) {
			if (!this.params.title) {
				uni.showModal({
					content: '便签标题不能为空!',
					showCancel: false
				});
				return false;
			}
			//type 0 保存  type 1 发布
			if (type == 1 && !this.userInfo.sign_type) {
				//只有报名本赛季的才可以发布便签
				uni.showModal({
					content: '您本赛季暂未报名',
					showCancel: false
				});
				return false;
			}
			let data = {};
			let { id, title, content, level, cover_url, summary, body } = this.params;
			if (this.params.id) {
				data = {
					id,
					title,
					content,
					level,
					cover_url,
					summary,
					status: type,
					body
				};
			} else {
				data = {
					title,
					content,
					level,
					cover_url,
					summary,
					status: type,
					body
				};
			}
			addNote(data).then(res => {
				if (res.code == 200) {
					if (isShare == true) {
						uni.showLoading({
							title: '生成图片中....'
						});
						uni.request({
							url: 'http://192.168.0.6:8030/api' + '/note/note_share',
							method: 'get',
							data: { id: this.params.id },
							header: {
								'content-type': 'application/x-www-form-urlencoded',
								Authorization: 'bearer' + ' ' + uni.getStorageSync('token')
							},
							responseType: 'arraybuffer',
							success: res => {
								let url = 'data:image/png;base64,' + wx.arrayBufferToBase64(res.data);
								base64src(url, res => {
									this.longImage = res;
								});
								this.showImg = true;
								uni.hideLoading();
							},
							fail: err => {
								uni.showToast({
									title: '生成图片失败',
									showCancel: false
								});
							}
						});
					} else {
						uni.showModal({
							content: type == 0 ? '保存成功' : '发布成功',
							showCancel: false,
							success: res => {
								if (res.confirm) {
									if (type == 0) {
										uni.redirectTo({
											url: '../note_pad/note_pad?curTab=' + 0
										});
									} else {
										uni.redirectTo({
											url: '../note_pad/note_pad?curTab=' + 1
										});
									}
								}
							}
						});
					}
				} else {
					uni.showModal({
						content: res.message || '添加失败',
						showCancel: false
					});
				}
			});
		},
		//点击分享生成图片
		shareBtn() {
			let that = this;
			if (!that.params.id) {
				uni.showModal({
					content: '保存或发布之后才能分享',
					showCancel: false
				});
				return false;
			}
			let type = that.params.status.toString();
			if (type) {
				that.skipNote(Number(type), true);
			}
		},
		//插入图片（一次只能插入一张）
		insertImage() {
			const that = this;
			wx.chooseImage({
				count: 1,
				success: res => {
					uni.showLoading({
						title: '图片上传中...'
					});
					uni.uploadFile({
						url: 'http://192.168.0.6:8030/api' + '/note/upload_img',
						filePath: res.tempFilePaths[0],
						name: 'img',
						formData: '',
						header: {
							'content-type': 'application/x-www-form-urlencoded',
							Authorization: 'bearer' + ' ' + uni.getStorageSync('token')
						},
						success: res => {
							uni.hideLoading();
							var data = JSON.parse(res.data);
							that.editorCtx.insertImage({
								src: data.data.img,
								data: {
									id: 'abcd',
									role: 'god'
								},
								width: '100%',
								extClass: 'center',
								success: res => {
									console.log('insert image success');
								}
							});
						},
						fail: err => {
							uni.showModal({
								content: res.message,
								showCancel: false
							});
						}
					});
				}
			});
		}
	}
};
</script>

<style lang="scss">
.long_img {
	position: fixed;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 999;
	width: 100vw;
	height: 100vh;
	background-color: rgba(0, 0, 0, 0.8);
	> view {
		width: 650rpx;
		margin: 0 auto;
		.img_box {
			width: 650rpx;
			height: 1000rpx;
			border-radius: 24rpx;
			margin-bottom: 40rpx;
			.iconfont {
				font-size: 54rpx;
				color: #999;
				position: fixed;
				right: 76rpx;
				top: 5rpx;
			}
			image {
				width: 100%;
				height: 100%;
				border-radius: 24rpx;
			}
		}
		.img_btn {
			width: 256rpx;
			text-align: center;
			height: 88rpx;
			line-height: 88rpx;
			background: linear-gradient(93deg, #f97c55 0%, #f44545 100%);
			opacity: 1;
			border-radius: 44rpx;
			color: #fff;
		}
	}
}
.ql-active {
	color: #06c;
}
button {
	margin-top: 10px;
}
.current {
	font-size: 36rpx;
	font-weight: bold;
	color: #fff;
	image {
		width: 50rpx;
		height: 50rpx;
		vertical-align: -13rpx;
	}
}
.add {
	width: 100%;
	height: 100%;
	position: relative;
}
.share {
	width: 100%;
	height: 88rpx;
	padding: 0 30rpx;
	box-sizing: border-box;
	background-color: #f44545;
	color: #fff;
	position: relative;
	image {
		width: 45rpx;
		height: 39rpx;
		margin-right: 15rpx;
	}
	.share_title {
		font-size: 28rpx;
		color: #fff;
	}
	.share_btn {
		width: 92rpx;
		text-align: center;
		height: 46rpx;
		line-height: 46rpx;
		background: #fff;
		border-radius: 8rpx;
		font-size: 28rpx;
		color: #f44545;
	}
	.note_color {
		position: fixed;
		top: 83rpx;
		right: 100rpx;
		z-index: 9999;
		image {
			width: 292rpx;
			height: 166rpx;
		}
		.color_change {
			position: absolute;
			top: 51rpx;
			left: 33rpx;
			width: 80%;
			.color_intr {
				font-size: 28rpx;
				color: #333;
			}
			.colors {
				display: flex;
				justify-content: space-around;
				align-items: center;
				margin-top: 17rpx;
				image {
					width: 32rpx;
					height: 32rpx;
				}
			}
		}
	}
}
.edit_note {
	.icon {
		width: 100%;
		display: flex;
		justify-content: space-around;
		align-items: center;
		margin: 20rpx 0;
		.iconfont {
			font-size: 40rpx;
		}
	}
	input {
		width: 100%;
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		padding: 15rpx 0;
	}
	#editor {
		width: 90%;
		margin: 0 auto;
		height: 70vh;
		font-size: 28rpx;
		line-height: 1.5;
	}
}
.add_btn {
	position: absolute;
	bottom: 15vh;
	left: 75%;
	image {
		width: 150rpx;
		height: 150rpx;
	}
}
.add_btn_active {
	width: 148rpx;
	height: 254rpx;
	.active_btn {
		width: 100%;
		height: 100%;
	}
	.opera {
		position: absolute;
		top: -103rpx;
		left: 38rpx;
		height: 342rpx;
		image {
			width: 72rpx;
			height: 72rpx;
		}
	}
}
.bottom {
	width: 100%;
	height: 88rpx;
	display: flex;
	align-items: center;
	background: #f44545;
	position: fixed;
	bottom: 0;
	left: 0;
	view:first-child {
		border-right: 1rpx solid #fff;
	}
	view {
		height: 100%;
		width: 50%;
		color: #fff;
		font-size: 28rpx;
	}
}
// .long_img {
// 	position: fixed;
// 	width: 100%;
// 	// height: 100%;
// 	top: 0;
// 	left: 0;
// 	background: rgba(0, 0, 0, 0.6);
// }
</style>
