<template>
  <div
    :class="'flexYbox box height100 '+(isBigScreen_&&isShowBigScreen?'bigScreen-con':'')"
    :style="{background:'var(--light-back-grey)'}"
  >
    <tsButton
      ref="designBtn"
      class="design-btn"
      icon="iconfont icon-guihuasheji"
      @click="onDesignBi"
      v-if="isFromPreview&&(config.biOutDesign||biOutDesign)&&!isFromList&&(sysRoleCode.indexOf(platSysRoleColde)>-1||sysRoleCode.indexOf(superSysRoleColde)>-1)"
    >设计</tsButton>
    <tsButton
      ref="designBtn"
      :class="'design-btn'"
      icon="iconfont icon-screenfull"
      @click="setScreenFull(true)"
      v-if="isBigScreen_&&!isShowBigScreen"
      :style="isFromPreview&&(config.biOutDesign||biOutDesign)&&menuType=='top'?'right:72px':(!isFromList&&isFromPreview?'top:45px;right:35px':'top:8px;right:35px')"
    >进入大屏</tsButton>
    <!-- 主模块区域 -->
    <div
      :class="'height100 flex preview_container '+(isFromPreview&&(config.biOutDesign||biOutDesign)&&type!='pivot'?'form_preview_con':'')"
      :style="{width:ancherList.length>0?'calc(100% - 120px)':'100%'}"
    >
      <div v-if="type === 'bigScreen'">
        <div class="biUserDefined-item__operate font16" v-if="!isShowBigScreen">
          <span @click="setScreenFull(true)" class="iconfont icon-screenfull"></span>
        </div>
        <dv-full-screen-container v-if="isShowBigScreen">
          <div class="biUserDefined-item__operate font16">
            <span @click="setScreenFull(false)" class="iconfont icon-error"></span>
          </div>
          <Editor :isEdit="false" :bigScreenNatureList="bigScreenNature" />
        </dv-full-screen-container>
        <Editor v-else :isEdit="false" :bigScreenNatureList="bigScreenNature" />
      </div>
      <div
        v-else-if="type == 'pivot'"
        v-show="isShowPivotTableEditor"
        :style="{padding:isFromList?'8px':0,height:isFromList?'calc(100% - 16px)':'100%',background:'white'}"
      >
        <pivot-table-editor :oldData_="oldData" :onPreview="true" :isAdd_="false" />
      </div>
      <template v-else-if="finalNatureArr.length>0">
        <div :class="'height100 '+(isShowBigScreen?'full-screen-con':'')">
          <div
            class="biUserDefined-item__operate"
            v-if="isShowBigScreen"
            @click="setScreenFull(false)"
          >
            <span class="iconfont icon-Group-21 font20"></span>
            <span class="font14">退出</span>
          </div>
          <grid-main-layout
            ref="gridMainLayout"
            :key="'preview'"
            :layoutList="finalNatureArr"
            :isDraggable="false"
            :isResizeable="false"
            :isEditable="false"
            @refreshData="refreshData"
            @interData="interData"
            :formId="paramId_"
            :isFromList="isFromList"
            :isHeightFit="isHeightFit_"
            @changeYH="changeYH"
            :isShowBigScreen="isShowBigScreen"
          ></grid-main-layout>
        </div>
        <!-- <grid-main-layout
          v-else
          ref="gridMainLayout"
          :key="'preview'"
          :layoutList="finalNatureArr"
          :isDraggable="false"
          :isResizeable="false"
          :isEditable="false"
          @refreshData="refreshData"
          @interData="interData"
          :formId="paramId_"
          :isFromList="isFromList"
          :isHeightFit="isHeightFit_"
          @changeYH="changeYH"
        ></grid-main-layout>-->
      </template>
    </div>
    <biEditor
      ref="biEditor"
      :isFromPreview="isFromPreview"
      :formId="paramId_"
      v-if="isFromPreview&&!isFromList"
    />
    <!-- 锚点 -->
    <div
      style="width:118px;overflow:hidden;position:fixed;right:0;top:150px;"
      v-if="ancherList.length>0"
    >
      <div
        class="ancher_item"
        :class="{ancher_active:itemIndex==index}"
        @click="clickAncher(item,index)"
        v-for="(item,index) in ancherList"
        :key="index"
      >
        <div class="ball"></div>
        <!-- <div class="ball2"></div> -->
        {{item.name}}
      </div>
    </div>
    <diaLog :source="layObj" ref="tableDialog" :key="layObj.title" type="right">
      <div style="width:100%;display:flex;height:30px;align-items:center;">
        <div class="crumb_box">
          <div
            class="crumb_style"
            v-for="(item,index) in breadcrumbList"
            :key="item.paramValue+index"
            @click="goBack(item,index)"
          >
            <div>{{item.paramValue}}</div>
            <i v-if="index!=breadcrumbList.length-1" class="iconfont icon-Group-3"></i>
          </div>
        </div>
        <ts-button type="button" icon="iconfont icon-daochu" class="fr" @click="exportExcel()">导出</ts-button>
      </div>
      <div style="height:calc(100% - 32px);">
        <ts-table
          v-if="openDialog"
          ref="tsTable"
          row-key
          :source="sourceRealFn(this.tableData,this.colModel)"
          width="100%"
          height="100%"
          @cellClick="cellClickEvent(arguments)"
        ></ts-table>
      </div>

      <!-- //文本弹窗/ -->
    </diaLog>
    <diaLog
      type="right"
      :cover="false"
      :source="showTextSource"
      width="40%"
      height="500"
      ref="showText"
    >
      <div class="height100" style="box-sizing: border-box;padding:5px;">{{showText}}</div>
      <!-- <json-viewer :value="log.content"></json-viewer> -->
    </diaLog>
  </div>
