<template>
  <grid-layout
    class="grid-main-layout"
    :layout.sync="layout"
    :col-num="36"
    :row-height="biModel=='mobile'?1:10"
    :is-draggable="isDraggable"
    :is-resizable="isResizeable"
    :is-mirrored="false"
    :vertical-compact="true"
    :margin="[7, 7]"
    :use-css-transforms="true"
    ref="gridLayout"
    @changeYH="changeYH"
    :formId="formId"
  >
    <grid-item
      :class="'biUserDefined__item ' + (isEditable?'edit_border':'') +(!isEditable&&item.type=='filter'&&!item.isNoTop?'filter-con':'')+' '+item.type"
      v-for="item in layout"
      :x="item.x"
      :y="item.y"
      :w="item.w"
      :minW="1"
      :minH="1"
      :h="item.h"
      :i="item.i"
      :key="item.i"
      :static="item.static"
      :uuid="item.i"
      :id="item.type"
      :type="item.type"
      :isFullHeight="item.isFullHeight"
      :HPosition="item.HPosition"
      @resized="resizedEvent(arguments,item)"
      @moved="movedEvent(arguments,item,$event)"
      @containerWidthUpdated="containerWidthUpdated(arguments,item)"
      :isNoTop="item.isNoTop"
      :ref="item.type"
      :formId="formId"
      :isHeightFit="isHeightFit"
      :layoutType="layoutType"
    >
      <div v-if="!isEditable&&item.type=='filter'&&!item.isNoTop" class="filter-con-border"></div>
      <bi-report-layout
        :item="item"
        :ref="item.i"
        :key="item.i"
        :biModel="biModel"
        @refreshData="refreshData"
        @interData="interData"
        @exportExcel="exportExcel"
        :isEditable="isEditable"
        :showMData="showMData"
        :formId="formId"
        :isFromList="isFromList"
        :isHeightFit="isHeightFit"
        :dataVKey="dataVKey"
        :isShowBigScreen="isShowBigScreen"
      ></bi-report-layout>
    </grid-item>
  </grid-layout>
</template>

