<template>
  <div class="biUserDefinedForm-add__con flexbox">
    <tsDragTree
      v-if="!onPreview"
      :isTreeExpand="false"
      ref="dataSourceTree"
      dragType="column"
      :emptyText="dSEmptyText"
      :treeData="dataSourceTree"
      class="biLeftTree-con"
      @dragstart="dragstart"
      @dragend="dragend"
      :source="{textName: 'name',
          childName: 'children',
          line: true,
          draggable: true,
          isHighlightHover: true,
          isHighlightCurrent: false,
          showOverFlow: true}"
    ></tsDragTree>
    <div class="height100 pivot-con">
      <tsTopBar
        @topBarOptClick="topBarOptClick"
        ref="topbar"
        :topBarOpt="topBarOpt"
        class="topbar-con"
        v-if="!onPreview"
      >
        <div slot="after" class="preview">
          <ts-select
            :source="nowVersionCodeSource"
            v-model="nowVersionCode"
            title="当前版本:"
            @selected="changeNowVersion"
          >
            <tsPopover slot="titleBefore" v-if="nowVersionNote">{{nowVersionNote}}</tsPopover>
          </ts-select>
        </div>
      </tsTopBar>
      <!-- 工具栏 end -->
      <!-- 画布 -->
      <div class="biUserDefinedIconDrag__view flexYbox" ref="biUserDefinedIconDragViewBox">
        <pivotMainLayout ref="pivotMainLayout" />
      </div>
    </div>
    <div class="preview-table preview-table-con" v-if="onPreview">
      <tsTable
        :source="source"
        width="100%"
        height="100%"
        ref="previewTable"
        :mergeCells="mergeCells"
      ></tsTable>
    </div>
    <!-- 画布 end -->
    <diaLog
      :source="{title:'保存',buttons:[{ text: '确认', event: this.formVerify }]}"
      ref="biSaveDialog"
      type="right"
      v-if="!onPreview"
    >
      <bi-save ref="biSave" @saveClick="saveClick" :isPublish="isPublish" :biModel="biModel"></bi-save>
    </diaLog>
    <diaLog
      :source="layObj"
      ref="previewTableDialog"
      width="100%"
      height="100%"
      @close="closePreviewDialog"
      class="preview-table-dialog"
      v-if="!onPreview"
    >
      <div class="preview-table-con">
        <tsTable
          :source="source"
          width="100%"
          height="100%"
          ref="previewTable"
          :mergeCells="mergeCells"
        ></tsTable>
      </div>
    </diaLog>
    <diaLog :source="versionNoteSource" ref="versionNote" :offCloseBtn="true" v-if="!onPreview">
      <ts-textarea
        v-model="versionNoteInfo"
        style="padding:6px;width:calc(100% - 12px);height:calc(100% - 20px)"
      ></ts-textarea>
    </diaLog>
  </div>
</template>

