<template>
	<div :class="{'sendContent-cmp':true, 'cmp-shadow': shadow}" @mouseover="shadow = true" @mouseout="shadow = false">
		<div class="sms-com-part">
			<div class="sms-com-title clearfix">
				<span class="sms-com-title-img"></span>
				<span class="sms-com-title-con">编辑短信内容</span>
				<div class="right-op">
					<a href="javascript:void(0);" class="el-c-hover m-r-10" style="color:gray;" @click="preview">
						<i class="fi-preview m-r-7" style="vertical-align: middle;"></i><span class="el-c-primary">预览</span>
					</a>
					<a href="javascript:void(0);" class="el-c-hover" style="color:gray;position: relative"
					   @click="chooseTpl">
						<i class="fi-select-module m-r-4"></i><span class="el-c-primary" >选择模板</span>
						<i class="fi-new el-c-danger new-tip-icon"></i>
					</a>
				</div>
			</div>

			<div class="sms-com-body">
				<div class="body-head clearfix">
					<div class="head-left">
						已输入<span class="kw">{{fullContent.length}}</span>/{{config.isLongText ? 1000 : 402}}字,
						计<span class="kw">{{sendNum}}</span>条短信,
						当前短信内容可编辑<span class="kw">{{config.isLongText ? 1000 : 402}}</span>字
						<i class="fi-notes el-c-info font-14" style="cursor: pointer;" @mouseenter="showWordDesc = true"
						   @mouseleave="showWordDesc = false"></i>
					</div>
					<div class="head-right">
						<el-checkbox v-model="useDyn" :true-label="1" :false-label="0">使用动态数据</el-checkbox>
						<el-checkbox v-model="ignoreWhiteSpace" :true-label="1" :false-label="0">自动过滤空格</el-checkbox>
					</div>
					<div class="sms-content-tip" v-show="showWordDesc">
						<WordDesc v-show="showWordDesc"></WordDesc>
					</div>
				</div>
				<DynaDataUpload
					v-if="useDyn === 1"
					class="m-b-10"
					:urls="urls"
					:fileUrls="fileUrls"
					@change:dyndata="changeDynData"
					@insertDynKey="insertDynKey"/>

				<!--position:relative-->
				<div class="text-box">
					<!-- 签名 -->
					<span class="sp-sign el-c-primary" v-show="showSign">{{config.spSign}}</span>
					<div class="tpl-container" v-show="Object.keys(tpldata).length>0">
						<!-- if发送内容为模版 -->
						<TplEdit :tpldata="tpldata"
								 @tplchange="tplChange"
								 :spsign="config.spSign"
								 :ignoreWhiteSpace="ignoreWhiteSpace === 1"
								 :insertDyn="insertDynVal" style="margin-top: -3px;"></TplEdit>
						<span class="text-reset el-bg-primary" @click="resetContent">
							<i class="fi-delete"></i>
						</span>

					</div>
					<!-- if发送内容为自定义文本 -->
					<div v-show="Object.keys(tpldata).length <= 0" class="text-edit-container">
						<div class="smstextarea el-textarea">
							<textarea :value="inputText" @input="textInputEvent" @focus="inputTextFocus = true"
									  @blur="inputTextFocus = false" name="inputTextName"
									  rows="8"
									  :disabled="disableEditCpu"
									  :maxlength="config.isLongText?1000-config.spSign.length:402-config.spSign.length"
									  class="el-textarea__inner" placeholder="请选择模版免审即时发送，或输入短信内容"></textarea>
							<span class="text-reset el-bg-primary" @click="resetContent">
							<i class="fi-delete"></i>
						</span>
						</div>
					</div>

					<div
						:class="{'text-operate':true,'bd-gray':!this.inputTextFocus,'el-border-primary':this.inputTextFocus}"></div>

				</div>

				<div class="bottom-tips el-c-danger" v-show="sensitiveMatchList.length>0"><i
					class="fi-information el-c-danger"></i>当前短信内容包含敏感词[{{sensitiveMatchStr}}],将无法发送
				</div>

			</div>

		</div>
	</div>