</template>

<script>
import pivotTableEditor from './pivotTable/pivotTableEditor'
import XEUtils from 'xe-utils'
import gridMainLayout from './components/gridLayout/gridMainLayout'
import previewMixins from './components/mixins/previewMixins'
import natureArrMixins from './components/mixins/natureArrMixins'
import screenfull from 'screenfull'
import _ from 'lodash'
import biEditor from './biEditor'
export default {
  name: 'biPreviewForm',
  mixins: [previewMixins, natureArrMixins],
  components: { gridMainLayout, pivotTableEditor,biEditor },
  props: {
    biCustom: {},
    paramId: {
      type: String,
      default: ''
    },
    biType: {
      type: String,
      default: ''
    },
    isFromList: {
      // 是否从列表进入
      type: Boolean,
      default: false
    },
    biOutDesign:{
      type:Boolean,
      default:false// 是否启动外部设计
    },
    isBigScreen: {
      // 是否具备大屏功能
      type: Boolean,
      default: false
    },
    isFromPreview: {
      // 是否来自外部预览
      type: Boolean,
      default: false
    },
    isHeightFit: {
      // 是否高度适配
      type: Boolean,
      default: true
    },
    versionCode: {
      type: String,
      default: ''
    },
    displayMode: {
      type: String,
      default: ''
    },
    systemConfig:{ // 系统配置
      type:Object,
      default:()=>{
        return {}
      }
    }
  },
  data() {
    return {
      menuType:this.systemConfig.menuType,
      isShowPivotTableEditor: true, //是否显示透视表
      sysRoleCode: global.userInfo?global.userInfo.sysRoleCode : '',
      platSysRoleColde:window.platSysRoleColde,
      superSysRoleColde: window.superSysRoleColde,
      isBigScreen_: this.isBigScreen, // 是否大屏功能
      isHeightFit_: this.isHeightFit,
      itemIndex: 0,
      ancherList: [],
      config: this.systemConfig,
      parameters: '',
      type: this.biType,
      showText: '',
      showTextSource: {
        title: '详情'
      },
      paramData: {}, //参数
      breadcrumbList: [],
      colModel: [],
      openDialog: false,
      tableData: [],
      layObj: {
        width: '100%', // 宽
        height: '100%', // 高
        closeBtn: true,
        title: '预览'
      },
      newBiCustom: this.biCustom,
      screenData: [],
      // screenData: _.cloneDeep(this.$store.state.bi.screenData),
      natureArr: this.isFromPreview
        ? []
        : _.cloneDeep(
            this.$store.state.bi.natureArr[
              'd' + (this.$store.state.bi.dialogEditors.length - 1)
            ]
          ) || [],
      finalNatureArr: [],
      bigScreenNature: _.cloneDeep(this.$store.state.bi.bigScreenNature),
      isShowBigScreen: false, // 是否显示大数据全屏
      isMenu: false,
      isMergeMenu: false,
      // dialogEditors: [], // 设计区弹框
      // oldDataList: [], //旧数据
      oldData: {},
      paramId_: this.paramId,
      showEditor: false
    }
  },
  created() {
    this.menuType = localStorage.getItem('menuTypeNew') || this.menuType
  },
  activated() {
    this.$nextTick(() => {
      window.dispatchEvent(new Event('resize'))
    })
  },
  mounted() {
    this.$nextTick(() => {
      window.dispatchEvent(new Event('resize'))
    })
    if (this.type === 'bigScreen') {
      screenfull.on('change', this.changeScreenFull)
    }
    this.$on('openTable', this.openTable) //接受打开子表格的方法
    //  this.$eventBus.$on('interData', this.interData) //接受打开子表格的方法
    this.$eventBus.$on('openTable', this.openTable) //接受打开子表格的方法
    this.$eventBus.$on('openDialog', this.openTextDialog) //接受打开子表格的方法
    this.$eventBus.$on('initServeData', this.initServeData)

    if (this.isFromPreview) {
      // 是否来自预览
      // 去设计情况下
      this.$eventBus.$on('refreshPreview', this.refreshPreview) // 刷新预览数据
    }
    if (this.$route.query && this.$route.query.type == 'physical') {
      return
    }
    if (
      this.isFromPreview &&
      (this.paramId_ || (this.$route.query && this.$route.query.mid))
    ) {
      // 真实菜单进入
      if (this.$route.query && this.$route.query.mid) {
        this.paramId_ = this.paramId_ || this.$route.path.substring(14)
      }
      this.initMenuServeData(this.paramId_)
    } else {
      if (this.type === 'bigScreen') {
        this.createTimer()
        this.refreshBigData()
      } else {
        this.refreshAllData()
      }
    }
  },
  methods: {
    // 改变旧版y和h
    changeYH(natureArr) {
      this.finalNatureArr = natureArr
      // this.$store.commit('setNatureArr', [...this.natureArr])
    },
    clickAncher(item, index) {
      //
      // if (index == this.itemIndex) {
      //   return
      // }
      this.itemIndex = index
      document.getElementsByClassName('_con')[0].scrollTop =
        document.getElementsByClassName('_con')[0].scrollTop +
        document.getElementById(item.id).getBoundingClientRect().top -
        120
    },
    // 进入设计区
    onDesignBi() {
      this.showEditor = true
      this.$nextTick(() => {
        if (this.oldData && this.oldData.length > 0) {
          this.$refs.biEditor.openDesignDialog({
            bid: this.paramId_,
            bTitle: this.oldData[0].designName,
            versionCode: this.oldData[0].versionCode,
            displayMode: this.oldData[0].displayMode
          })
        }
      })
    },
    // 刷新自定义报表
    refreshPreview(param) {
      this.showEditor = false
      
      this.initMenuServeData(this.paramId_)
    },
    // 设置是否全屏
    setScreenFull(isShowBigScreen) {
      screenfull.toggle()
      this.isShowBigScreen = isShowBigScreen
    },
    changeScreenFull() {
      if (!screenfull.isFullscreen) {
        this.$nextTick(() => {
          this.isShowBigScreen = false
        })
      }
    },
    exportExcel() {
      const _this = this
      let data = JSON.parse(JSON.stringify(_this.paramData))
      this.$api({
        url: '/ts-query/api/user/query/table/export/excel',
        method: 'post',
        data: data,
        responseType: 'blob'
      })
        .then(function(res) {
          // 请求成功
          let blob = res.data
          if (blob.size > 0) {
            let reader = new FileReader()
            reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
            reader.onload = function(e) {
              // 转换完成，创建一个a标签用于下载
              let a = document.createElement('a')
              a.download = new Date().getTime() + '.' + 'xls'
              a.href = e.target.result
              document.body.appendChild(a)
              a.click()
              a.remove()
            }
          }
        })
        .catch(function(error) {
          // 请求失败
        })
    },
    goBack(item, index) {
      if (index < this.allTableData.length) {
        if (index < this.breadcrumbList.length - 1) {
          this.getDataSource([this.breadcrumbList[index]])
          this.breadcrumbList = this.breadcrumbList.slice(0, index + 1)
        }
      }
    },
    cellClickEvent(args) {
      let value = args[0][args[1].property]
      if (this.breadcrumbList.length < this.allTableData.length) {
        if (
          args[1].property ==
          this.breadcrumbList[this.breadcrumbList.length - 1].targetField
        ) {
          this.breadcrumbList = this.allTableData.slice(
            0,
            this.breadcrumbList.length + 1
          )
          this.breadcrumbList[
            this.breadcrumbList.length - 1
          ].paramValue = value.toString().trim()
          this.getDataSource([
            this.breadcrumbList[this.breadcrumbList.length - 1]
          ])
        }
        if (
          args[1].property ==
          this.breadcrumbList[this.breadcrumbList.length - 1].textField
        ) {
          this.openTextDialog(value)
        }
      } else {
        this.$utils.msg(this, '已无子表')
      }
    },
    openTextDialog(value) {
      this.showText = value
      this.$refs.showText.open()
    },
    openTable(data, value) {
      if (value == '合计') {
        return
      }
      if (this.dataSourceUrls.length > 0) {
        this.dataSourceUrls.forEach((res, index) => {
          if (res.item.type == 'table') {
            this.parameters = res.data.parameters
          }
        })
      }
      this.allTableData = [...data]
      this.allTableData[0].paramValue = value.toString().trim()
      this.breadcrumbList = this.allTableData.slice(0, 1)
      this.$refs.tableDialog.open()
      this.openDialog = true
      this.getDataSource(this.breadcrumbList, value)
      // setTimeout(()=>{
      //     this.$eventBus.$off('openTable', this.openTable)
      //    this.$eventBus.$off('openDialog', this.openTextDialog)
      // },1000)
    },
    // 得到所有的数据源url
    getDataSource(crumb) {
      let allfield = crumb[0].selectData
      let formatterFn = function({ cellValue, row, column }) {
        return cellValue
      }
      this.colModel = []
      for (let col of allfield) {
        if (col.filter == 1) {
          //千分位
          formatterFn = function({ cellValue, row, column }) {
            return XEUtils.commafy(parseFloat(cellValue), { digits: 2 })
          }
        } else if (col.filter == 2) {
          //年月日
          formatterFn = function({ cellValue, row, column }) {
            return XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
          }
        } else if (col.filter == 3) {
          //年月日时分秒
          formatterFn = function({ cellValue, row, column }) {
            return XEUtils.toDateString(cellValue, 'yyyy-MM-dd HH:mm:ss')
          }
        } else if (col.filter == 4) {
          //保留两位小数
          formatterFn = function({ cellValue, row, column }) {
            return Number(cellValue).toFixed(2)
          }
        } else {
          formatterFn = function({ cellValue, row, column }) {
            return cellValue
          }
        }
        if (
          (crumb[0].targetField && crumb[0].targetField == col.field) ||
          crumb[0].textField == col.field
        ) {
          this.colModel.push({
            formatter: formatterFn,
            title: col.title,
            field: col.field,
            width: col.width,
            align: col.align,
            hasClick: true
          })
        } else {
          this.colModel.push({
            formatter: formatterFn,
            title: col.title,
            field: col.field,
            width: col.width,
            align: col.align
          })
        }
      }
      // SQL与存储过程分开处理
      let parameters = [
        { name: crumb[0]['targetParam'], value: crumb[0]['paramValue'] }
      ]
      let rootParameters = JSON.parse(this.parameters)
      let finalParameters = [...parameters, ...rootParameters]
      let url = '/ts-query/api/user/query/table/query'
      let data = {
        id: crumb[0].targetDataSource,
        pageSize: 3000,
        pageNo: 1,
        parameters: JSON.stringify(finalParameters)
      }
      this.paramData = data
      this.$api({
        method: 'post',
        url: url,
        data: data,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
        }
      })
        .then(res => {
          this.tableData = res.rows
        })
        .catch(error => {
          this.$utils.msg(this, error.message)
        })
    },
    // 列表配置
    sourceRealFn(item, colModel) {
      let sourceRealFn = {
        rownumbers: true,
        dataType: 'local',
        pageSize: 100,
        data: item,
        offPage: false,
        showOverflow: true,
        colModel: colModel
      }
      // mergeCells.push({ row: 0, col: 1, rowspan: 1, colspan: 2 }) //这个获取数据的长度赋值
      return sourceRealFn
    },
    // 清空sse
    clearEventSource() {
      console.warn('清除监听:',this.eventSources)
      if (this.eventSources.length > 0) {
        // 关闭sse
        for (let source of this.eventSources) {
          source.close()
        }
        this.eventSources = []
      }
    }
  },
  watch: {
    oldData: {
      handler(n) {
        if (n && n.length > 0) {
          this.isBigScreen_ =
            (this.oldData[0].other &&
              JSON.parse(this.oldData[0].other).isBigScreen) ||
            false
          this.isHeightFit_ =
            (this.oldData[0].other &&
              JSON.parse(this.oldData[0].other).isHeightFit) ||
            false
        }
      },
      deep: true
    }
  },
  deactivated() {
    this.clearEventSource()
  },
  destroyed() {
    // this.$eventBus.$off('interData', this.interData)
    this.$eventBus.$off('openTable', this.openTable)
    this.$eventBus.$off('openDialog', this.openTextDialog)
    this.$eventBus.$off('initServeData', this.initServeData)
    if (this.isFromPreview) {
      // 去设计情况下
      this.$eventBus.$off('refreshPreview', this.refreshPreview) // 刷新预览数据
      // this.$eventBus.$off('openDesignDialog', this.openDesignDialog)
    }
    screenfull.off('change', this.changeScreenFull)
    this.clearEventSource()
  }
}
</script>
<style lang="less" scoped>
@import url('./assets/css/bigScreen.less');
.ancher_item {
  cursor: pointer;
  margin: 0 10px;
  // text-indent: 1em;
  padding-left: 1em;
  position: relative;
  height: 40px;
  line-height: 40px;
  font-size: 12px;
  border-left: 1px solid #444;
}
.ancher_active {
  color: #0079fb;
}
.ancher_active .ball {
  position: absolute;
  left: -5px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 999;
  content: '';
  width: 9px;
  height: 9px;
  border-radius: 50%;
  background: #0079fb;
  animation: ani 2s linear infinite;
}
@keyframes ani {
  0% {
    box-shadow: 0 0 0px #3795facb;
  }
  25% {
    box-shadow: 0 0 10px #5ba4f1;
  }
  50% {
    box-shadow: 0 0 0px #4f9ef1;
  }
  75% {
    box-shadow: 0 0 10px #53a4fa;
  }
  100% {
    box-shadow: 0 0 0px #52a2f7;
  }
}
.ancher_item:hover {
  color: #0079fb;
}
.crumb_box {
  height: 30px;
  display: flex;
  align-items: center;
  width: calc(100% - 80px);
  padding: 0 0 0 10px;
}
.crumb_style {
  display: flex;
  align-items: center;
  div {
    cursor: pointer;
    padding: 0 5px 0 5px;
    font-size: 13px;
  }
  div:hover {
    color: var(--base-acv);
  }
}
.design-btn {
  position: fixed;
  top: 86px;
  right: 8px;
}
.screen-btn {
  position: fixed;
  top: 90px;
  right: 20px;
}
.form_preview_con {
  top: -7px !important;
}
.preview_container {
  // .laybox-dialog__box {
  //   padding: 0;
  //   height: 100% !important;
  // }
  position: absolute;
  width: 100%;
  top: 0px;
  left: 0;
  /deep/.form__title {
    width: auto;
  }
  .biUserDefined-item__operate {
    position: absolute;
    top: 0px;
    right: 0px;
    z-index: 199;
    padding: 3px;
    margin-right: 5px;
    display: flex;
    span {
      border-radius: 15px;
      cursor: pointer;
      font-weight: 400;
      color: #02d9fd;
      line-height: 30px;
      height: 25px;
    }
    .icon-Group-21 {
      font-weight: bold;
      margin-right: 3px;
    }
  }
}
</style>
