<!-- 新格式的富文本组件 -->
<template>
  <div>
    <c-rich-text-editor 
      v-model="model"
      :model="modelData"
      :style="{'border-bottom': isShowRed ? `1px solid ${isShowRed}` : ''}"
      v-bind="$attrs"
      v-show="editorShow"
      @blur="blurEvent"
      @focus="focusEvent"
      @change="changeEvent"
      :disabled="disabled"
      :maxLength="maxLength"
      ref="editor"
      :heightStr="heightStr"
      :chs="chs"
			:isShowScale="isShowScale"
    ></c-rich-text-editor>

    <el-dialog
      :modal="false"
      :visible.sync="errorDialogVisible"
      :width="`${getCharWidth()+100+'px'}`"
      v-dialogDrag = true
      title="错误检查"
      destroy-on-close
      :close-on-click-modal="false"
      class= "errorDialogTip"
      top='0'
    >
      <div :style="{
        position:'relative',
        height:'100%',
        overflow:'auto'
      }">
        <div
          class="view-scroll"
          :class="[chs ? '' : 'view-scroll-en']"
          :style="{
            'padding': isShowScale ? '80px calc((100% + 20px) * 0.1 + 10px) 100px calc((100% + 20px) * 0.08' : `10px calc((100% - ${getCharWidth()+'px'} - 20px) / 2)`,
            'font-family':isShowScale ?'':'Courier New !important',
            'line-height':1.5,
            'font-size':'18.6px',
            'word-break': 'break-word'
          }"
          v-html="colorText"
        ></div>
      </div>
    </el-dialog>

		<div
			class="editor_view_div"
			v-if="isShowScale && viewShow"
			style="overflow: auto;"
			:style="{
				'background-color': disabled ? '#DFDCE6' : '#ffffff',
				'width': isShowScale ? 794 * curScale + 'px' : '',
				'border-bottom': isShowScale ? '1px solid #ccc' : '',
				'height': 'calc(100% - 41px)',
			}"
			@click="viewClick"
		>
			<div
				ref="viewDiv"
				class="w-e-text-container"
				data-slate-editor
				style="padding-left: 10px;"
				:style="{ 'font-size': curFontSize, }"
			>
				<div
					class="view-scroll"
					:class="[chs ? '' : 'view-scroll-en']"
					:style="{
            'padding': isShowScale ? '80px calc((100% + 20px) * 0.1 + 10px) 100px calc((100% + 20px) * 0.08' : `10px calc((100% - ${getCharWidth()+'px'}  - 20px) / 2)`,
            'font-family':isShowScale ?'':'Courier New !important',
            'line-height':1.5
          }"
					v-html="colorText"
				></div>
			</div>
		</div>

    <!--显示PDF的效果 -->
    <!-- <div style="height:904px;border:1px solid #EFEFEF;background:#888" v-if="pdfShow" v-loading="!$viewPdfUrl">
      <iframe v-if="tink" :key="$viewPdfUrl" :src="$viewPdfUrl" frameborder="0" height="100%" width="100%" ></iframe>
    </div> -->
    <div style="height:904px;border:1px solid #EFEFEF;background:#888" v-if="pdfShow" v-loading="!$viewPdfUrl">
			<object
				v-if="tink"
				:data="$viewPdfUrl"
				type="application/pdf"
				width="100%"
				height="100%"
			></object>
    </div>
  </div>
</template>

<script>
import commonDepend from '~/mixin/commonDepend.js'
import markSetShowRed from '~/components/business/componentMixins/markSetShowRed.js'
import Api from "~/service/Api";
import lodash from "lodash"
import {SWIFTZ_CHARS} from "~/utils"

