<template>
	<view class="check">
		<uni-forms ref="form" :model="datainfo">
			<view class="cbox">
				<view class="chmain">
					<uni-forms-item label="发布时间" name="publishTime">
						<picker mode="date" :disabled="isdisabled" @change='bindDateChangeb'>
							<view class="flexc">
								<view class="flex1 txr f13"  :class="datainfo.publishTime?'co27':'coa'">{{datainfo.publishTime||"请选择发布时间"}}</view>
								<view class="rimg"><image :src="rimg"></image></view>
							</view>
						</picker>
					</uni-forms-item>
					<uni-forms-item label="是否启用" name="status">
						<view class="flexc" @click="getChangeFn">
							<view class="flex1"></view>
							<image :src="check" v-if="datainfo.status=='1'" class="checkimg"></image>
							<image :src="ncheck" v-else class="checkimg"></image>
						</view>
					</uni-forms-item>
					<!-- <uni-forms-item label="是否置顶" name="isTop">
						<picker range-key='dictLabel' :disabled="isdisabled" :value="sfztidx" :range="sfztList"   @change='bindDateChangea'>
							<view class="flexc">
								<view class="flex1 txr f13 co27" v-if="datainfo.isTop&&!sfzt">{{statusFormats(datainfo.isTop,sfztList,'sfzt')}}</view>
								<view class="flex1 txr f13" v-else :class="sfzt?'co27':'coa'">{{sfzt||"请选择是否置顶"}}</view>
								<view class="rimg"><image :src="rimg"></image></view>
							</view>
						</picker>
					</uni-forms-item> -->
				</view>
			</view>
			<view class="cbox">
				<view class="chmain pb10">
					<uni-forms-item label-width='0'  name="manualTitle">
						<uni-easyinput type="textarea" :disabled="isdisabled" autoHeight v-model="datainfo.manualTitle" :inputBorder='false' placeholder="输入标题" />
					</uni-forms-item>
					<view>
						<view class='toolbar' @tap="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.strike ? 'ql-active' : ''" class="iconfont icon-zitishanchuxian" data-name="strike"></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 :class="formats.lineHeight ? 'ql-active' : ''" class="iconfont icon-line-height" data-name="lineHeight"
							 data-value="2"></view>
							<view :class="formats.letterSpacing ? 'ql-active' : ''" class="iconfont icon-Character-Spacing" data-name="letterSpacing"
							 data-value="2em"></view>
							<view :class="formats.marginTop ? 'ql-active' : ''" class="iconfont icon-722bianjiqi_duanqianju" data-name="marginTop"
							 data-value="20px"></view>
							<view :class="formats.previewarginBottom ? 'ql-active' : ''" class="iconfont icon-723bianjiqi_duanhouju"
							 data-name="marginBottom" data-value="20px"></view>
							<view class="iconfont icon-clearedformat" @tap="removeFormat"></view>
							<view :class="formats.fontFamily ? 'ql-active' : ''" class="iconfont icon-font" data-name="fontFamily" data-value="Pacifico"></view>
							<view :class="formats.fontSize === '24px' ? 'ql-active' : ''" class="iconfont icon-fontsize" data-name="fontSize"
							 data-value="24px"></view>
						
							<view :class="formats.color === '#0000ff' ? 'ql-active' : ''" class="iconfont icon-text_color" data-name="color"
							 data-value="#0000ff"></view>
							<view :class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''" class="iconfont icon-fontbgcolor"
							 data-name="backgroundColor" data-value="#00ff00"></view>
						
							<view class="iconfont icon-date" @tap="insertDate"></view>
							<view class="iconfont icon--checklist" data-name="list" data-value="check"></view>
							<view :class="formats.list === 'ordered' ? 'ql-active' : ''" class="iconfont icon-youxupailie" data-name="list"
							 data-value="ordered"></view>
							<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie" data-name="list"
							 data-value="bullet"></view>
							<view class="iconfont icon-undo" @tap="undo"></view>
							<view class="iconfont icon-redo" @tap="redo"></view>
						
							<view class="iconfont icon-outdent" data-name="indent" data-value="-1"></view>
							<view class="iconfont icon-indent" data-name="indent" data-value="+1"></view>
							<view class="iconfont icon-fengexian" @tap="insertDivider"></view>
							<view class="iconfont icon-charutupian" @tap="insertImage"></view>
							<view :class="formats.header === 1 ? 'ql-active' : ''" class="iconfont icon-format-header-1" data-name="header"
							 :data-value="1"></view>
							<view :class="formats.script === 'sub' ? 'ql-active' : ''" class="iconfont icon-zitixiabiao" data-name="script"
							 data-value="sub"></view>
							<view :class="formats.script === 'super' ? 'ql-active' : ''" class="iconfont icon-zitishangbiao" data-name="script"
							 data-value="super"></view>
							<view class="iconfont icon-shanchu" @tap="clear"></view>
							<view :class="formats.direction === 'rtl' ? 'ql-active' : ''" class="iconfont icon-direction-rtl" data-name="direction"
							 data-value="rtl"></view>
						
						</view>
						
						<editor id="editor" class="ql-container" placeholder="开始输入..." showImgSize showImgToolbar showImgResize
						 @statuschange="onStatusChange" :read-only="isdisabled" @ready="onEditorReady">
						</editor>
						<!-- <editor-box ></editor-box> -->
					</view>
				</view>
			</view>
		</uni-forms>
		<view class="rfbtn" @click="getEditFn" v-if="isdisabled">修改</view>
		<view class="rfbtn" @click="getSubmit" v-else>发布</view>
		<loading></loading>
	</view>
