<template>
    <div class="sendContent-cmp">
        <div class="send-content clear-fix">
            <div class="content-label font-14" v-if="config.title">{{config.title}}</div>
            <div class="text-container">
                <!--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"
                                 :insertDyn="insertDynVal"></TplEdit>
                    </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>
						</div>
                    </div>

                    <div
                            :class="{'text-operate':true,'bd-gray':!this.inputTextFocus,'el-border-primary':this.inputTextFocus}">
                        <!-- 动态数据变量插入 -->
                        <DynaDataVarList class=""
                                         v-if="dynFileObj && dynFileObj.titles && dynFileObj.titles.length>0"
                                         btnName="插入动态变量"
                                         placement="bottom"
                                         trigger="hover"
                                         @handleBtnClick="handleDynInsert"
                                         :dynFileObj="dynFileObj"></DynaDataVarList>
                        <el-button :disabled="!hasInput" size="small" type="primary" @click="resetContent"
                                   class="clean-btn m-b-5">清空
                        </el-button>
                        <el-button :disabled="!hasInput" size="small" type="primary" @click="preview" class="m-r-5">预览
                        </el-button>
                    </div>

                </div>
                <!-- 字数、条数 -->
                <div class="text-info el-border-master el-c-master font-12 m-t-10 clearfix">
                    已输入<span class="el-c-primary">{{fullContent.length}}</span>/{{config.isLongText ? 1000 : 402}}个字，最多{{config.isLongText ? 1000 : 402}}字，计
                    <span class="el-c-primary">{{sendNum}}</span>条短信
                    <el-popover ref="tips" placement="top" trigger="hover">
                        <p>1.短信字数<=70字，按单条短信计算（一个汉字为一个字符<br/>
                            2.短信字数>70字，按长短信计算，例如135字=67+67+1=3条<br/>
                            &nbsp;（最多一次可发送1000字，计15条短信）<br/>
                            3.字数统计含企业签名</br/>
                            4.每一个换行占用一个汉字或字符
                        </p>
                    </el-popover>
                    <i v-popover:tips class="el-icon-information el-c-primary"></i>
                    <el-checkbox v-model="ignoreWhiteSpace" class="pull-right">自动过滤内容中空格</el-checkbox>
                </div>

                <!-- 字数超过70提示 -->
                <div class="text-warning m-t-15" v-show="fullContent.length>70">
                    <div class="com-info-box el-bg-primary-light el-c-primary text-center font-12">
                        注意：当前内容已超过70字，会产生多条收费，为避免多收费，请再次确认短信内容长度
                    </div>
                </div>
                <div class="text-warning" v-show="sensitiveMatchList.length>0">
                    <div class="com-info-box el-bg-primary-light el-c-danger text-center font-12">
                        注意：您的内容存在禁止类敏感词[{{sensitiveMatchStr}}]
                    </div>
                </div>

            </div>
        </div>

        <!-- 预览 -->
        <transition name="slide-fade">
            <div class="preview-dialog" v-show="showPreviewPopFmt"
                 :style="{backgroundImage: 'url(' + previewbgimg + ')'}">
                <div class="priview-close" @click="preview"><i class="el-icon-circle-close"></i></div>
                <div class="clearfix content-body">
                    <div class="preview-container" v-if="sendNum ==1">
                        <div class="preview-item el-bg-master-dark">{{fullContent}}</div>
                    </div>
                    <div v-else>
                        <div class="preview-container m-t-10" v-for="item in fullList">
                            <div class="preview-item el-bg-master-dark">{{item}}</div>
                        </div>
                    </div>
                </div>
            </div>
        </transition>

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

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

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

			},
			//动态数据变量列表{}
			dynFileObj: {
				type: Object,
				required: false
			},
			//{sensitive: '敏感词'}
			urls: {
				type: Object,
				required: false,
				default: function () {
					return {}
				}

			},
			config: {
				type: Object,
				required: true,
				default: function () {
					return {
						title: '发送内容',
						spSign: '',
						isLongText: false
					}
				}
			},
			//是否显示预览弹出框
			showPreviewPop: {
				type: Boolean
			},
			//是否将输入框置灰
			disableEdit: {
				type: Boolean,
				default: true
			}

		},
		data() {
			return {
				previewbgimg: require('./static/img/preview.png'),
				sensitiveMatchList: [],//敏感词匹配到的集合
				insertDynVal: {},
				inputTextFocus: false,
				inputText: this.value.text,//文本框内容
				tplEditRes: {},//模板内容
				showSign: true,//文本框中显示签名
				matching: false,//是否正在匹配敏感词
				matchQueue: [],//匹配关键字队列
				ignoreWhiteSpace: true,//自动过滤内容中空格
			}
		},
		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;
				}
			},
			showPreviewPopFmt() {
				return this.showPreviewPop
			},
			disableEditCpu() {
				return this.config.disableEdit
			}
		},
		methods: {
			//清空
			resetContent: function () {
				this.inputText = ''
				this.$emit('update:tpldata', {})//对应templateObj.sync语法糖
				this.$emit('input', {
					text: '',
					isValid: false,
					sensitiveMatchList: [],
					textTemplateId: '',
					sendNum: this.sendNum
				})
			},
			preview: function () {
				this.$emit('togglePop', !this.showPreviewPopFmt)
			},
			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)
			},
			emitInputEvent: function () {
				if (Object.keys(this.tpldata).length > 0) {
					var text = this.tplEditRes.valList.join('')
					this.$emit('input', {
						text: text,
						isValid: this.sensitiveMatchList.length > 0,
						sensitiveMatchList: this.sensitiveMatchList,
						textTemplateId: this.tplEditRes.textTemplateId,
						sendNum: this.sendNum
					})
				} else {
					this.$emit('input', {
						text: this.inputText,
						isValid: this.sensitiveMatchList.length > 0,
						sensitiveMatchList: this.sensitiveMatchList,
						sendNum: this.sendNum
					})
				}
			},
			//插入动态变量
			handleDynInsert: function (index) {
				this.insertDynVal = {
					title: '{' + this.dynFileObj.titles[index] + '}',
					maxVal: this.dynFileObj.colMaxValMap[index]
				}
				if (!this.tpldata.id) {
					this.insertDyn2Input()
				} else {

				}

			},
			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
				})
			}

		},
		watch: {
			config: {
				deep: true,
				handler: function () {
					this.setTextareaStyle()
				}
			}

		},
		mounted: function () {
			this.setTextareaStyle()
			this.listenerTextArea()
		}

	}
