<template>
	<el-dialog title="添加公告" :visible.sync="visible_" :close-on-click-modal="false" :before-close="close_before" append-to-body width="640px" top="5%">
		<el-form ref="dialogData" label-width="100px" class="form">
			<el-form-item label="公告标题" :rules="[{ required: true, message: '请输入公告标题', trigger: 'blur' }]">
				<el-input type="text" v-model="params.name" placeholder="请输入公告标题" maxlength="30" show-word-limit></el-input>
			</el-form-item>
			<div style="border: 1px solid #ccc;margin-bottom: 20px;" v-if="visible_">
				<!-- 工具栏 -->
				<Toolbar style="border-bottom: 1px solid #ccc" :editorId="editorId" :defaultConfig="toolbarConfig"/>
				<!-- 编辑器 -->
				<Editor style="height: 300px" :editorId="editorId" :defaultConfig="editorConfig" :defaultContent="getDefaultContent" @onChange="onChange" />
			</div>
			<el-form-item label="图片">
				<uploadOss
					:headers="Xtoken"
					:action="'https://' + 'integralsys.oss-cn-shenzhen.aliyuncs.com'"
					:show-file-list="true"
					:file-list="img_fileList"
					:on-success="handleFilesSuccess"
					:on-preview="onFilePreView"
					:before-upload="beforeUpload"
					accept="image/jpeg,image/png"
					:on-remove="onFileRemove"
					:limit="1"
					:multiple="true"
				>
					<el-button type="primary" size="small">点击上传</el-button>
					(最多选择1张)
				</uploadOss>
			</el-form-item>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="close">取 消</el-button>
			<el-button type="primary" @click="confirm">确 定</el-button>
		</span>
	</el-dialog>
</template>

<script>
import uploadOss from '@/components/upload';
import { Editor, Toolbar, getEditor, removeEditor, createEditor } from '@wangeditor/editor-for-vue';
import cloneDeep from 'lodash.clonedeep';
import { getToken } from '@/api/auth';
export default {
	name: 'Suggest',
	components: { uploadOss, Editor, Toolbar },
	props: {
		isAdd: {
			type: Boolean,
			default: true
		},
		visible: {
			// 是否显示组件
			type: Boolean,
			default: false
		},
		detaliData:{
			type: Object,
			default:()=>{
				return {}
			}
		}
	},
	data() {
		return {
			Xtoken: { 'X-Token': getToken() },
			visible_: false,
			// 建议
			img_fileList: [], // 图片附件
			save_loading: false,
			params: {
				name: '',
				html: '',
				content: '',
				file_list: [],
				// tag: ['福利']
			},

			// 富文本
			editorId: 'wangEditor-1', // 定义一个编辑器 id ，要求：全局唯一且不变。重要！！！
			defaultContent: [], // 编辑器的默认内容，只在初始化时使用
			latestContent: [], // 用于存储编辑器最新的内容，onChange 时修改
			toolbarConfig: {
				mode: 'simple',
				toolbarKeys: [
					'headerSelect', // 分割线
					'|',
					'bold',
					'italic',
					'underline',
					'through',
					'color',
					'bgColor',
					'indent',
					'justifyLeft',
					'justifyRight',
					'justifyCenter',
					'justifyJustify',
					'bulletedList',
					'numberedList',
					'clearStyle'
				]
			},
			editorConfig: {
				placeholder: '请输入内容...'
			}
		};
	},
	computed: {
		// <!-- 注意，这里使用 computed 的结果 -->
		getDefaultContent() {
			return cloneDeep(this.defaultContent); // 深拷贝，重要！！！
		}
	},
	watch: {
		visible(val) {
			if(!this.isAdd&&val){
				let detaliData=this.detaliData;
				if(detaliData.content.content){
					this.defaultContent=JSON.parse(detaliData.content.content);
					if(detaliData.file_list){
						this.img_fileList=[{name:'图片',url:detaliData.file_list}]
						this.params.file_list=[detaliData.file_list]
					}
					
				}
				this.params.name=detaliData.name
			}
			this.visible_ = JSON.parse(JSON.stringify(val));
		}
	},
	methods: {
		onChange(editor) {
			this.params.content = editor.children;
			this.params.html = editor.getHtml();
		},
		// 图片上传
		beforeUpload(file) {
			const isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
			const isLt2M = file.size / 1024 / 1024 < 5;
			if (!isJPG) {
				this.$message.error('上传图片只能是 jpeg|png|jpg 格式!');
			}
			if (!isLt2M) {
				this.$message.error('上传图片大小不能超过 5MB!');
			}
			return isJPG && isLt2M;
		},
		onFilePreView(file) {
			window.open(file.url, '_blank');
		},
		onFileRemove(file, fileList) {
			this.img_fileList = fileList;
			let imgs = [];
			fileList.forEach((element, index) => {
				imgs.push(element.url);
			});
			this.params.file_list = imgs;
		},
		handleFilesSuccess(response, file, fileList) {
			let fileListData=fileList.filter(e=>{
			  return e.url
			})
			this.img_fileList = fileListData;
			let imgs = [];
			fileListData.forEach((element, index) => {
				imgs.push(element.url);
			});
			this.params.file_list = imgs;
		},

		// 确定
		confirm() {
			if (!this.params.name) {
				this.$message.error('请填写标题');
				return false;
			}
			this.params.content=JSON.stringify(this.params.content)
			if(!this.isAdd){
				this.params.id=this.detaliData.id;
				this.$axios('post','/api/information/update',this.params).then(res => {
						this.$message.success('发布成功');
						this.$parent.noticeList();
						this.close();
				})
			}else{
				this.$axios('post','/api/information/create',this.params).then(res => {
						this.$message.success('发布成功');
						this.$parent.noticeList();
						this.close();
				})
			}
		},
		close_before(done) {
			this.close();
			done();
		},
		close() {
			this.img_fileList=[];
			this.defaultContent=[];
			this.params={
				name: '',
				html: '',
				content: '',
				file_list: [],
			};
			this.beforeDestroys();
			this.$emit('update:visible', false);
		},
		beforeDestroys() {
			const editor = getEditor(this.editorId);
			if (editor == null) return;
			editor.destroy(); // 组件销毁时，及时销毁编辑器 ，重要！！！
			removeEditor(this.editorId);
		}
	},
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped="scoped" lang="scss">
/* 表格 */
table {
	border-collapse: collapse;
}
table th,
table td {
	border: 1px solid #ccc;
	min-width: 50px;
	height: 20px;
	text-align: left;
}
table th {
	background-color: #f1f1f1;
	text-align: center;
}

/* 代码块 */
pre > code {
	display: block;
	border: 1px solid hsl(0, 0%, 91%);
	border-radius: 4px 4px;
	text-indent: 0;
	background-color: #fafafa;
	padding: 10px;
	font-size: 14px;
}

/* 引用 */
blockquote {
	display: block;
	border-left: 8px solid #d0e5f2;
	padding: 10px 10px;
	margin: 10px 0;
	background-color: #f1f1f1;
}

/* 列表 */
ul,
ol {
	margin: 10px 0 10px 20px;
}

/* 分割线 */
hr {
	display: block;
	width: 90%;
	margin: 20px auto;
	border: 0;
	height: 1px;
	background-color: #ccc;
}
</style>
