<template>
  <div class="biUserDefinedForm-add__con">
    <div class="flexYbox box height100">
      <!-- 工具栏 -->
      <!-- <topbar @topBarOptClick="topBarOptClick" @dragstart="dragstart" @dragend="dragend"></topbar> -->
      <tsTopBar @topBarOptClick="topBarOptClick">
        <div slot="after" class="preview">
          <ts-select
            :source="nowVersionCodeSource"
            v-model="nowVersionCode"
            title="当前版本:"
            @selected="changeNowVersion"
          ></ts-select>
          <ts-switch
            name="isBigScreen"
            off-label="否"
            on-label="是"
            title="开启大屏"
            v-model="isBigScreen"
            width="50%"
            :key="'isBigScreen'+nowVersionCode"
          />
          <ts-switch
            off-label="否"
            on-label="是"
            title="高度固定"
            title-width="auto"
            v-model="allHPosition"
            @change="changeHPosition($event)"
            :key="'allHPosition'+nowVersionCode"
          >
            <tsPopover slot="title">
              注：全局设置高度比；
              <br />默认为浏览器的相对高度，用于高度等比功能，自动填充等；
              <br />开启后，高度为固定值，不可根据浏览器变化而变化
            </tsPopover>
          </ts-switch>
        </div>
      </tsTopBar>
      <!-- 工具栏 end -->
      <!-- 画布 -->
      <div class="flex biUserDefinedIconDrag__view flexYbox" ref="biUserDefinedIconDragViewBox">
        <!-- 主模块区域 -->
        <div
          class="biUserDefinedIconDrag-view__con biUserDefined-itemcon__box flex"
          ref="biUserDefinedIconDragView"
          @click="gridMainClick"
          @dragover="dragOver"
          @drop="dropHandler"
          @dragenter="dropEnterHandler"
        >
          <!-- 标尺辅助线 -->
          <ts-row class="ruler__handle" type="flex" v-if="!isDragEnd&&this.dragType != 'target'">
            <ts-col :flex="1" class="ruler_item" v-for="(i,index) of 6" :key="index"></ts-col>
          </ts-row>
          <grid-main-layout
            v-if="!isHideMainLayout"
            :layoutList="natureArr||[]"
            ref="gridMainLayout"
            biModel="custom"
            :isDraggable="true"
            :isEditable="true"
            :isResizeable="true"
            :isHeightFit="isHeightFit"
            @changeYH="changeYH"
          ></grid-main-layout>
        </div>
      </div>
      <!-- 画布 end -->
      <diaLog :source="layObj" ref="biSaveDialog" type="right">
        <bi-save ref="biSave" @saveClick="saveClick" biModel="custom" :isPublish="isPublish"></bi-save>
      </diaLog>
      <diaLog
        :source="layObj"
        ref="previewDialog"
        @hide="hide"
        :width="layObj.width"
        :height="layObj.height"
      >
        <biPreviewForm
          :biCustom="biCustom"
          ref="biPreview"
          :isBigScreen="isBigScreen"
          :isHeightFit="true"
        ></biPreviewForm>
      </diaLog>
      <diaLog :source="versionNoteSource" ref="versionNote" :offCloseBtn="true">
        <ts-textarea
          v-model="versionNoteInfo"
          style="padding:6px;width:calc(100% - 12px);height:calc(100% - 20px)"
        ></ts-textarea>
      </diaLog>
    </div>
  </div>
</template>