</template>
<script type="text/ecmascript-6">
	import Vue from 'vue'
	import {Button, Input, Popover, Checkbox} from 'element-ui'
	import TplEdit from './TplEdit.vue'
	import DynaDataUpload from './DynaDataUpload.vue'
	import WordDesc from './WordDesc.vue'

	Vue.use(Button).use(Input).use(Popover).use(Checkbox)
	export default {
		components: {TplEdit, DynaDataUpload, WordDesc},
		created() {

		},
		props: {
			/**
			 * 输出 {text:'文本内容',textTemplateId:'模板id',dynPath:'',delRepeat:1}
			 */
			//v-model
			value: {
				type: Object,
				required: true
			},
			/**
			 * 输入
			 */
			//模版对象
			tpldata: {
				type: Object,
				required: false

			},

			//{sensitive: '敏感词'}
			urls: {
				type: Object,
				required: false,
				default: function () {
					return {}
				}

			},
			fileUrls: {
				type: Object
			},
			config: {
				type: Object,
				required: true,
				default: function () {
					return {
						title: '发送内容',
						spSign: '',
						isLongText: false
					}
				}
			},

			//是否将输入框置灰
			disableEdit: {
				type: Boolean,
				default: true
			}

		},
		data() {
			return {
				shadow: false,//鼠标移入阴影效果
				showWordDesc: false,//显示字数描述
				useDyn: 0,
				dynData: {validityFilePath: '', validityCount: 0},//上传的动态数据
				//dynFileObj: {},//动态数据上传结果
				//previewbgimg: require('./static/img/preview.png'),
				sensitiveMatchList: [],//敏感词匹配到的集合
				insertDynVal: {},//插入动态数据{title:'{手机号}',maxVal:'1355555555'}
				inputTextFocus: false,
				inputText: this.value.text,//文本框内容
				tplEditRes: {},//模板内容
				showSign: true,//文本框中显示签名
				matching: false,//是否正在匹配敏感词
				matchQueue: [],//匹配关键字队列
				ignoreWhiteSpace: 0//自动过滤内容中空格
			}
		},
		computed: {
			sensitiveMatchStr: function () {
				if (this.sensitiveMatchList.length <= 0) {
					return '';
				}
				var str = '';
				for (var i = 0; i < this.sensitiveMatchList.length; i++) {
					str += this.sensitiveMatchList[i]['word'] + ' '
				}
				return str;
			},
			//发送内容=签名+短信内容
			fullContent: function () {
				if (Object.keys(this.tpldata).length <= 0) {
					return this.config.spSign + this.inputText
				} else {
					var vals = this.tplEditRes.valList || [];
					return this.config.spSign + vals.join('')
				}
			},
			//发送计数
			sendNum: function () {
				if (this.fullContent.length <= 70) {
					return Math.ceil(this.fullContent.length / 70)
				} else {
					return Math.ceil(this.fullContent.length / 67)
				}
			},
			hasInput() {
				return this.inputText.length > 0 || Object.keys(this.tpldata).length > 0
			},
			fullList: function () {
				if (this.fullContent.length > 70) {
					var count = Math.ceil(this.fullContent.length / 67);
					var contentList = [];
					for (var i = 0; i < count; i++) {
						contentList.push(this.fullContent.slice(i * 67, 67 * (i + 1)));
					}
					return contentList
				} else {
					return false;
				}
			},

			disableEditCpu() {
				return this.config.disableEdit
			}
		},
		methods: {

			//清空
			resetContent: function () {
				this.inputText = ''
				this.$emit('update:tpldata', {})//对应templateObj.sync语法糖
				this.$emit('input', {
					text: '',
					dynData: this.dynData,
					isValid: false,
					sensitiveMatchList: [],
					textTemplateId: '',
					sendNum: this.sendNum
				})
			},
			preview: function () {
				this.$emit('preview');
			},
			chooseTpl: function () {
				this.$emit('chooseTpl');
			},
			tplChange: function (vals) {
				this.tplEditRes = vals
				this.emitInputEvent()
				var text = this.tplEditRes.valList.join('')
				this.matchSensitiveWord(text)
			},
			textInputEvent: function (e) {
				let text = e.target.value
				this.inputText = this.ignoreWhiteSpace ? text.replace(/\s/g, '') : text;
				this.emitInputEvent()
				this.matchSensitiveWord(this.inputText)
			},
			changeDynData: function (dynData) {
				this.dynData = dynData;
				this.emitInputEvent();
			},
			emitInputEvent: function () {
				if (Object.keys(this.tpldata).length > 0) {
					var text = this.tplEditRes.valList.join('')
					this.$emit('input', {
						text: text,
						dynData: this.dynData,
						isValid: this.sensitiveMatchList.length > 0,
						sensitiveMatchList: this.sensitiveMatchList,
						textTemplateId: this.tplEditRes.textTemplateId,
						sendNum: this.sendNum
					})
				} else {
					this.$emit('input', {
						text: this.inputText,
						dynData: this.dynData,
						isValid: this.sensitiveMatchList.length > 0,
						sensitiveMatchList: this.sensitiveMatchList,
						sendNum: this.sendNum
					})
				}
			},
			//插入动态变量
			insertDynKey: function (data) {
				this.insertDynVal = data;
				if (!this.tpldata.id) {
					this.insertDyn2Input()
				}

			},
			insertDyn2Input: function () {
				var inputs = document.getElementsByName('inputTextName')
				if (inputs.length > 0) {
					var input = inputs[0]
					var start = input.selectionStart
					var end = input.selectionEnd
					this.inputText = this.inputText.substring(0, start) + this.insertDynVal.title + this.inputText.substring(end)
				}
				this.emitInputEvent()
			},
			setTextareaStyle: function () {
				var textarea = document.getElementsByName('inputTextName')[0]
				if (textarea) {
					textarea.style.textIndent = this.config.spSign.length * 14 + 'px';
				}
			},
			listenerTextArea: function () {
				var textarea = document.getElementsByName('inputTextName')[0]
				if (textarea) {
					textarea.addEventListener('scroll', () => {
						this.showSign = !(textarea.scrollTop > 10)
					})
				}
			},
			matchSensitiveWord: function (text) {
				if (!this.urls.sensitive) {
					return;
				}
				if (text) {
					this.matchQueue.push(text)
				}
				if (this.matching) {
					return;
				}
				this.matching = true
				setTimeout(() => {
					var txt = this.matchQueue.pop()
					this.matchQueue = []
					if (!txt) {
						this.matching = false
						return;
					}
					this.querySensitive(txt)
				}, 1000)

			},
			querySensitive: function (text) {
				this.$http.post(this.urls.sensitive, {text: text, type: '2'}).then((res) => {
					this.matching = false
					this.sensitiveMatchList = res.data.matchList || []
					this.emitInputEvent()
					if (this.matchQueue.length > 0) {
						this.matchSensitiveWord(this.matchQueue.pop())
					}
				}).catch(() => {
					this.matching = false
				})
			},
			resetDynData: function (dynData) {
				this.dynData = {validityFilePath: '', validityCount: 0};
				this.emitInputEvent();
			}
		},
		watch: {
			config: {
				deep: true,
				handler: function () {
					this.setTextareaStyle()
				}
			},
			useDyn(val) {
				if (val === 0) {
					this.resetDynData()
				}
			},
			tpldata() {
				if (Object.keys(this.tpldata).length > 0) {
					this.showSign = true;
				}
			}
		},
		mounted: function () {
			this.setTextareaStyle()
			this.listenerTextArea()
		}

	}