</template>

<script>
	import config from '@/config'
	import editorBox from "@/manage/components/editor/editor.vue"
	import {checkPermi,checkRole} from "@/utils/permission"; // 权限判断函数
	import {getDictionaryFn} from "@/api/system/user.js"
	import {selectValueKey,uploadmore} from "@/utils/common.js"
	import {manualAdd,manualPut,manualDet} from "@/api/work/manage.js"
	export default {
		components: {editorBox},
		data() {
			return {
				rimg: require('@/people/static/people/rimg.png'),
				baseUrl: config.baseUrl,
				checkflag:true,
				check: require('@/people/static/people/check.png'),
				ncheck: require('@/people/static/people/ncheck.png'),
				datainfo: {
					// "manualId":"员工培训手册ID",
					"manualTitle":"",//员工培训手册标题
					"manualType":"1",//员工培训手册类型（1：图片 2:视频）
					"manualContent":"",//员工培训手册内容
					"status":"1",//员工培训手册状态
					"publishTime":"",//发布时间
					// "videoUrl":"视频地址URL",
					// "coverImage":"封面图片",
					// "author":"作者",
					// "source":"来源",
					// "viewCount":"浏览次数",
					// "isTop":"是否置顶：Y（置顶）、N（不置顶）"
				},
				formats: {},
				readOnly: false,
				wzlx:'',
				wzlxidx:'0',
				wzlxList:[],
				sfzt:'否',
				sfztidx:'1',
				sfztList:[{dictLabel:'是',dictValue:'Y'},{dictLabel:'否',dictValue:'N'}],
				id:'',
				ptype:"add",
				isdisabled:false,
				editinfo:''
			}
		},
		onLoad: function(e) {
			if(e.id){
				this.id=e.id;
				this.ptype='edit';
				// this.isdisabled=true;
				this.getDetailFn()
			}
		},
		methods: {
			checkPermi,
			checkRole,
			getEditFn(){
				this.isdisabled=false;
			},
			statusFormats(data, list,type) {
				var aite=selectValueKey(list, data);
				if(type=='wzlx'){
					this.wzlxidx=aite.key
				}else if(type=='sfzt'){
					this.sfztidx=aite.key
				}
				return aite.actions;
			},
			bindDateChange(e){
				var val=e.detail.value;
				this.datainfo.partyType=this.wzlxList[val].dictValue;
				this.wzlx=this.wzlxList[val].dictLabel;
			},
			bindDateChangea(e){
				var val=e.detail.value;
				this.datainfo.isTop=this.sfztList[val].dictValue;
				this.sfzt=this.sfztList[val].dictLabel;
			},
			bindDateChangeb(e){
				var val=e.detail.value;
				this.datainfo.publishTime=val;
			},
			getChangeFn(){
				if(this.isdisabled){
					return
				}
				if(this.datainfo.status=='1'){
					this.datainfo.status='2'
				}else{
					this.datainfo.status='1'
				}
			},
			init(){
				// 发布类型
				getDictionaryFn('publication_type').then(res=>{
					if(res.code==200){
						if(res.data){
							this.wzlxList = res.data.map(v => {
								return {
									dictLabel: v.dictLabel,
									dictValue: v.dictValue
								}
							})
						}
					}
				})
			},
			getDetailFn(){
				var that=this;
				manualDet(this.id).then(res=>{
					if(res.code==200){
						this.datainfo=res.data;
						var data=JSON.parse(JSON.stringify(res.data))
						if(data.manualContent){
							var fwbinfo=this.formatRichText(res.data.manualContent);
							this.editinfo=fwbinfo;
							uni.createSelectorQuery().select('#editor').context(function(res) {
								that.editorCtx = res.context||'';
								that.editorCtx.setContents({
									html:fwbinfo
								})
							}).exec();
						}
					}
				})
			},
			getSubmit(){
				var that=this;
				this.$refs.form.validate().then(res => {
					var params=JSON.parse(JSON.stringify(this.datainfo))
					if(!params.publishTime){
						this.$toast('请选择发布时间')
						return
					}
					if(!params.manualTitle){
						this.$toast('请输入标题')
						return
					}
					var infoContent=''
					this.editorCtx.getContents({
					    success: function(data) {
							var s=data.html;
					        infoContent=s.replace(/\<img src="(http?:\/\/)([^\/]+)(:\d+)?/g,'<img src="');
					        infoContent=infoContent.replace(/\<img src="(https?:\/\/)([^\/]+)(:\d+)?/g,'<img src="');
					    }  
					}) 
					params.manualContent=infoContent;
					if(this.ptype=='add'){
						manualAdd(params).then(res=>{
							if(res.code==200){
								this.$toast("新增成功")
								setTimeout(function(){
									uni.$emit("newsygList")
									uni.navigateBack({
										delta:1
									})
								},1500)
							}
						})
					}else{
						manualPut(params).then(res=>{
							if(res.code==200){
								this.$toast("修改成功")
								setTimeout(function(){
									uni.$emit("newsygList")
									uni.navigateBack({
										delta:1
									})
								},1500)
							}
						})
					}
					
				})
			},
			//解析富文本方法
			formatRichText(html) {
					let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
						match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '').replace(/style=""/gi, '');
						match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
						match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
						return match;
					});
					newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
						match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
						return match;
					});
					newContent = newContent.replace(/<br[^>]*\/>/gi, '');
					newContent = newContent.replace(/\<img src="/gi,
						'<img style="max-width:100%;height:auto;display:block;margin:10rpx auto;" src="' +this.baseUrl);
					return newContent;
			},
			readOnlyChange() {
				this.readOnly = !this.readOnly
			},
			onEditorReady() {
				var that=this;
				// #ifdef MP-BAIDU
				this.editorCtx = requireDynamicLib('editorLib').createEditorContext('editor');
				// #endif
			
				// #ifdef APP-PLUS || MP-WEIXIN || H5
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
					that.editorCtx.setContents({
						html:that.editinfo
					})
				}).exec()
				// #endif
			},
			undo() {
				this.editorCtx.undo()
			},
			redo() {
				this.editorCtx.redo()
			},
			format(e) {
				let {
					name,
					value
				} = e.target.dataset
				if (!name) return
				// console.log('format', name, value)
				this.editorCtx.format(name, value)
			},
			onStatusChange(e) {
				const formats = e.detail
				this.formats = formats
			},
			insertDivider() {
				this.editorCtx.insertDivider({
					success: function() {
						console.log('insert divider success')
					}
				})
			},
			clear() {
				uni.showModal({
					title: '清空编辑器',
					content: '确定清空编辑器全部内容？',
					success: res => {
						if (res.confirm) {
							this.editorCtx.clear({
								success: function(res) {
									console.log("clear success")
								}
							})
						}
					}
				})
			},
			removeFormat() {
				this.editorCtx.removeFormat()
			},
			insertDate() {
				const date = new Date()
				const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
				this.editorCtx.insertText({
					text: formatDate
				})
			},
			insertImage() {
				var that=this;
				uni.chooseImage({
					count: 1,
					success: (res) => {
						let img= res.tempFilePaths;
						let imglen = res.tempFilePaths.length;
						var fuwufile = [];
						uploadmore('/common/upload',img,0,0,0,imglen,fuwufile,function(rs){
							var url=that.baseUrl+rs[0];
							that.editorCtx.insertImage({
								src: url,
								alt: '图像',
								success: function() {
									console.log('insert image success')
								}
							})
						})	
						
					}
				})
			}
		}
	}
