<template>
    <div class="attention-text-wrap">
	    <div class="attention-text-content">
	    	<div class="text-title">
	        <a @click="addLinkDialogShow" class="iconfont icon-lianjie" title="添加链接"></a>
					<a @click="removeLink" class="iconfont icon-duankailianjie" :class="{'no-link':!cancelLink}" title="取消链接"></a>
	       </div>
        <div class="text-content">
        	<div @mouseup="selectLeft" v-html="textarea" class="my-textarea" @blur="getAllMytext" ref="myTextarea" contentEditable=true></div>
        </div>
	    </div>
        <!-- 添加回复链接的dialog -->
	    <div class="add-replay-link" v-if="addReplayDialog">
        <el-dialog
          title="添加回复链接"
          width="1068px"
          class="replay-link-dialog"
          :visible.sync="addReplayDialog">
          <div class="add-replay-content">
            <el-form  label-position="right" ref="form" :model="form" label-width="100px">
              <el-form-item class="text-content" label="文本内容">
				    		<el-input v-model="form.text" @keyup.native="toInput(form.text,$event)"></el-input>
					    	<span class="text-num">{{inputNum}}/{{inputLength}}</span>
							</el-form-item>
							<el-form-item label="文本链接">
								<el-radio-group v-model="form.linkStyle">
								  <el-radio label="0">网址</el-radio>
								  <el-radio label="1">小程序</el-radio>
								</el-radio-group>
							</el-form-item>
							<div class="content-wrap">
							 	<div v-show="form.linkStyle==0" class="url-content-wrap">
								 	<el-form-item label="链接地址">
								    <el-input v-model="form.url" ></el-input>
								    <p class="link-url-warning">
								      若您输入的超链接中不包含http等协议，默认将为您添加http://前缀
								    </p>
									</el-form-item>
								</div>
								<div v-show="form.linkStyle==1" class="xcx-content-wrap">
								 	<div class="upload-img-wrap">
								 		<span>上传图片</span>
								 		<div class="upload-content">
								 			<!-- <el-upload
											  class="avatar-uploader"
											  action="/api-admin/marketing-wechat-image-save"
											  :show-file-list="false"
											  :on-success="handleAvatarSuccess"
											  :before-upload="beforeAvatarUpload">
											  <img v-if="imageUrl" :src="imageUrl" class="avatar">
											  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
											</el-upload> -->
                      <el-upload
                        class="avatar-uploader"
                        action="123"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      </el-upload>
                      <p>请上传长宽比为5:4的图片</p>
								 		</div>
								 	</div>
                  <linkToolsPage ref="childlinktoolspage" :isWx="isWx" @linkSelect="linkSelect" :showType="showType"></linkToolsPage>
								</div>
							</div>
            </el-form>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addReplayDialog = false">取 消</el-button>
            <el-button type="primary" @click="addReplyBtn">确 定</el-button>
          </div>
        </el-dialog>
	    </div>
    </div>
</template>