</script>

<style type="text/css" scoped>

	.sms-com-body {
		border: 1px solid #ebebeb;
		padding: 10px;
		background-color: #f5f5f5;
		box-sizing: border-box;
	}

	.sms-com-title {
		margin-bottom: 7px;
	}

	.sms-com-title .sms-com-title-con {
		margin-left: 5px;
		font-size: 14px;
		font-weight: bold;
		color: #333;
	}

	.sms-com-title .sms-com-title-img {
		display: inline-block;
		width: 20px;
		height: 23px;
		/*background: url("../../../assets/img/model_03.jpg");*/
		background: url("../../assets/img/tep-icons.png") no-repeat -5px -5px;
		vertical-align: middle;
	}

	.sms-com-part {
		background-color: #fff;
		padding: 15px;
		border: 1px solid #ebebeb;
	}

	.new-tip-icon {
		position: absolute;
		right: 0px;
		top: 0px;
		transform: translate(100%, -100%);
	}

	.cmp-shadow {
		box-shadow: 1px 1px 5px gray;
	}

	.right-op {
		float: right;
	}

	.body-head {
		margin-bottom: 10px;
		position: relative;
	}
	.sms-content-tip{
		position: absolute;
		z-index: 100;
		top:28px;
	}
	.head-left {
		float: left;
	}

	.head-right {
		float: right;
	}

	/*输入框开始*/
	.text-box {
		position: relative;
	}

	.sp-sign {
		position: absolute;
		font-size: 14px;
		left: 7px;
		top: 15px;
	}

	.tpl-container {
		border: 1px solid #dcdcdc;
		border-bottom: none;
		padding: 10px;
		background-color: #fff;
	}

	.text-reset {
		position: absolute;
		bottom: 0px;
		right: 0px;
		font-size: 14px;
		width: 26px;
		height: 26px;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: center;

	}

	.text-operate {
		border-width: 1px;
		border-style: solid;
		border-top: none;
		text-align: right;
		padding-bottom: 1px;
		padding-right: 5px;
		margin-top: -1px;
	}

	.bd-gray {
		border-color: #dcdcdc;
	}

	.kw {
		font-family: Georgia;
		font-size: 18px;
		color: #f67a17;
	}

	.bottom-tips {

	}
	.m-r-7 {
		margin-right:7px;
	}
	.m-r-4 {
		margin-right:4px;
	}
	.fi-delete:before {
		color: #FFF;
	}
</style>

<style type="text/css">
	.sendContent-cmp {
		font-size: 12px;
	}

	.sendContent-cmp .el-checkbox__label {
		font-size: 12px;
	}

	.sendContent-cmp .smstextarea textarea {
		/*text-indent: 50px;*/
		border-bottom: none;
		padding-bottom: 0px;
		padding-top: 14px;
		font-size: 14px;
	}

	.sendContent-cmp .el-textarea__inner {
		resize: none
	}

	.tpl-container .el-input {
		max-width: 490px;
	}
</style>