</script>
<style>
	page{background: #F3F3F0;}
</style>
<style lang="scss" scoped>
.check /deep/ .uni-forms-item{min-height: 106rpx;box-sizing: border-box;display: flex;align-items: center;margin-bottom: 0;border-bottom: 2rpx solid #E6E6E6;padding:10rpx 0;}
.check .cbox /deep/ .uni-forms-item:last-child{border: none;}
.check /deep/ .uni-forms-item__label{font-weight: bold;font-size: 26rpx;color: #222327;flex: 0 0 auto;width: auto !important;}
.check /deep/ .uni-easyinput{flex: 1;text-align: left;font-size: 26rpx;color: #222327;}
.check /deep/ .uni-easyinput__content-textarea{min-height: 40rpx;font-size: 26rpx;}
.check /deep/ .uni-easyinput__placeholder-class{font-size: 26rpx;color: #AAAAAA;}
.check /deep/ .uni-easyinput__content-input{padding-left: 0 !important;}
.check /deep/ .uni-input-input{font-size: 26rpx;}
.check /deep/ .uni-textarea-textarea{font-size: 26rpx;}
.check /deep/ .is-disabled{color: #222327;background-color: #ffffff !important;}
.check /deep/ .uni-data-checklist .checklist-group .checklist-box{margin:10rpx 8rpx 10rpx 16rpx;}
.check /deep/ .uni-data-checklist{flex: 0 0 auto;}
.check{min-height: 100vh;padding: 20rpx 18rpx 110rpx;box-sizing: border-box;}
.cbox{background: #FFFFFF;border-radius: 20rpx;flex: 1;margin-bottom: 24rpx;
// min-height: calc(100vh - 140rpx);

	.chmain{
		padding: 0 32rpx 0rpx;
		.rimg{width: 16rpx;height: 28rpx;flex: 0 0 auto;margin-left: 20rpx;
			image{width: 100%;height: 100%;}
		}
		.checkimg{width: 80rpx;height: 40rpx;margin-right: 8rpx;}
	}
	
}
@import "@/static/editor-icon.css";

	.page-body {
		height: calc(100vh - var(--window-top) - var(--status-bar-height));
	}

	.wrapper {
		height: 100%;
	}

	.editor-wrapper {
		height: calc(100vh - var(--window-top) - var(--status-bar-height) - 140px);
		background: #fff;
	}

	.iconfont {
		display: inline-block;
		padding: 8px 8px;
		width: 24px;
		height: 24px;
		cursor: pointer;
		font-size: 20px;
	}

	.toolbar {
		margin-bottom: 20rpx;
		box-sizing: border-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
	}

	.ql-container {
		box-sizing: border-box;
		width: 100%;
		min-height: 30vh;
		height: 100%;
		font-size: 16px;
		line-height: 1.5;
	}

	.ql-active {
		color: #06c;
	}
</style>