<script>
import pivotMainLayout from './components/pivotMainLayout'
// import biSave from '../components/biDialog/biSave'
import submitMixins from '../components/mixins/submitMixins'
import _ from 'lodash'
export default {
  name: 'pivotTableEditor',
  components: { pivotMainLayout },
  mixins: [submitMixins],
  props: {
    isAdd_: {
      type: Boolean,
      default: true
    },
    oldData_: {
      type: Array,
      default: []
    },
    onPreview: {
      // 是否在预览下
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isAdd: this.isAdd_,
      oldData: this.oldData_,
      biModel: 'pivot',
      isPublish: false,
      versionNoteInfo: '', //版本说明
      versionNoteSource: {
        title: '版本说明', // 标题
        width: '400px', // 宽
        height: '150px', // 高
        offCloseBtn: false, // 关闭按钮区域，boolean 默认：false
        // 按钮
        buttons: [
          {
            text: '确认',
            event: this.handleSave
          }
        ]
      },
      dSEmptyText: '--暂无数据--',
      source: {
        dataType: 'local',
        data: [],
        colModel: [],
        showOverflow: true,
        postData: {},
        filtrate: [],
        buttons: [],
        isPrint: true, // 是否打印,boolean 默认：false
        isExport: true
      },
      dataSourceTree: [],
      layObj: {
        title: '保存', // 标题
        height: '100%', // 高
        closeBtn: false // 关闭按钮区域，boolean 默认：false
      },
      topBarOpt: [
        {
          iconfont: 'icon-baocun',
          title: '保存',
          color: '#f59a23'
        },
        {
          iconfont: 'icon-Group-21',
          isBack: true,
          title: '保存并退出',
          color: '#ea7061'
        },
        {
          iconfont: 'icon-fabu',
          isBack: true,
          title: '保存并发布',
          color: '#a89b60'
        },
        {
          iconfont: 'icon-yulan',
          title: '预览',
          color: '#00c297'
        }
      ],
      isBack: false,
      mergeCells: [],
      nowVersionCode: '', // 当前版本
      nowVersionNote: '' //当前版本备注
    }
  },
  computed: {
    nowVersionCodeSource() {
      return {
        dataType: 'json',
        url: '/ts-version/api/version/list',
        method: 'get',
        data: {
          name:
            this.oldData && this.oldData.length > 0 ? this.oldData[0].id : '',
          systemName: '平台应用',
          moduleName: '自定义报表',
          type: 3
        },
        page: 'pageNo',
        code: 'versionCode',
        text: 'versionCode',
        condition: 'condition',
        isReq: true,
        // isReq: true,
        value: {
          name: this.nowVersionCode || '草稿',
          code: this.nowVersionCode
        }
      }
    }
  },
  created() {},
  mounted() {
    if (!this.isAdd && this.oldData.length > 0) {
      this.nowVersionCode =
        this.oldData && this.oldData.length > 0
          ? this.oldData[0].versionCode
          : '草稿'
      // 修改，设置旧数据
      this.$refs.pivotMainLayout.$refs.pivot.setOtherDatas(
        this.oldData[0].other
      )
    }
    if (!this.onPreview) {
      this.getDataSourceTree('init')
    }
  },
  methods: {
    // // 数据源树搜索框
    // searchDSTree(val) {
    //   this.keywords = val
    //   this.getDataSourceTree()
    // },
    // 表单验证触发
    formVerify() {
      this.$refs.biSave.$refs.xForm.submit()
    },
    // 拖拽指标
    dragstart(ev, type, item) {
      if (item.type == 'condition') {
        type = 'condition,column'
      }
      this.$refs.pivotMainLayout.$refs.pivot.dragstart(ev, type, item)
    },
    // 拖拽停止
    dragend(ev, type, item) {
      this.$refs.pivotMainLayout.$refs.pivot.dragend(ev, type, item)
    },
    // 获取数据源数据
    getDataSourceTree(val) {
      let _this = this
      _this.dSEmptyText = '数据加载中...'
      let data = { condition: this.keywords, pageSize: 2000 }
      this.$api({
        url: '/ts-bi/api/v2/OfBusiCode/tree',
        method: 'get',
        loading: false,
        data: JSON.stringify(data),
        timeout: 30000000, // 指定请求超时的毫秒数
        loading: false,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
        }
      })
        .then(function(response) {
          // 请求成功
          if (response.object) {
            _this.dataSourceTree = []
            _this.dataSourceTree = _this.changeDateTree([...response.object])
            _this.dSEmptyText = '--暂无数据--'
          } else {
            _this.$utils.msg(_this, response.message, 'error')
          }
        })
        .catch(function(error) {
          // 请求失败
          _this.dSEmptyText = '--暂无数据--'
          _this.$utils.msg(_this, error.message, 'error')
        })
    },
    // 修改树
    changeDateTree(datas) {
      datas.unshift({
        id: '维度',
        name: '维度',
        type: 'conditionAll',
        children: [
          {
            id: 'yqdm',
            name: '院区',
            code: 'YQMC',
            type: 'condition',
            priority: 2,
            isScreen: true // 是否可过滤
          },
          {
            id: 'dept',
            name: '科室',
            code: 'KSMC',
            priority: 1,
            type: 'condition',
            isScreen: true
          },
          {
            id: 'doctor',
            name: '医生',
            code: 'YSMC',
            priority: 0,
            type: 'condition',
            isScreen: true // 是否可过滤
          },
          {
            id: 'item',
            name: '项目',
            code: 'ITEM_NAME',
            type: 'condition',
            isScreen: true // 是否可过滤
          },
          {
            id: 'YEAR',
            name: '年度',
            type: 'condition',
            code: 'YEAR_DSC',
            flag: 'dateType',
            priority: 3,
            isScreen: true // 是否可过滤
          },
          {
            id: 'QUARTER',
            name: '季度',
            code: 'QUARTER_DSC',
            type: 'condition',
            flag: 'dateType',
            priority: 2,
            isScreen: true // 是否可过滤
          },
          {
            id: 'MONTH',
            name: '月度',
            code: 'MONTH_DSC',
            type: 'condition',
            flag: 'dateType',
            priority: 1,
            isScreen: true // 是否可过滤
          },
          {
            id: 'DAY',
            name: '天',
            code: 'DAY_DSC',
            type: 'condition',
            flag: 'dateType',
            isScreen: true,
            priority: 0,
            isScreen: true // 是否可过滤
          }
        ]
      })
      return datas
    },
    //更改版本号
    changeNowVersion(row) {
      this.$nextTick(() => {
        this.nowVersionNote = row.versionNote || '无备注'
        this.loadVersionData(row.versionCode)
      })
    },
    // 加载版本号
    loadVersionData(nowVersionCode) {
      let url =
        nowVersionCode && nowVersionCode != '草稿'
          ? '/ts-version/api/version/data?versionCode=' + nowVersionCode
          : 'ts-version/api/version/data?type=3&systemName=平台应用&moduleName=自定义报表&name=' +
            this.oldData[0].id +
            '&copyFlag=1'
      const _this = this
      this.$api({
        url: url,
        method: 'get',
        contentType: 'application/x-www-form-urlencoded; charset=utf-8'
      })
        .then(function(res) {
          if (res.success) {
            _this.oldData[0].versionCode = nowVersionCode
            _this.oldData[0].other = res.object
            // 修改，设置旧数据
            _this.$refs.pivotMainLayout.$refs.pivot.setOtherDatas(res.object)
          } else {
            _this.$utils.msg(_this, '加载失败，请联系管理员', 'error')
          }
        })
        .catch(function(error) {
          // 请求失败
        })
    },
    topBarOptClick(item) {
      let validate = ''
      switch (item.title) {
        case '保存并退出':
        case '保存':
          this.isBack = item.isBack
          if (this.isAdd) {
            this.$refs.biSaveDialog.open()
          } else {
            this.saveClick({ type: 'edit' }) // 编辑
          }
          break
        case '保存并发布':
          if (this.isAdd) {
            this.isPublish = true
            this.$refs.biSaveDialog.open()
          } else {
            // 编辑
            this.$refs.versionNote.open()
          }
          break
        case '预览':
          this.layObj.title = '预览'
          this.layObj.flag = 'preview'
          this.$nextTick(() => {
            this.$refs.previewTableDialog.open()
          })
          this.getPreviewSource(false)
          break
      }
    },
    // 得到预览相关内容
    getPreviewSource(isRefresh) {
      this.$nextTick(() => {
        if (this.$refs.pivotMainLayout) {
          let obj = this.$refs.pivotMainLayout.$refs.pivot.getPreviewTableDatas()
          this.source.data = obj.datas
          this.source.colModel = [
            ...this.$refs.pivotMainLayout.$refs.pivot.getPreviewTableCols()
          ]
          if (!isRefresh||this.source.filtrate.length == 0) {
            // 只有加载时才加载筛选框，防止重复加载
            this.source.filtrate = this.$refs.pivotMainLayout.$refs.pivot.getPreviewTableFiltrate(
              this.dataSourceTree
            )
          }
          this.mergeCells = obj.mergeCells
          // this.$refs.previewTable.colModelFn(_.cloneDeep(this.source.colModel))
          this.$refs.previewTable
            ? (this.$refs.previewTable.tableKey = this.$utils.uuid(6))
            : ''
        }
      })
    },
    // 保存并发布
    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
      // )
    },
    // 关闭预览框，还原数据
    closePreviewDialog() {
      this.$refs.pivotMainLayout.asyncData = [
        ...this.$refs.pivotMainLayout.filterBeforeData
      ]
      // this.getPreviewSource()
    }
  },
  watch: {},
  deactivated() {}
}
</script>
<style lang="less" scoped>
.biUserDefinedForm-add__con {
  width: 100%;
  height: 100%;
  float: left;
  background: var(--light-back-grey);
  z-index: 9999;
  overflow: hidden;
  .preview-table {
    width: calc(100% - 14px);
    height: calc(100% - 14px);
    padding: 7px;
    position: absolute;
    top: 0;
    left: 0;
    background: white;
  }
  .biLeftTree-con {
    width: 200px;
    background: white;
    margin: 8px 0 8px 8px;
    height: calc(100% - 16px) !important;
  }
  .topbar-con {
    margin: 8px 8px 0 8px;
  }
  .pivot-con {
    width: calc(100% - 200px);
  }
  .biUserDefinedIconDrag__view {
    height: calc(100% - 48px);
  }
  .preview-table-dialog {
    /deep/.layer-con__con {
      background-color: #fff !important;
    }
    .preview-table-con {
      margin: 5px 8px;
      width: calc(100% - 16px) !important;
      height: calc(100% - 10px);
    }
  }
}
</style>