</script>

<style type="text/css" scoped>
    .content-body {
        margin-top: 80px;
        height: 420px;
        width: 275px;
        overflow-y: auto;
    }

    .content-body::-webkit-scrollbar {
        width: 10px;
        height: 16px;
        background-color: #f5f5f5;
    }

    /*定义滚动条的轨道，内阴影及圆角*/
    .content-body::-webkit-scrollbar-track {
        -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
        border-radius: 10px;
        background-color: #f5f5f5;
    }

    /*定义滑块，内阴影及圆角*/
    .content-body::-webkit-scrollbar-thumb {
        height: 10px;
        border-radius: 10px;
        -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
        background-color: #e2e2e1;
    }

    .send-content {
        display: flex;
        /*align-items: center;*/
        padding: 10px 0px;
    }

    .content-label {
        padding-bottom: 24px;
        flex: 2;
    }

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

    .text-container {
        margin-left: 10px;
        flex: 16;
    }

    .text-box {
        position: relative;
    }

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

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

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

    .com-info-box {
        border-style: none
    }

    .clean-btn {
        margin-left: 10px;
    }

    .preview-dialog {
        z-index: 2002;
        position: fixed;
        top: 50%;
        right: 0px;
        transform: translate(0, -50%);
        height: 600px;
        width: 300px;
        background-repeat: no-repeat;
    }

    .slide-fade-enter-active {
        transition: all .5s;
    }

    .slide-fade-leave-active {
        transition: all .5s;
    }

    .slide-fade-enter, .slide-fade-leave-to
        /* .slide-fade-leave-active for below version 2.1.8 */
    {
        transform: translate(100%, -50%);
        opacity: 0
    }

    .preview-container {

        position: relative;
        width: 220px;
        max-height: 360px;
        left: 36px;
        font-size: 12px;
    }

    .preview-item {
        overflow-y: auto;
        padding: 2px;
        max-height: 360px;
        border-radius: 10px;
        padding: 10px;
    }

    .preview-container:before {
        position: absolute;
        content: "\00a0";
        width: 0px;
        height: 0px;
        border-width: 6px 18px 6px 0;
        border-style: solid;
        border-color: transparent rgb(230, 230, 230) transparent transparent;
        top: 10px;
        left: -18px;
        z-index: 99999;
    }

    .priview-close {
        position: relative;
        top: -6px;
        left: 278px;
        cursor: pointer;
        font-size: 20px;
    }

    .mask {
        position: fixed;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: #000;
        opacity: 0.7;
        z-index: 2001;
        height: 100%
    }
</style>

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

    .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>