// 保函文本
export default {
	inject: {
		root: {
			default: () => null
		}
	},

	mixins: [commonDepend, markSetShowRed],
  name: "XmlFormatEditor",
  props: {
    value: {
      type: String,
      default: ''
    },
    maxLength:{
      type:Number
    },
		modelData: {
      type: Object,
      default: () => {}
    },
    // 此对象为markset或者modifySet所在的对象,如果传了此对象可以标记当前对象下的字段为红色下划线
    markSetData: {
      type: Object,
      default: () => null
    },
		customModifykey: {
			type: String,
      default: null
    },
    disabled: {
      type: Boolean,
      default: false
    },
    chs: {
      type: Boolean,
      default: true
    },
    heightStr:{
      type:String
		},
		isShowScale: {
			type: Boolean,
			default: false
		}
  },
  computed: {
    model: {
      get () {
        return this.value
      }, 
      set (newVal) {
        this.$new = newVal
        this.$emit('input',newVal )
      }
		},
		mode() {
			return this.$store.state.Status.mode;
    },
    editorShow(){
      return !(this.chs || this.isShowScale) || !this.disabled || !this.model;
    },
    viewShow(){
			// 国内保函并且语言类型是英文或者国际保函;失焦;不显示pdf;富文本不禁用状态也就是非预览状态
      return ((this.isShowScale && !this.chs) || !this.isShowScale) && !this.focused && !this.disabled && this.model
    },
    pdfShow(){
      return this.model && (this.chs || this.isShowScale) && this.disabled
		}
  },
  data() {
    return {
      focused:false,
      colorText:"",
			tink:false,
			curScale: 1,
      curFontSize: '',
      errorDialogVisible:false
    };
  },
  methods: {
    getCharWidth(){
      if(!this.$refs.editor){
        return 0
      }
      return this.$refs.editor.getCharWidth()
    },
    viewClick(){
      if(this.disabled){
        return
      }
      let scroll = this.$refs.viewDiv.scrollTop
      this.focused = true
      this.$refs.editor.editor.focus()
      //同步滚动条
      this.$refs.editor.$el.getElementsByClassName("w-e-scroll")[0].scrollTop = scroll
      this.focusEvent()
    },
    blurEvent () {
      this.$editflg = 0
      this.focused = false
      this.colorText = this.filterChar(this.model)
      if(!this.isShowScale && this.colorText.indexOf('"color: red;') >= 0){
        this.errorDialogVisible = true
        this.$emit('blur')
        return
      }
      // this.model = this.colorText
      if(this.viewShow){
        this.$nextTick(()=>{
          if(this.$refs.viewDiv)
            this.$refs.viewDiv.scrollTop = this.$refs.editor.$el.getElementsByClassName("w-e-scroll")[0].scrollTop
        })
			}
			this.$emit('blur')
    },
    changeEvent () {
      if(!this.$editflg){
        return
      }
      if(this.disabled){
        return
      }
      if(this.$new == this.model){
        return;
      }
			this.$emit('change', this.model)
			if (!this.customModifykey) {
				// 添加isModify属性
				this.changeModify()
			}
    },
    focusEvent(){
      this.$editflg = 1
    },
    filterChar(valStr){
      // valStr = valStr.replace(/\<span style\="color: rgb\(216, 68, 147\);"\>([\s\S]*)\<\/span\>/g,function(match,g1){
      //   return g1
			// })
			console.log('valStr=======', valStr)
      if(this.chs){
        return valStr
      }
      let newVal = "";
      let begPos = -2;
      for(let i = 0;i<valStr.length;i++){
				let c = valStr.charAt(i)
				if (SWIFTZ_CHARS.indexOf(c) < 0) {
          newVal =  newVal + "<span style=\"color: red;font-weight: bold;border-bottom: 1px solid red;min-height:0.8em;min-width:0.8em;display:inline-block;\">" + c + "</span>"
				} else {
					newVal = newVal + c
				}
        // if(SWIFTZ_CHARS.indexOf(c)>=0){
        //   if(begPos >= 0){
        //     newVal = newVal+"</span>";
        //     begPos = -1
        //   }
        //   newVal = newVal + c
        // }else{
        //   if(begPos < 0){
        //     newVal =  "<span class=\"text_error_tip\">" + newVal
        //     begPos = i
        //   }
        //   newVal = newVal + c
        // }
      }
      // if(begPos >= 0){
      //   newVal = newVal+"</span>";
			// }
			newVal = newVal.replace(/<br>/g, `<div style="width: 100%;height: calc(${this.curFontSize} * 1.5);"></div>`)
      return newVal;
    },
    viewInPdfSrc:async function(){
      // this.viewPdfUrl = ""
        let res = await Api.post(`/business/gittxt/pdfView`, {
          htmlStr: this.model,
          title:  this.root.model && this.root.model.nitp && this.root.model.nitp.lettername ?this.root.model.nitp.lettername:"" ,
          ownref: this.root.model && this.root.model.nidgrp && this.root.model.nidgrp.rec && this.root.model.nidgrp.rec.ownref ?this.root.model.nidgrp.rec.ownref:"",
          quycod: this.root.model && this.root.model.nidgrp && this.root.model.nidgrp.rec && this.root.model.nidgrp.rec.quycod ?this.root.model.nidgrp.rec.quycod:"",
          cxmflg: this.root.model && this.root.model.nidgrp && this.root.model.nidgrp.rec && this.root.model.nidgrp.rec.cxmflg ?this.root.model.nidgrp.rec.cxmflg:"",
          giduil: this.root.model && this.root.model.nidgrp && this.root.model.nidgrp.rec && this.root.model.nidgrp.rec.giduil ?this.root.model.nidgrp.rec.giduil:"",
          smhinr: this.root.model && this.root.model.spt?this.root.model.spt.smhinr:"",

        });
        if (res.respCode === SUCCESS) {
          this.$viewPdfUrl = "data:application/pdf;base64,"+ res.data.data+"#toolbar=0&view=FitH,top"
          this.tink = true
        }
    },
    loadPdfView(){
      if(this.model && this.disabled && (this.chs || this.isShowScale)){
        this.tink = false
        this.viewInPdf()
      }
		},
		initViewDivWrapWidth () {
			if (this.isShowScale) {
				let contentWidth = document.body.clientWidth - 340
				if (contentWidth > 1588) {
					this.curScale = 2
				} else {
					this.curScale = contentWidth / 794
				}
				this.curFontSize = this.curScale * 18.6 + 'px'
			} else {
				let contentWidth = document.body.clientWidth - 440
				if (contentWidth > 1588) {
					this.curScale = 2
				} else {
					this.curScale = contentWidth / 794
				}
				this.curFontSize = '18.6px'
			}
    },
  },
  watch:{
    model(newVal,oldVal){
      if (newVal && !newVal.startsWith('<p>')) {
        this.model = '<p>' + newVal + '</p>'
      }
      if(!this.$refs.editor.editor.isFocused()){
        this.colorText = this.filterChar(this.model)
      }
      if(newVal == oldVal){
        return
      }
      this.loadPdfView()
    },
    disabled(newVal){
      this.loadPdfView()
      if (newVal) {
        this.resetValidate()
      }
		},
		chs () {
			this.loadPdfView()
			this.$nextTick(() => {
				this.initViewDivWrapWidth()
			})
    }
  },
  mounted(){
    this.loadPdfView()
		this.colorText = this.filterChar(this.model)
		
		this.$nextTick(() => {
			this.initViewDivWrapWidth()
			window.addEventListener('resize', this.initViewDivWrapWidth)
		})
  },
  created(){
    this.$viewPdfUrl=""
    this.viewInPdf = lodash.debounce(this.viewInPdfSrc,1000)
	},
	beforeDestroy() {
		window.removeEventListener('resize', this.initViewDivWrapWidth)
  }
};
</script>

<style lang="less" scoped>
  .el-dialog__wrapper.errorDialogTip{
    pointer-events: none;
  }
  .errorDialogTip /deep/ .el-dialog{
    pointer-events: auto;
  }

  .editor_view_div{
    width: 100%;
    background-color: white;
    border-left:1px solid #ccc;
    border-right:1px solid #ccc;
    border-bottom:1px solid #ccc;
    position:absolute;
		top:42px;
		left: 50%;
		transform: translate(-50%, 0);
		padding: 10px 0;
		margin: auto;
		.w-e-text-container {
			background: transparent;
			overflow: auto;
			height: 100%;
		}
		.view-scroll {
			font-family: '宋体';
			/deep/ p {
				font-family: '宋体';
      	word-break: break-word;
			}
		}
		.view-scroll-en {
			padding: 10px;
			font-family: "Times New Roman";
			/deep/ p {
				font-family: "Times New Roman";
			}
		}
		p br {
			width: 100%;
		}
    p:after{
      content: ' ';
      display: inline-block;
    }
  }
  
  .text_error_tip{
    color:red;
    font-size:1.3em;
    font-weight: bolder;
    text-decoration: underline;
	}
</style>