<template>
	<!-- 禁止滚动穿透 -->
	<page-meta :page-style="'overflow:'+(show?'hidden':'visible')"></page-meta>
	<view class="main">
		<view class="one">
			<view class="one_1">
				<input type="text" v-model="searchInfo.title" @input="toInput" placeholder="搜索标题">
			</view>
			<view class="one_2">
				<button size="mini" class="button" type="primary" @click="toAdd">添加</button>
			</view>
		</view>
		<view class="two">
			<scroll-view scroll-y="true" class="scroll-view" @scrolltolower="toPage" @scroll="toScroll">
				<view class="list-scroll-view">
					<view class="list" v-for="(item, index) in list" :key="index">
						<view class="name">{{item.title||'暂无标题'}}</view>
						<view class="other textOver">
							来源：{{item.origin||'暂无'}}
						</view>
						<view class="other textOver">
							创建时间：{{item.create_time||'暂无'}}
						</view>
						<view class="other textOver">
							是否启用：{{item.is_use == '0' ? '是' : '否'}}
						</view>
						<view class="button">
							<button class="warning" size="mini" type="warn" @tap.stop="toEdit(item)">修改</button>
							<button class="danger" size="mini" type="warn" @tap.stop="toDel(item)">删除</button>
						</view>
					</view>
				</view>
				<view class="is_bottom" v-if="is_bottom">
					<text>{{config.bottom_title||'到底了！'}}</text>
				</view>
			</scroll-view>
		</view>
		<!-- 修改/添加信息 -->
		<uni-popup ref="popup" background-color="#fff" type="center" :is-mask-click="false" @change="change">
			<view class="popup">
				<view class="close">
					<text>信息管理</text>
					<uni-icons @tap="toClose" type="close" size="20"></uni-icons>
				</view>
				<view class="info">
					<scroll-view class="scroll-view" scroll-y="true">
						<view class="list-scroll-view">
							<view class="info_1">
								<uni-forms ref="valiForm" :rules="rules" :modelValue="form" label-width="85">
									<uni-forms-item label="标题" required name="title">
										<uni-easyinput v-model="form.title" placeholder="请输入标题" />
									</uni-forms-item>
									<uni-forms-item label="来源" required name="origin">
										<uni-easyinput v-model="form.origin" placeholder="请输入来源" />
									</uni-forms-item>
									<uni-forms-item label="封面图片" required name="img_url">
										<upload class='upload' :list="form.img_url" name="img_url" :count="1"
											@uplSuc="uplSuc" @uplDel="uplDel">
										</upload>
									</uni-forms-item>
									<uni-forms-item label="内容" required name="content">
										<editor style="width: 100%; padding: 10upx;" id="editor"
											:placeholder="placeholder" @input="editorChange" @ready="onEditorReady">
										</editor>
									</uni-forms-item>
									<uni-forms-item label="是否启用" name="is_use">
										<uni-data-select v-model="form.is_use" :localdata="is_useList"
											@change="is_usechange">
										</uni-data-select>
									</uni-forms-item>
								</uni-forms>
								<button class="button" size="mini" type="primary"
									@click="submit('valiForm')">保存</button>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import upload from '../../components/upload/index.vue';
	export default {
		components: {
			upload
		},
		data() {
			return {
				user: {},
				config: {},
				searchInfo: {},
				list: [],
				total: 0,
				skip: 0,
				limit: 10,
				page: 0,
				form: {
					img_url: []
				},
				// 校验规则
				rules: {
					title: {
						rules: [{
							required: true,
							errorMessage: '标题不能为空'
						}]
					},
					origin: {
						rules: [{
							required: true,
							errorMessage: '来源不能为空'
						}]
					},
					img_url: {
						rules: [{
							required: true,
							errorMessage: '请上传封面图片'
						}]
					},
				},
				is_useList: [{
						text: '是',
						value: '0'
					},
					{
						text: '否',
						value: '1'
					}
				],
				placeholder: '请输入内容',
				content: '',
				// 数据是否触底
				is_bottom: false,
				scrollTop: 0,
				// 禁止滚动穿透
				show: false
			}
		},
		onShow: async function() {
			const that = this;
			that.clearPage();
			await that.searchToken();
			await that.searchConfig();
			await that.search();
		},
		onPullDownRefresh: async function() {
			const that = this;
			that.clearPage();
			await that.search();
			uni.stopPullDownRefresh();
		},
		methods: {
			// 禁止滚动穿透
			change(e) {
				const that = this;
				that.show = e.show
			},
			searchToken() {
				const that = this;
				try {
					const res = uni.getStorageSync('token');
					if (res) {
						const user = that.$jwt(res);
						that.$set(that, `user`, user);
					}
				} catch (e) {}
			},
			searchConfig() {
				const that = this;
				try {
					const res = uni.getStorageSync('config');
					if (res) that.$set(that, `config`, res);
				} catch (e) {}
			},
			async search() {
				const that = this;
				let user = that.user;
				let info = {
					skip: that.skip,
					limit: that.limit,
				}
				if (that.user.role == 'Doctor') info.doctor = that.user._id
				else info.doctor = that.user.doctor
				const res = await that.$api(`/article`, 'GET', {
					...info,
					...that.searchInfo
				})
				if (res.errcode == '0') {
					let list = [...that.list, ...res.data];
					that.$set(that, `list`, list)
					that.$set(that, `total`, res.total)
				} else {
					uni.showToast({
						title: res.errmsg,
					});
				}
			},
			// 输入框
			toInput(e) {
				const that = this;
				if (that.searchInfo.title) that.$set(that.searchInfo, `title`, e.detail.value)
				else that.$set(that, `searchInfo`, {})
				that.clearPage();
				that.search();
			},
			// 是否使用
			is_usechange(is_use) {
				const that = this;
				that.$set(that.form, `is_use`, is_use);
			},
			// 富文本
			onEditorReady() {
				const that = this
				uni.createSelectorQuery().select('#editor').context((res) => {
					that.editorCtx = res.context
					that.editorCtx.setContents({
						html: that.form.content || '',
						success: (res) => {
							// console.log(res)
						},
						fail: (res) => {
							// console.log(res)
						},
					})
				}).exec()
			},
			editorChange: function(e) {
				const that = this
				that.$set(that, `content`, e.detail.html || '')
			},
			// 图片上传
			uplSuc(e) {
				const that = this;
				that.$set(that.form, `${e.name}`, [...that.form[e.name], e.data]);
			},
			// 图片删除
			uplDel(e) {
				const that = this;
				let data = that.form[e.name];
				let arr = data.filter((i, index) => index != e.data.index);
				that.$set(that.form, `${e.name}`, arr)
			},
			// 添加
			toAdd() {
				const that = this;
				that.$refs.popup.open()
			},
			// 修改
			async toEdit(item) {
				const that = this;
				const res = await that.$api(`/article/${item._id}`, 'GET', {})
				if (res.errcode == '0') {
					that.$set(that, `form`, res.data)
					that.onEditorReady()
					that.$refs.popup.open()
				} else {
					uni.showToast({
						title: res.errmsg,
						icon: 'none'
					});
				}
			},
			// 保存
			submit(ref) {
				const that = this;
				const form = that.form;
				that.$refs[ref].validate().then(async data => {
					let res;
					if (that.user.role == 'Doctor') data.doctor = that.user._id
					else data.doctor = that.user.doctor
					data.content = that.content
					data.create_time = that.getNowDate()
					if (form._id) res = await that.$api(`/article/${form._id}`, 'POST', data)
					else res = await that.$api(`/article`, 'POST', data)
					if (res.errcode == '0') {
						uni.showToast({
							title: '维护信息成功',
							icon: 'none'
						})
						that.toClose();
						that.clearPage();
						that.search();
					} else {
						uni.showToast({
							title: res.errmsg,
							icon: 'none'
						});
					}
				})
			},
			// 删除
			async toDel(item) {
				const that = this;
				uni.showModal({
					title: '提示',
					content: '您确定删除该数据吗?',
					success: async function(res) {
						if (res.confirm) {
							const res = await that.$api(`/article/${item._id||item.id}`, 'DELETE', {})
							if (res.errcode == 0) {
								that.clearPage();
								that.search();
							} else {
								uni.showToast({
									title: res.errmsg,
									icon: 'none'
								})
							}
						}
					}
				});
			},
			// 关闭弹框
			toClose() {
				const that = this;
				that.$set(that, `form`, {})
				that.onEditorReady()
				that.$refs.popup.close();
			},
			// 分页
			toPage(e) {
				const that = this;
				let list = that.list;
				let limit = that.limit;
				if (that.total > list.length) {
					uni.showLoading({
						title: '加载中',
						mask: true
					})
					let page = that.page + 1;
					that.$set(that, `page`, page)
					let skip = page * limit;
					that.$set(that, `skip`, skip)
					that.search();
					uni.hideLoading();
				} else that.$set(that, `is_bottom`, true)
			},
			toScroll(e) {
				const that = this;
				let up = that.scrollTop;
				that.$set(that, `scrollTop`, e.detail.scrollTop);
				let num = Math.sign(up - e.detail.scrollTop);
				if (num == 1) that.$set(that, `is_bottom`, false);
			},
			// 清空列表
			clearPage() {
				const that = this;
				that.$set(that, `list`, [])
				that.$set(that, `skip`, 0)
				that.$set(that, `limit`, 10)
				that.$set(that, `page`, 0)
			},
			// 格式化日对象
			getNowDate() {
				var date = new Date();
				var sign2 = ":";
				var year = date.getFullYear() // 年
				var month = date.getMonth() + 1; // 月
				var day = date.getDate(); // 日
				var hour = date.getHours(); // 时
				var minutes = date.getMinutes(); // 分
				var seconds = date.getSeconds() //秒
				var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
				var week = weekArr[date.getDay()];
				// 给一位数的数据前面加 “0”
				if (month >= 1 && month <= 9) {
					month = "0" + month;
				}
				if (day >= 0 && day <= 9) {
					day = "0" + day;
				}
				if (hour >= 0 && hour <= 9) {
					hour = "0" + hour;
				}
				if (minutes >= 0 && minutes <= 9) {
					minutes = "0" + minutes;
				}
				if (seconds >= 0 && seconds <= 9) {
					seconds = "0" + seconds;
				}
				return year + "-" + month + "-" + day + " " + hour + sign2 + minutes + sign2 + seconds;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		display: flex;
		flex-direction: column;
		width: 100vw;
		height: 100vh;

		.one {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 2vw;

			.one_1 {
				padding: 0 2vw;
				width: 75vw;

				input {
					padding: 2vw;
					background-color: var(--f1Color);
					font-size: var(--font14Size);
					border-radius: 5px;
				}
			}

			.one_2 {
				padding: 2vw 0;

				.button {
					background-color: var(--f3CColor);
					color: var(--mainColor);
				}
			}
		}

		.two {
			position: relative;
			flex-grow: 1;
			background-color: var(--f9Color);

			.list:first-child {
				margin: 2vw;
			}

			.list {
				background-color: var(--mainColor);
				border: 1px solid var(--f5Color);
				padding: 2vw;
				margin: 0 2vw 2vw 2vw;
				border-radius: 5px;

				.name {
					font-size: var(--font14Size);
					font-weight: bold;
					padding: 2vw 0;
				}

				.other {
					font-size: var(--font12Size);
					color: var(--f85Color);
				}


				.button {
					margin: 2vw 0 0 0;
					text-align: center;

					.warning {
						background: var(--f3CColor);
					}

					.danger {
						background: var(--fF0Color);
					}

					button {
						margin: 0 1vw 0 0;
					}
				}
			}
		}

		.uni-popup {
			z-index: 9999 !important;
		}

		.popup {
			display: flex;
			flex-direction: column;
			width: 90vw;
			background-color: var(--f9Color);

			.close {
				display: flex;
				justify-content: space-between;
				padding: 2vw;

				text:first-child {
					font-size: var(--font16Size);
					font-weight: bold;
				}
			}

			.info {
				position: relative;
				height: 40vh;

				.info_1 {
					display: flex;
					flex-direction: column;
					align-items: center;
					padding: 2vw;

					#editor {
						width: 100%;
						height: 100px;
						border: 1px solid #F0F0F0;
					}

					.button {
						margin: 2vw 0 0 0;
						background-color: var(--f3CColor);
						color: var(--mainColor);
						font-size: var(--font14Size);
					}
				}
			}
		}
	}

	.scroll-view {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;

		.list-scroll-view {
			display: flex;
			flex-direction: column;
		}
	}

	.is_bottom {
		width: 100%;
		text-align: center;

		text {
			padding: 2vw 0;
			display: inline-block;
			color: var(--f85Color);
			font-size: var(--font14Size);
		}
	}
</style>