<script>
  import linkToolsPage from '@/components/linktools/linktoolspage'
  import strLength from '@/utils/strlen';
  export default {
    name: "public_attention_text",
    props:{
  		msgText:{
  			type:String,
  			default:''
  		}
  	},
    data(){
    	return {
    		form: {
          text:'',
          linkStyle:'0',
          url:''
        },
    		cancelLink:false,
    		addReplayDialog:false,
    		imageUrl: '',
    		textarea:'',
    		textareaContent:'',

        inputNum: 0,      // 输入文字个数(两个字母/汉字算一个字)
        inputLength: 20,   // 限制最大字数

        isWx:true,  // 小程序链接去掉h5

        imageMediaId: '',  // 图片上传之后的 uid
        xcxUrlObj:{},
        showType:2,
    	}
    },
    watch:{
  		msgText:function(val){
  			// console.log(val);	// val即message的值
  			this.textarea=val;
        var reg = /<a\s+href=['"]([^"]*)['"].*?[^>]*>(.*?)<\/a>/g;
        if(reg.exec(this.textarea)!=null){
          this.cancelLink=true;
        }
    	}
    },
    created(){
    	this.textarea = this.$parent.oldTextarea;
    },
    mounted(){
    	this.oldCancelLink()
    },
    methods: {
    	oldCancelLink(){
    		// console.log(this.textarea);
    		var reg = /<a\s+href=['"]([^"]*)['"].*?[^>]*>(.*?)<\/a>/g;
    		if(reg.exec(this.textarea)!=null){
    			this.cancelLink=true;
    		}
    	},
      toInput(value,e) {          // 控制字符数量
        var that = this;
        that.form.text = strLength.getByteVal(e.target.value,that.inputLength);
        that.inputNum = strLength.getZhLen(that.form.text);
      },
    	beforeAvatarUpload(file) {
        console.log(file)
        let fd = new FormData();
        fd.append('file', file);
        fd.append('requestProject', 'gic-web');
        this.axios.post('/api-admin/marketing-wechat-image-save', fd).then((res)=> {//成功后回调
          var data = res.data;
          console.log(data);
          if(data.errorCode==0){
            this.imageUrl = data.result.qcloudImageUrl;
            this.imageMediaId = data.result.imageMediaId;

            this.$message({
              type:'success',
              message:'上传成功'
            })

          } else {
            this.$message({
              type:'error',
              message:data.message
            })
          }
        })
        return true
    	},
      handleAvatarSuccess(res, file) {
        // console.log(file);
        // this.$message({
        //   type:'success',
        //   message:'上传成功'
        // })
        // this.imageUrl = URL.createObjectURL(file.raw);
        // this.imageMediaId = file.uid;
        // console.log(this.imageUrl);
      },
      selectLeft(){   // 获得鼠标左键选中的值的函数
        this.form.text=window.getSelection().toString();  // 获得鼠标左键选中的值
      },
    	addLinkDialogShow(){	// 是否显示添加回复链接的dialog
    		// console.log(this.cancelLink);
    		if(this.cancelLink){
    			this.$message.error('只能添加一个链接');
    		}else{
    			this.addReplayDialog=true
    		}
    	},
    	removeLink(){
    		this.cancelLink=false;
    		this.textarea = this.$refs.myTextarea.innerText;
    	},
    	getAllMytext(){  // 文本框输入失去焦点时获得输入框的内容
        this.textarea = this.$refs.myTextarea.innerHTML.replace(/(<(?!\/?(a)(\s|\>))[^>]*>)/g,'').replace(/[&nbsp;]/g,'');
        console.log(this.textarea)
        this.xcxUrlObj.textarea = this.textarea;
        if(this.form.linkStyle==0){   // 文本链接
          this.xcxUrlObj.imageMediaId = ''
        } else if(this.form.linkStyle==1){   // 小程序链接
          this.xcxUrlObj.imageMediaId = this.imageMediaId
        }
    		this.$emit('listenWxText',this.xcxUrlObj)
    	},
      linkSelect(val){
        // console.log(val);     // 获得小程序链接的结果对象
        if(val!=''){
          this.cancelLink = true;
          this.form.url = val.url;
          this.textarea = this.textarea + '<a href="'+this.form.url+'">'+this.form.text+'</a>';
          this.xcxUrlObj.textarea = this.textarea;

          if(this.form.linkStyle==0){   // 文本链接
            this.xcxUrlObj.imageMediaId = ''
          } else if(this.form.linkStyle==1){   // 小程序链接
            this.xcxUrlObj.imageMediaId = this.imageMediaId
          }
          this.$emit('listenWxText',this.xcxUrlObj)
          this.addReplayDialog=false;
        }
      },
    	addReplyBtn(){	// 弹框按钮
    		var self = this;
        if(self.form.text==""){
          self.$message({
            message: '请输入文本内容',
            type: 'error'
          });
          return;
        }
    		if(self.form.linkStyle==0){   // 文本链接
    			if(self.form.url==""){
    				self.$message({
		          message: '请输入链接地址',
		          type: 'error'
		        });
		        return;
    			}else{
            self.addReplayDialog = false;
    				self.cancelLink = true;
            console.log(self.form.url);
    				if(self.form.url.indexOf('http://')!=-1 || self.form.url.indexOf('https://')!=-1){

      			}else{
              self.form.url='http://' + self.form.url;
            }
      			self.textarea = self.textarea + '<a href="'+self.form.url+'">'+self.form.text+'</a>';
            self.xcxUrlObj.textarea = self.textarea;
            self.xcxUrlObj.imageMediaId = '';
      			self.$emit('listenWxText',self.xcxUrlObj)
    			}
    		} else if (self.form.linkStyle==1){   // 小程序链接
          if(self.imageMediaId  == ''){
            self.$message({
              message: '请上传图片',
              type: 'error'
            });
          } else {
            self.$refs.childlinktoolspage.confirmLinkSelect();
          }
    		}
    	}
    },
    components:{
      linkToolsPage
    }
  }
</script>

<style lang="scss" scoped>
  .attention-text-wrap{
  	.attention-text-content{
  		width: 100%;
  		border: 1px solid #e7e7eb;
    	.text-title{
    		width: 100%;
		    height: 40px;
		    line-height: 44px;
		    position: relative;
		    z-index: 1;
		    border-bottom: 1px solid #e7e7eb;
		    padding-left: 10px;
		    box-sizing: border-box;
		    a{
		    	margin-left: 10px;
		    	width: 16px;
			    height: 16px;
			    display: inline-block;
			    cursor: pointer;
		    }
		    .icon-lianjie{
		    	color: #808995
		    }
		    .icon-duankailianjie{
		    	color: #808995;
		    	&.no-link{
		    		color: #c0c4cc
		    	}
		    }
    	}
    	.text-content{
    		.my-textarea{
    			width: 100%;
    			height: 110px;
    			border: none;
    			outline: none;
    			resize: none;
    			padding: 15px;
    			font-size: 14px;
    			box-sizing: border-box;
          line-height: 1.3;
    			a{
    				color: #409EFF
    			}
    			.selectLinkText{
    				color: #409EFF
    			}
    		}
    	}
  	}
  }
  .add-replay-link{
  	.url-content-wrap{
  		width: 758px;
  	}
    .add-replay-content{
    	position: relative;
      // width: 450px;
      // margin: 0 auto;
      .text-content{
      	position: relative;
        width: 758px;
        .text-num{
          position: absolute;
          right: 10px;
          bottom: 1px;
          color: #c0c4cc;
          font-size: 12px;
          background: #fff;
          height: 34px;
          line-height: 34px;
          padding-left: 10px;
        }
      }
      .link-url-warning{
        color: #909399;
		    font-size: 12px;
		    line-height: 1;
		    padding-top: 4px;
		    margin-top: 3px;
		    position: absolute;
		    top: 100%;
		    left: 0;
      }
    }
  }
  .xcx-content-wrap{
    width: 100%;
  	.upload-img-wrap{
  		position: relative;
  		> span{
			display: inline-block;
			width: 90px;
			height: 36px;
			line-height: 36px;
      text-align: right;
			position: absolute;
  		}
  		.upload-content{
  			padding-left: 100px;
  			margin-bottom: 22px;
  			> p{
  				height: 36px;
  				line-height: 36px;
  				font-size: 12px;
  				color: #b8b8b8
  			}
  		}
  	}
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
	    border-color: #409EFF;
		}
 	}
	.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
	}
	.avatar {
    width: 150px;
    height: 150px;
    display: block;
	}
	.upload-content /deep/ .avatar-uploader .el-upload{
		border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
	}
  .upload-content /deep/ .avatar-uploader .el-upload:hover{
    border-color: #409EFF;
  }
  .add-replay-link /deep/ .replay-link-dialog > .el-dialog{
    max-height: 600px;
    overflow: auto;
  }
</style>