<script>
import GridItem from './gridCom/components/GridItem'
import GridLayout from './gridCom/components/GridLayout'
import gridMainLayoutMixins from '../mixins/gridMainLayoutMixins'
import biReportLayout from './biReportLayout'
import _ from 'lodash'
export default {
  name: 'gridMainLayout',
  props: {
    isShowBigScreen: {
      // 是否是大屏模式下
      type: Boolean,
      default: false
    },
    isDraggable: {
      type: Boolean,
      default: false
    },
    isResizeable: {
      type: Boolean,
      default: false
    },
    isEditable: {
      type: Boolean,
      default: false
    },
    biModel: {
      type: String,
      default: ''
    },
    showMData: {
      // 是否显示模拟数据
      type: Boolean,
      default: false
    },
    layoutList: {
      type: Array,
      default: () => []
    },
    formId: {
      type: String,
      default: ''
    },
    isFromList: {
      // 是否来自于列表
      type: Boolean,
      default: false
    },
    isHeightFit: {
      // 是否高度适配
      type: Boolean,
      default: true
    },
    layoutType: {
      // 类型
      type: String,
      default: ''
    }
  },
  mixins: [gridMainLayoutMixins],
  components: {
    GridLayout,
    GridItem,
    biReportLayout
  },
  data() {
    return {
      dataVKey: '',
      tableArry: [],
      layout: _.cloneDeep(this.layoutList),
      fixedMarginLeft: 0 // 固定距离右边的边距
    }
  },
  mounted() {
    // if (!this.isEditable&&!this.showMData) {
    //   let fixedMarginLeft = this.$refs.gridLayout.$el.getBoundingClientRect().left
    //   let fixedMarginRight = this.$refs.gridLayout.$el.getBoundingClientRect().right
    //   if (this.$refs.filter) {
    //     for (let item of this.$refs.filter) {
    //       if (!item.isNoTip) {
    //         // 置顶
    //         item.$el.style.marginLeft = fixedMarginLeft +'px'
    //         item.$el.style.width = 'calc(100% - '+(fixedMarginLeft+20)+'px)'
    //
    //       }
    //     }
    //   }
    // }
    //
  },
  methods: {
    changeYH(natureArr) {
      this.$emit('changeYH', natureArr)
    },
    // getMarginLeft() {
    //   this.$nextTick(() => {
    //     let fixedMarginLeft = this.$refs.gridLayout.$el.getBoundingClientRect().left
    //     console.log(fixedMarginLeft)
    //     return fixedMarginLeft + 'px !important'
    //   })
    // },
    refreshData(param) {
      this.$emit('refreshData', param)
    },
    interData(interDatas) {
      this.$emit('interData', interDatas)
    },
    findTable(layout) {
      for (let item of layout) {
        if (item.type == 'tab') {
          let index = parseInt(item.activeIndex)
          this.findTable(item.tabs[index].natureArr)
        }
        if (item.type == 'panel') {
          this.findTable(item.natureArr)
        }
        if (item.type == 'table') {
          this.tableArry.push(item)
        }
      }
    },
    setTitle(arr) {
      arr.forEach((ev, i) => {
        if (ev.field) {
          ev.name = ev.field
          for (var obj in ev) {
            if (obj == 'title' || obj == 'name' || obj == 'children') {
            } else {
              delete ev[obj]
            }
          }
          if (ev.children && ev.children.length > 0) {
            ev.virtual = true
            this.setTitle(ev.children)
          } else {
            delete ev.children
          }
        }
      })
    },
    exportExcel(val) {
      let url = '/ts-query/api/user/query/table/export/csv'
      if (val == 'xlsx') {
        url = '/ts-query/api/user/query/table/export/excel'
      }
      //导出 val 为导出格式类型 csv和xlxs
      // let tableList = this.layout.filter(res => res.type == 'table')
      // 还剩一个带child的导出
      const _this = this
      _this.tableArry = []
      _this.findTable(_this.layout)
      if (_this.tableArry && _this.tableArry.length > 0) {
        for (let item of _this.tableArry) {
          var titles = _.cloneDeep(item.cols)
          // titles.splice(0, 1)
          _this.setTitle(titles)
          let data = {
            id: item.dataSourceId,
            parameters:
              sessionStorage.getItem('parameters') ||
              JSON.stringify(item.parameters) ||
              [],
            titles: JSON.stringify(titles)
          }
          this.$api({
            url: url,
            method: 'post',
            data: data,
            responseType: 'blob',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
            }
          })
            .then(function(res) {
              // 请求成功
              if (res) {
                var 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 = '表格' + '.' + val
                    a.href = e.target.result
                    document.body.appendChild(a)
                    a.click()
                    a.remove()
                  }
                }
              }
            })
            .catch(function(error) {
              // 请求失败
              _this.$utils.msg(_this, error.message || '导出失败', 'error')
            })
        }
      } else {
        _this.$utils.msg(_this, '暂无表格，无法导出', 'error')
      }
    }
    // // 列表配置
    // sourceRealFn(item) {
    //   let mergeCells = []
    //   // mergeCells.push({ row: 0, col: 1, rowspan: 1, colspan: 2 }) //这个获取数据的长度赋值
    //   return {
    //     dataType: 'local',
    //     id: item.id,
    //     offPage: item.offPage || false,
    //     showOverflow: true,
    //     data: item.data,
    //     totalSet: item.isCount && item.totalSet ? [...item.totalSet] : [],
    //     colModel: item.cols,
    //     mergeCells: mergeCells
    //   }
    // }
  },
  watch: {
    layoutList: {
      handler(val, o) {
        this.layout = [...val]
        // this.layout = JSON.parse(JSON.stringify(val))
        // if (!this.isEditable) {
        //   for (let item of this.layout) {
        //     if (item.type == 'table') {
        //       item.sourceRealFn = JSON.parse(
        //         JSON.stringify(this.sourceRealFn(item))
        //       )
        //     }
        //   }
        // }
        // // console.log(this.layout, 2222222222222)
        // this.$nextTick(() => {
        //   let chartList = this.layout.filter(res => res.type == 'chart')
        //   if (chartList && chartList.length > 0) {
        //     for (let chartItem of chartList) {
        //       let chart = this.$refs[chartItem.i][0].$refs.tsChart

        //       if (chart.chartWidth === 0) {
        //         //若图表未被渲染，则渲染
        //         chart.initChart()
        //       }
        //     }
        //   }
        // })
      }
      // immediate: true,
    }
  }
}
</script>

<style lang="scss" scoped>
.grid-main-layout {
  height: 100% !important;
  // overflow: hidden;
  // overflow-y: auto;
  .edit_border:hover {
    border: 1.5px dashed var(--base-acv);
  }
  .edit_border {
    border: 1px solid #bbbbbb;
    box-sizing: border-box;
  }
  .biUserDefined__item {
    width: 100%;
    height: 100%;
    // z-index: 0;
    // background: white;
  }
  // .filter-con-formId {
  //   position: fixed !important;
  //   z-index: 99 !important;
  //   box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
  // }
  .filter-con {
    position: fixed !important;
    // z-index: 99 !important;
    .filter-con-border {
      position: fixed;
      height: 14px;
      width: calc(100% + 14px);
      background: var(--light-back-grey);
      margin-top: -7px;
      margin-left: -7px;
    }
    // margin-top: -8px;
    // box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
  }
}
</style>
