<template>
  <!--  <div v-html="iframeHtml"></div>-->
  <iframe
      id="iframe"
      ref="iframe"
      :srcdoc="iframeHtml"
      :style="{height}"
      width="100%"
  >
  </iframe>
</template>

<script>
import { writeIframe } from './print'

export default {
  name: 'html-report',
  inject: ['getToken', 'getSetting'],
  props: {
    uid: [String, Array],
    // 地址转换
    urlTransformation: [String, Array],
    // 签名
    autographSrc: [String],
    // 审核员签名
    reviewedSignedSrc: [String],
    height: [String],
    reportHideList: [Array],
  },
  watch: {
    uid: {
      handler (id) {
        const { host, hostSuffix, path } = this.getSetting()
        console.log('数据请求：', host + hostSuffix + path)
        // html 模板
        // console.log('id----',id)
        if (Object.prototype.toString.call(id) === '[object Array]') {
          this.objectStatus = 'Array'
          // console.log('数据为数组类型')
          for (let i = 0; i < id.length; i++) {
            this.iframeHtmlList.push('')
            this.getReportSrcDoc(host + hostSuffix + path + id[i], i)
          }
          console.log('this.iframeHtmlList----',this.iframeHtmlList)
        }
        if (Object.prototype.toString.call(id) === '[object String]') {
          this.objectStatus = 'String'
          // console.log('数据为字符串类型')
          this.getReportSrcDoc(host + hostSuffix + path + id)
        }
      },
      deep: true,
      immediate: true
    },
  },
  data () {
    return {
      objectStatus: '',
      iframeHtml: '',
      iframeHtmlList: [],
      gentleNumbr: 0
    }
  },
  methods: {
    // 打印事件
    print () {
      console.log('html- 打印')
      let $slot = this.$slots['footer-html']
      // let html_content = this.iframeHtml // 打印源码
      // 打印页面数据
      let html_document = document.getElementById('iframe').contentDocument || document.getElementById('iframe').contentWindow.document
      let html_content = html_document.documentElement.outerHTML
      if ($slot) {
        let footer = $slot[0].elm.innerHTML
        html_content = html_content.replace(/(?=<\/body>)/gm, footer)
      }
      let str = '.subject{box-shadow:none !important;margin-bottom:0px !important;'
      html_content = html_content.replace(/\.subject\{/g, str)
      writeIframe(html_content)
    },
    // 隐藏模块
    filterHideModule (html, index) {
      // Id:
      // 封面:gauge_cover
      // 标题:headerTitle
      // 标题图片:headerTitleImg
      // 基本信息:user
      // 量表简介:gauge_introduce
      // 筛查维度:gauge_dimension
      // 量表得分:gauge_score
      // 测评结果:gauge_conclusion
      // 图:mainChart
      // 表:gauge_surface
      // 测评分析:gauge_analysis
      // 指导意见:gauge_opinion
      // 预警等级:gauge_warning
      // 尾部:gauge_footer
      // 审核员签名:gauge_reviewedSigned
      // 原始答卷:gauge_answer

      let str = 'additionalJs(){'
      let html2
      for (let i = 0; i < this.reportHideList.length; i++) {
        if (this.reportHideList[i] != '') {
          let list = this.reportHideList[i]
          if (list.indexOf('ClassName') != -1) {
            str = str + `
              var ${list}List = document.getElementsByClassName('${list}')
              for(var i = ${list}List.length-1; i >= 0; i-- ){
                document.getElementsByClassName('${list}')[i].remove()
              }
              `
          } else {
            let obj = html.indexOf('id="' + list)
            if (obj != -1) {
              str = str + `
                document.getElementById('${list}').remove();
                `
            } else {
              // console.log('obj',obj,list)
            }
          }
        }
        
      }

      // console.log('签名处理str',str)
      html2 = html.replace(/additionalJs\(\){/g, str)
      if (this.objectStatus === 'Array') {
        // 多报告多图表,index索引值
        let obj = html.indexOf('id="mainChart"')
        if (obj != -1) {
          let str = 'mainChart' + index
          html2 = html2.replace(/mainChart/g, str)
          // console.log('多报告多图表html2', index, obj, str)
        }
      }

      // 显示边框
      if (this.showShadow) {
        let str2 = '.subject{box-shadow: 0px 4px 10px 0px rgb(0, 43, 110, 0.15);'
        html2 = html2.replace(/\.subject\{/g, str2)
      }
      // console.log('html2',html2)
      // 签名处理
      if (this.autographSrc) {
        let obj = html.indexOf('id="autographUrl" src=""')
        if (obj != -1) {
          let str3 = `id="autographUrl" src="${this.autographSrc}"`
          html2 = html2.replace(/id="autographUrl" src=""/g, str3)
        } else {
          console.log('签名处理obj', obj)
        }
      }
      // 审核员签名处理
      if (this.reviewedSignedSrc) {
        let obj = html.indexOf('id="reviewedSigned" src=""')
        if (obj != -1) {
          let str3 = `id="reviewedSigned" src="${this.reviewedSignedSrc}"`
          html2 = html2.replace(/id="reviewedSigned" src=""/g, str3)
        } else {
          console.log('审核员签名处理obj', obj)
        }
      }
      // console.log('多报告多图表html2',html2,html2)
      // 显示下载、打印按钮
      this.$emit('refreshOperation', true, '10px')
      return html2
    },
    // 数据请求，获取报告参数
    async getReportSrcDoc (url, index) {
      let _this = this
      this.$tool.request({
        url: url,
        headers: {
          // Authorization: await this.getToken(),
          way: 1
        },
        method: _this.getSetting().method,
        params: {}
      }).then(res => {
        if (res.code == 200) {
          _this.base64Fun(res.data, index)
        } else {
          this.$emit('error', res)
        }
      }).catch(err => {
        _this.$emit('error', err)
      })
    },
    // base64转换，调用源码处理
    base64Fun (data, index, backHtmlStatus) {
      let html = this.$tool.Base64.decode(data)
      html = this.filterHideModule(html, index)
      if(this.objectStatus === 'Array'){
        this.iframeHtmlList[index] = html
        this.gentleNumbr ++
        this.sequentialProcessing(backHtmlStatus)
        // console.log('base64转换，调用源码处理:index---',index,'this.gentleNumbr',this.gentleNumbr,'this.iframeHtmlList',this.iframeHtmlList)
      }else{
        if (backHtmlStatus) {
          // 是否需要返回源码
          this.$emit('backHtml', html)
        } else {
          this.iframeHtml = this.iframeHtml + html
        }
      }
      
    },
    // 多报告数据顺序处理
    sequentialProcessing(backHtmlStatus){
      
      if(this.gentleNumbr === this.iframeHtmlList.length){
        console.error("已处理完毕")
        for(let i=0;i<this.iframeHtmlList.length;i++){
          this.iframeHtml = this.iframeHtml + this.iframeHtmlList[i]
          
        }
        if (backHtmlStatus) {
          // 是否需要返回源码
          this.$emit('backHtml', this.iframeHtml)
        }
      }
    },
    // 源码转换
    urlTransformationFun () {
      let url = this.urlTransformation
      if (url) {
        if (Object.prototype.toString.call(url) === '[object Array]') {
          this.objectStatus = 'Array'
          // console.log('数据为数组类型')
          for (let i = 0; i < url.length; i++) {
            this.base64Fun(url[i], i, true)
          }
        }
        if (Object.prototype.toString.call(url) === '[object String]') {
          this.objectStatus = 'String'
          // console.log('数据为字符串类型')
          this.base64Fun(url, 0, true)
        }
      }
    },
    // 清理数据
    clearHtml () {
      // this.iframeHtml = ''
    }
  }
}
</script>

<style scoped>

</style>