<script>
// import biSave from './biDialog/biSave'
import gridMainLayout from './gridLayout/gridMainLayout'
import submitMixins from './mixins/submitMixins'
import dragEventMixins from './mixins/dragEventMixins'
import dragColMixins from './mixins/dragColMixins'
import biSave from './biDialog/biSave'
// import dragScreenMixins from './mixins/dragScreenMixins'
import _ from 'lodash'
export default {
  name: 'definedCenterEditor',
  components: { gridMainLayout,biSave },
  mixins: [dragEventMixins, dragColMixins, submitMixins],
  props: {
    isAdd: {
      type: Boolean,
      default: true
    },
    oldDatas: {
      type: Array,
      default: () => {
        return []
      }
    },
    versionDatas: {
      type: Array,
      default: () => {
        return []
      }
    },
    biCustom: {}
  },
  data() {
    return {
      allHPosition: false,
      isFromEventBusHP: false, //来自于eventBus的修改
      oldData: this.oldDatas,
      screenData: [],
      natureArr: [],
      biModel: 'custom',
      type: '',
      showDialogType: '',
      layObj: {},
      isBack: false,
      isBigScreen: false, //开启大屏模式
      isHeightFit: true, // 是否高度适配：只有旧版的报表不具备高度适配功能，故只有oldData的isHeightFit为空时为false，新保存的都为true
      isPublish: false, //是否发布
      nowVersionCode: '', // 当前版本
      draging: false,
      isDragEnd: true, // 是否拖拽结束
      isHideMainLayout: false, // 是否隐藏MainLayout
      versionNoteInfo: '', //版本说明
      versionNoteSource: {
        title: '版本说明', // 标题
        width: '400px', // 宽
        height: '150px', // 高
        offCloseBtn: false, // 关闭按钮区域，boolean 默认：false
        // 按钮
        buttons: [
          {
            text: '确认',
            event: this.handleSave
          }
        ]
      }
    }
  },
  computed: {
    nowVersionCodeSource() {
      return {
        dataType: 'local',
        code: 'versionCode',
        text: 'versionCode',
        data: this.versionDatas,
        // isReq: true,
        value: {
          name: this.nowVersionCode || '草稿',
          code: this.nowVersionCode
        }
      }
    }
  },
  created() {},
  mounted() {
    this.initViewData()
    this.natureArr =
      _.cloneDeep(
        this.$store.state.bi.natureArr[
          'd' + (this.$store.state.bi.dialogEditors.length - 1)
        ]
      ) || []
    this.$eventBus.$on('resetOtherActive', this.resetOtherActive)
    this.$eventBus.$on('optDel', this.optDel)
    this.$eventBus.$on(
      'changeAllPosition' +
        (this.oldData && this.oldData.length > 0 ? this.oldData[0].id : ''),
      this.changeAllPosition
    )
  },
  methods: {
    // 初始化数据
    initViewData() {
      if (this.oldDatas && this.oldDatas.length > 0) {
        // 初始化当前版本
        this.nowVersionCode =
          this.oldDatas && this.oldDatas.length > 0
            ? this.oldDatas[0].versionCode
            : '草稿'
        if (this.oldDatas[0].other != 'null') {
          this.isBigScreen =
            (this.oldDatas[0].other &&
              JSON.parse(this.oldDatas[0].other).isBigScreen) ||
            false
          this.isHeightFit =
            (this.oldDatas[0].other &&
              JSON.parse(this.oldDatas[0].other).isHeightFit) ||
            false
        }
      }
    },
    //更改版本号
    changeNowVersion(row) {
      this.$nextTick(() => {
        this.$emit('loadVersionData', row.versionCode)
      })
    },
    // 改变旧版y和h
    changeYH(natureArr) {
      this.natureArr = natureArr
      this.$store.commit('setNatureArr', [...this.natureArr])
    },

    topBarOptClick(item) {
      let validate = ''
      switch (item.title) {
        case '保存并退出':
        case '保存':
          // console.log('screenData', this.screenData)
          // // console.log('screenData', JSON.stringify(this.screenData))
          // console.log('biCustom', JSON.stringify(this.biCustom))
          // console.log('natureArr', this.natureArr)
          // console.log('natureArr', JSON.stringify(this.natureArr))
          // 先验证
          validate = this.validateAllItem()
          if (validate) {
            this.$utils.msg(this, validate)
            validate = ''
            return false
          }
          this.isBack = item.isBack
          this.isPublish = false
          // this.resetBusinessNatureArr(this.natureArr,bid,versionCode)
          if (
            this.$store.state.bi.isBIAdd[
              'd' + (this.$store.state.bi.dialogEditors.length - 1)
            ]
          ) {
            // 新增
            this.layObj = this.layObjFn('add')
            this.$refs.biSaveDialog.open()
          } else {
            this.saveClick({ type: 'edit' }) // 编辑
          }
          break
        case '删除':
          this.optDel()
          break
        case '清空画布':
          this.clearCanvas()
          break
        case '预览':
          this.layObj = this.layObjFn('preview')
          this.$store.commit('setNatureArr', [...this.natureArr])
          this.$refs.previewDialog.open()
          break
        case '保存并发布':
          // 先验证
          validate = this.validateAllItem()
          if (validate) {
            this.$utils.msg(this, validate, 'warning')
            validate = ''
            return false
          }
          if (
            this.$store.state.bi.isBIAdd[
              'd' + (this.$store.state.bi.dialogEditors.length - 1)
            ]
          ) {
            // 新增
            this.layObj = this.layObjFn('add')
            this.isPublish = true
            this.$refs.biSaveDialog.open()
          } else {
            // 编辑
            this.$refs.versionNote.open()
          }
          break
      }
    },
    // 清空画布
    clearCanvas() {
      this.$store.commit('setSelectData', {})
      this.$store.commit('setNatureArr', [])
    },
    // 保存并发布
    handleSave() {
      this.isPublish = true
      this.saveClick({ type: 'edit' }) // 编辑
      let _this = this
      setTimeout(() => {
        _this.$refs.versionNote.close()
      }, 300)
      // this.requestSave(
      //   param,
      //   '/ts-plat-cfg/version/createAndActive',
      //   true,
      //   preParam
      // )
    },
    //修改高度固定比状态
    changeAllPosition(isAllPosition) {
      this.$nextTick(() => {
        this.allHPosition = isAllPosition
        this.isFromEventBusHP = true
        this.$forceUpdate()
      })
    },
    //删除控件
    optDel(item) {
      let selectData = item || this.$store.state.bi.selectData
      if (Object.keys(selectData).length === 0) {
        this.$utils.msg(this, '未选择可删除的控件', 'warning')
        return false
      }
      if (selectData.type == 'col') {
        this.$eventBus.$emit('deleteCol', selectData) //可以删除列
      } else {
        let removeId = selectData.id
        let isRemoved = this.deleteNatureArrByid(this.natureArr, removeId)
        if (isRemoved) {
          this.$eventBus.$emit('itemselectchange', {
            target: {},
            select: false
          })
          this.$store.commit('setSelectData', {})
          this.$store.commit('setNatureArr', [...this.natureArr])
        }
      }
      // }
      return false
    },
    hide() {
      this.showDialogType = ''
    },
    // 弹窗属性
    layObjFn(type) {
      this.showDialogType = type
      let d = {
        title: '', // 标题
        width: '100%', // 宽
        height: '100%', // 高
        closeBtn: false // 关闭按钮区域，boolean 默认：false
      }
      if (type === 'preview') {
        d.title = '预览'
        d.closeBtn = true
      } else if (type === 'add') {
        d.title = '保存'
        d.width = '500'
        d.height = '200'
        d.buttons = [{ text: '确认', event: this.formVerify }]
      }
      return d
    },
    // 表单验证触发
    formVerify() {
      this.$refs.biSave.$refs.xForm.submit()
      // this.$refs.biSave.$refs.submit.$el.click()
    },
    // // 清空业务组件内控件
    // resetBusinessNatureArr(natureArr, bid, versionCode) {
    //   for (let item of natureArr) {
    //     if (
    //       item.type == 'business' &&
    //       item.bid == bid &&
    //       item.versionCode == versionCode
    //     ) {
    //       item.natureArr = [] // 替换
    //     } else if (item.type === 'tab') {
    //       for (let tab of item.tabs) {
    //         this.resetBusinessNatureArr(tab.natureArr, bid, versionCode)
    //       }
    //     } else if (item.type === 'panel') {
    //       this.resetBusinessNatureArr(item.natureArr, bid, versionCode)
    //     }
    //   }
    // },
    //通过下标删除控件（含tab的情况）
    deleteNatureArrByid(natureArr, id) {
      for (let i = 0; i < natureArr.length; i++) {
        if (natureArr[i].id === id) {
          natureArr.splice(i, 1)
          return true
        } else {
          if (natureArr[i].type === 'tab') {
            for (let tab of natureArr[i].tabs) {
              if (tab.index == natureArr[i].activeIndex) {
                if (this.deleteNatureArrByid(tab.natureArr, id)) {
                  return true
                }
              }
            }
          } else if (natureArr[i].type === 'panel') {
            // 删除面板里面的值
            if (this.deleteNatureArrByid(natureArr[i].natureArr, id)) {
              return true
            }
          }
        }
      }
      return false
    },
    // 递归清除高亮
    clearHanderClass(boxDom) {
      for (let child of Object.keys(boxDom)) {
        if (boxDom[child].length > 0) {
          let tsTable = boxDom[child][0].$refs.tsTable
          if (tsTable) {
            let tc = tsTable.getTableColumn()
            this.resetHeaderClass(tc.collectColumn)
          }
          if (boxDom[child][0].$refs.tabMainLayout) {
            if (boxDom[child][0].$refs.tabMainLayout.length) {
              //假如ref有多个是个数组
              for (
                let i = 0;
                i < boxDom[child][0].$refs.tabMainLayout.length > 0;
                i++
              ) {
                if (boxDom[child][0].$refs.tabMainLayout.$refs) {
                  this.clearHanderClass(
                    boxDom[child][0].$refs.tabMainLayout.$refs
                  )
                } else {
                  this.clearHanderClass(
                    boxDom[child][0].$refs.tabMainLayout[i].$refs
                  )
                }
              }
            } else {
              //ref 单个为对象
              if (boxDom[child][0].$refs.tabMainLayout.$refs) {
                this.clearHanderClass(
                  boxDom[child][0].$refs.tabMainLayout.$refs
                )
              } else {
                // this.clearHanderClass(
                //   boxDom[child][0].$refs.tabMainLayout[i].$refs
                // )
              }
            }
          }
        }
      }
    },
    // 清空递归头部
    resetHeaderClass(cols) {
      for (let col of cols) {
        if (col.children && col.children.length > 0) {
          this.resetHeaderClass(col.children)
        }
        if (col.headerClassName) {
          col.headerClassName = {}
        }
      }
    },
    //清除其他高亮
    resetOtherActive() {
      let itemHandles = document.getElementsByClassName(
        'biUserDefined-item__handle'
      )
      for (let item of itemHandles) {
        item.style.height = '0'
        item.style.border = '0'
      }
      let screenActives = document.getElementsByClassName(
        'definedScreen__item_active'
      )
      for (let item of screenActives) {
        item.classList.remove('definedScreen__item_active')
      }
      let tableActive = document.getElementsByClassName(
        'biUserDefined-table__active'
      )
      for (let item of tableActive) {
        item.classList.remove('biUserDefined-table__active')
      }
      if (this.$refs.gridMainLayout && this.$refs.gridMainLayout.$refs) {
        this.clearHanderClass(this.$refs.gridMainLayout.$refs)
      }
    }
  },
  watch: {
    '$store.state.bi.natureArr': {
      handler(val) {
        this.natureArr =
          _.cloneDeep(
            val['d' + (this.$store.state.bi.dialogEditors.length - 1)]
          ) || []
      }
    },
    oldDatas: {
      handler(val) {
        this.initViewData()
        if (!this.isHeightFit) {
          // 不适应高度，重载
          this.isHideMainLayout = true
          this.$nextTick(() => {
            this.isHideMainLayout = false
          })
        }
      },
      deep: true
    }
  },
  deactivated() {
    this.$eventBus.$off('resetOtherActive', this.resetOtherActive)
    this.$eventBus.$off('optDel', this.optDel)
    this.$eventBus.$off(
      'changeAllPosition' +
        (this.oldData && this.oldData.length > 0 ? this.oldData[0].id : ''),
      this.changeAllPosition
    )
  }
}
</script>
<style lang="less" scoped>
.biUserDefinedForm-add__con {
  width: 100%;
  height: 100%;
  float: left;
  background: #eeeeee;
  z-index: 9999;
  /deep/.layer-con__con {
    margin: 0;
    background-color: var(--light-back-grey);
  }
  .ruler__handle {
    height: 100%;
    width: calc(100% + 2px);
    position: absolute;
    left: -2px;
    right: 0;
    top: -2px;
    z-index: 2;
    background-color: transparent;
    display: flex;
    .ruler_item {
      padding: 0 3.5px;
      &:not(:last-child) {
        height: 100%;
        border-right: 2px dashed #176ce621;
      }
    }
  }
  .biUserDefinedIconDrag-view__con {
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    position: relative;
  }
  .biUserDefinedIconDrag-view__screen {
    /*padding: 0 5px 5px;*/
    // overflow: hidden;
    z-index: 1;
    background-color: #ffffff;
    border-radius: 5px;
    transition: all 0.3s;
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    -ms-transition: all 0.3s;
    -o-transition: all 0.3s;
    position: relative;
  }

  .biUserDefinedIconDrag-screen_hover:after {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 10000;
    border: 1px var(--base-acv) solid;
    border-radius: 5px;
  }
  .biUserDefinedIconDrag__view {
    background: var(--light-back-grey);
    // margin-right: 5px;
    height: calc(100% - 100px);
  }
  .biUserDefinedIconDrag-screen__item {
    /* max-width: 200px; */
    width: 200px;
    height: 28px;
    float: left;
    margin: 5px 5px 0;
    position: relative;

    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
