<template>
	<div custom-class="bbsl-location-dialog">
		<el-dialog :title="title" :visible.sync="showFormDia" width="85%" :close-on-click-modal="false" top="5vh"
			:before-close="handleClose">
			<el-form ref="formInfo" :rules="rules" :model="params" label-width="150px">
				<el-row>
					<el-col :span="8">
						<el-form-item label="所属类型:" prop="type">
							<el-select style="width: 100%" size="mini" v-model="params.type" clearable
								placeholder="请选择所属类型">
								<el-option v-for="item in classifyNames" :key="item.value" :label="item.name"
									:value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="标题:" prop="title">
							<el-input size="mini" clearable placeholder="请输入标题" v-model="params.title">
							</el-input>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="拟稿人:" prop="drafter">
							<el-input size="mini" clearable placeholder="请输入拟稿人" v-model="params.drafter">
							</el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="摘要:" prop="titleDescription">
							<el-input size="mini" type="textarea" :rows="2" clearable placeholder="请输入摘要"
								v-model="params.titleDescription">
							</el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item label="是否外部链接:" prop="isUrl">
							<el-radio-group v-model="params.isUrl">
								<el-radio :label="true">是</el-radio>
								<el-radio :label="false">否</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="创建时间:" prop="createTime">
							<el-date-picker v-model="params.createTime" type="datetime"
								value-format="yyyy-MM-dd HH:mm:ss" size="mini" placeholder="选择日期">
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="过期时间:" prop="endTime">
							<el-date-picker v-model="params.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
								size="mini" placeholder="选择日期">
							</el-date-picker>
						</el-form-item>
					</el-col>

				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item label="外部URL:" v-if="params.isUrl" prop="url">
							<el-input size="mini" clearable placeholder="请输入外部URL" v-model="params.url">
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" v-if="params.type == '2'">
						<el-form-item label="轮播展示图片:" prop="rotatingDisplayPictures">
							<el-upload name="files" class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
								:headers="header" :data="{bizCode: 'newAccessory', bizId: '',bizType:''}"
								:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
								<img v-if="params.rotatingDisplayPictures" :src="this.rotatingDisplayPictures"
									class="avatar" />
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="附件:" prop="file">
							<el-upload name="files" :action="uploadUrl" :on-success="uploadSuccess"
								:before-upload="beforeUpload" :headers="header"
								:data="{bizCode: 'newAccessory', bizId: '',bizType:''}" :accept="accept"
								:file-list="fileList">
								<el-button size="mini" icon="el-icon-upload" type="success">上传</el-button>
							</el-upload>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24" v-show="!this.params.isUrl">
						<el-form-item label="内容:" prop="content">
							<div class="quill-editor">
								<!-- 图片上传组件辅助-->
								<el-upload name="img" class="avatar-qeuploader" :action="uploadUrl"
									:show-file-list="false" :on-success="qeuploadSuccess" :before-upload="beforeUpload"
									:headers="header" :accept="acceptImg"></el-upload>
								<!--富文本编辑器组件-->
								<quill-editor v-model="params.content" :content="params.content" :options="editorOption"
									@blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
									@ready="onEditorReady($event)" @change="onEditorChange" ref="QuillEditor">
								</quill-editor>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="goInfo">保 存</el-button>
				<el-button @click="handleClose">取 消</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import req from '@/request.js'
	import latitude from '@/mixins/latitude'
	import moment from 'moment';
	import dictUtils from '@/components/dict/DictSelectUtils.js'
	// import flashFloods from '@/api/flashFloods.js'
	import newsRelease from '@/api/newsRelease.js'
	import iconDialog from './iconDialog.vue'
	import 'quill/dist/quill.core.css'
	import 'quill/dist/quill.snow.css'
	import 'quill/dist/quill.bubble.css'
	import {
		quillEditor
	} from 'vue-quill-editor'
	const toolbarOptions = [
		['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
		['blockquote', 'code-block'], //引用，代码块
		[{
				header: 1
			},
			{
				header: 2
			}
		], // 几级标题
		[{
				list: 'ordered'
			},
			{
				list: 'bullet'
			}
		], // 有序列表，无序列表
		[{
				script: 'sub'
			},
			{
				script: 'super'
			}
		], // 下角标，上角标
		[{
				indent: '-1'
			},
			{
				indent: '+1'
			}
		], // 缩进
		[{
			direction: 'rtl'
		}], // 文字输入方向
		[{
			size: ['small', false, 'large', 'huge']
		}], // 字体大小
		[{
			header: [1, 2, 3, 4, 5, 6, false]
		}], // 标题
		[{
				color: []
			},
			{
				background: []
			}
		], // 颜色选择
		[{
			font: [
				'SimSun',
				'SimHei',
				'Microsoft-YaHei',
				'KaiTi',
				'FangSong',
				'Arial'
			]
		}], // 字体
		[{
			align: []
		}], // 居中
		['clean'], // 清除样式,
		['link', 'image'] // 上传图片、上传视频
	]
	export default {
		name: 'falshForm',
		props: {
			showFormDia: {
				type: Boolean,
				default: false
			},
			title: {
				type: String,
				default: ''
			},
			pId: {
				type: String,
				default: ''
			}
		},
		components: {
			quillEditor,
			iconDialog
		},
		data() {
			return {
				previewUrl: window.context.portal + '/file/onlinePreviewController/v1/getFileById_',
				uploadUrl: window.context.portal + '/file/v1/uploadFileForConfig', // 服务器上传地址
				accept: '.bmp,.jpg,.png,.tif,.gif,.pcx,.tga,.exif,.fpx,.svg,.psd,.cdr,.pcd,.dxf,.ufo,.eps,.ai,.raw,.WMF,.webp,.avif,.apng,.xls,.docx,.docm,.doc,.dotx,.pptx,.pptm,.ppt,.pdf,.xps,.potx,.txt,.xls,.xlsx,.xps,.zip,.rar,.7z',
				acceptImg: '.jpg,.jpeg,.png,.JPG,.JPEG,.gif,.PNG,.GIF',
				fileList: [],
				params: {
					type: null,
					title: null,
					titleDescription: null,
					isUrl: true,
					url: null,
					endTime: null,
					drafter: null,
					rotatingDisplayPictures: null,
					file: null,
					type: null,
					content: null,
					createTime: moment().format('YYYY-MM-DD HH:mm:ss')
				},
				rotatingDisplayPictures: null,
				classifyNames: [{
						name: '新闻公告',
						value: 1
					},
					{
						name: '轮播图',
						value: 2
					}
				],
				crOverTypes: [], //跨界类型字典数组
				basGrads: [], //流域级别字典类型
				basAdNames: [], //行政下拉
				AdName: null, //接受每次选中的值
				setKesLabel: {
					value: 'code',
					label: 'name',
					children: 'children'
				},
				rules: {
					type: [{
						required: true,
						message: '请选择所属类型',
						trigger: 'change'
					}],
					title: [{
						required: true,
						message: '请输入标题',
						trigger: 'blur'
					}],
					isUrl: [{
						required: true,
						message: '请选择是否外部链接',
						trigger: 'blur'
					}],
					url: [{
						required: true,
						message: '请输入外部链接',
						trigger: 'blur'
					}],

					rotatingDisplayPictures: [{
						required: true,
						message: '请上传轮播展示图片',
						trigger: 'blur'
					}],

					drafter: [{
						required: true,
						message: '请输入拟稿人',
						trigger: 'blur'
					}]
				},
				buildTypes: [],
				buildStructures: [],
				// 富文本配置
				editorOption: {
					placeholder: '请在这里输入',
					theme: 'snow', //主题 snow/bubble
					modules: {
						history: {
							delay: 1000,
							maxStack: 50,
							userOnly: false
						},
						toolbar: {
							container: toolbarOptions,
							handlers: {
								image: function(value) {
									if (value) {
										// 调用element的图片上传组件
										document.querySelector('.avatar-qeuploader input').click()
									} else {
										this.quill.format('image', false)
									}
								}
							}
						}
					}
				}
			}
		},
		created() {
			this.getDetailInfo()
			this.buildTypes = dictUtils.getDictItemsFromCache('shzhfz-zfjzlx')
			this.buildStructures = dictUtils.getDictItemsFromCache('shzhfz-zfjgxs')
		},
		computed: mapState({
			header: state => {
				return {
					Authorization: `Bearer ${state.login.currentUser.token}`
				}
			}
		}),
		methods: {
			handleAvatarSuccess(res, file) {
				console.log(res.fileId)
				console.log(this.previewUrl + res.fileId)
				this.$set(this.params, 'rotatingDisplayPictures', res.fileId)
				this.rotatingDisplayPictures = this.previewUrl + res.fileId
				// this.$set(this.params, 'rotatingDisplayPictures', res.fileId)
				// this.params.rotatingDisplayPictures = URL.createObjectURL(file.raw);
			},
			beforeAvatarUpload(file) {
				const suffix =
					file.type === 'image/jpg' ||
					file.type === 'image/png' ||
					file.type === 'image/jpeg'
				if (!suffix) {
					this.$message.error('上传轮播图片支持格式-JPG/PNG/JPEG!')
				}
				return suffix
			},
			handleClose() {
				this.params = {}
				this.$emit('closeFormDiao')
			},
			uploadData() {
				return {
					body: JSON.stringify({
						bizCode: 'newAccessory',
						bizId: ''
					})
				}
			},
			selectIcon(data) {
				this.params.icon = data
				this.$forceUpdate()
			},
			// 失去焦点
			onEditorBlur(editor) {},
			// 获得焦点
			onEditorFocus(editor) {},
			// 开始
			onEditorReady(editor) {},
			// 值发生变化
			onEditorChange(editor) {
				this.params.content = editor.html
			},
			qeuploadSuccess(res) {
				// 获取富文本组件实例
				let quill = this.$refs.QuillEditor.quill
				// 如果上传成功
				if (res) {
					// 获取光标所在位置
					let fileId = res.fileId
					let url = this.previewUrl + fileId
					let length = quill.getSelection().index
					// 插入图片，res为服务器返回的图片链接地址
					quill.insertEmbed(length, 'image', url)
					// 调整光标到最后
					quill.setSelection(length + 1)
				} else {
					// 提示信息，需引入Message
					this.$message.error('图片插入失败！')
				}
			},
			uploadSuccess(res) {
				if (res) {
					console.log(res)
					let arr = []
					arr.push({
						fileName: res.fileName,
						fileId: res.fileId
					})
					this.params.file = JSON.stringify(arr)
				} else {
					// 提示信息，需引入Message
					this.$message.error('上传失败！')
				}
			},
			beforeUpload(file) {
				return true
			},
			// 根据ID查询
			getDetailInfo() {
				if (this.title === '修改') {
					newsRelease.detailId(this.pId, res => {
						this.params = res
						this.params.isUrl =
							res.isUrl == 'false' ? false : res.isUrl == 'true' ? true : ''
						this.rotatingDisplayPictures =
							this.previewUrl + res.rotatingDisplayPictures
						this.params.file = res.file
						if (res.file) {
							let aaa = JSON.parse(res.file)
							aaa.forEach(e => {
								this.fileList.push({
									name: e.fileName,
									url: this.previewUrl + e.fileId
								})
							})
						}
					})
				} else {}
			},
			goInfo() {
				if (!this.params.isUrl) {
					this.params.url = ''
				} else if (this.params.isUrl) {
					this.params.content = ''
				} else {
					this.params.url = ''
					this.params.content = ''
				}
				if (this.params.type == '1') {
					this.params.rotatingDisplayPictures = ''
				} else if (this.params.type == '2') {
					this.params.icon = ''
				} else {
					this.params.rotatingDisplayPictures = ''
					this.icon = ''
				}
				this.$refs.formInfo.validate(valid => {
					if (valid) {
						if (this.title === '新增') {
							newsRelease.addSave(this.params, response => {
								if (response.state) {
									this.$notify({
										type: 'success',
										message: '新增成功',
										duration: 2000
										// offset: 80
									})
									this.$emit('closeFormDiao')
									this.$emit('refList')
								} else {}
							})
						}
						if (this.title === '修改') {
							newsRelease.upData(this.params, response => {
								if (response.state) {
									this.$notify({
										type: 'success',
										message: '修改成功',
										duration: 2000
									})
									this.$emit('closeFormDiao')
									this.$emit('refList')
								} else {}
							})
						}
					} else {
						return false
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	/deep/.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	/deep/.avatar-uploader .el-upload:hover {
		border-color: #409eff;
	}

	/deep/.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	/deep/.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	/deep/ .ql-container {
		min-height: 300px;
	}

	/deep/.el-dialog__body {
		overflow-y: auto;
		max-height: 600px;
	}
</style>
