<template>
    <div :class="['el-basic-template', size ? 'el-basic-template--' + size : '']">
        <!-- 头部 -->
        <div class="el-basic-template-header">
            <!-- 标题区域 -->
            <div class="el-basic-template-header-left" v-if='hasTitle || title'>
                <slot v-if="hasTitle" name="title"></slot>
                <div class="el-basic-template-header-left-title" v-else>
                    {{ title }}
                </div>
            </div>
            <!-- 交互区 -->
            <div class="el-basic-template-header-right">
                <!-- 靠近标题的交互区 -->
                <div class='el-basic-template-header-right-action-left'>
                    <slot name="actionLeft"></slot>
                </div>
                <!-- 头部右侧的交互区 -->
                <div v-if='hasActionRight' class='el-basic-template-header-right-action-right'>
                    <slot name="actionRight"></slot>
                </div>
            </div>
        </div>
        <!-- 主体区域 -->
        <div class="el-basic-template-content" ref="content">
            <!-- 左侧，树区域 -->
            <el-scrollbar
                ref='contentLeft'
                class="el-basic-template-content-left"
                :class="{
                    'background-fuzzy': isFuzzy,
                }"
                :style="{minWidth: dragWidth || null}"
                v-if="hasTree"
            >
                <div class='el-basic-template-content-left-container'>
                    <slot name="tree" :max-height="treeMaxH"></slot>
                </div>
            </el-scrollbar>
            <div v-else-if="hasLargeTree"
                ref='contentLeft'
                class="el-basic-template-content-left-large"
                :class="{
                    'background-fuzzy': isFuzzy,
                }"
                :style="{minWidth: dragWidth || null}"
            >
                <div class='el-basic-template-content-left-large-container'>
                    <slot name="largeTree" :max-height="treeMaxH"></slot>
                </div>
            </div>
            <!-- 右侧，表格和筛选区域 -->
            <div
                ref="contentRight"
                class="el-basic-template-content-right"
                :class="{ 'has-left-tree': hasTree || hasLargeTree, 'has-left-large-tree': hasLargeTree }"
                :style="{minWidth: dragWidth ? `calc(100% - ${dragWidth})` : '100%'}"
            >
                <div class="el-basic-template-content-right-handle" ref="resizeHandle" v-show="resizeable && (hasTree || hasLargeTree)"></div>
                <!-- 表格筛选条件区域 -->
                <div class="el-basic-template-content-right-filter" v-if="hasFilterLeft || hasFilterRight">
                    <!-- 筛选区左侧 -->
                    <!-- 不能缺少时，使用v-if去除，会使flex布局错误 -->
                    <div ref="filterLeft" class="el-basic-template-content-right-filter-left">
                        <slot name="filterLeft"></slot>
                    </div>
                    <!-- 筛选区右侧 -->
                    <div class="el-basic-template-content-right-filter-right" v-if="hasFilterRight">
                        <slot name="filterRight"></slot>
                    </div>
                </div>
                <div class="el-basic-template-content-right-statistic" v-if="hasStatistic">
                  <slot name="statistic"></slot>
                </div>
                <!-- 表格区域 -->
                <el-scrollbar class="el-basic-template-content-right-default" v-if="hasDefault">
                    <div class='el-basic-template-content-right-default-container' ref="default">
                        <slot :max-height="tableMaxH"></slot>
                    </div>
                </el-scrollbar>
            </div>
        </div>
    </div>
</template>
<script>
import { templateProps } from './config';
import { addDragHandle } from '@ued_fpi/element-ui/src/utils/dragHandle';
import { getStyle, getRect } from '@ued_fpi/element-ui/src/utils/util';
import ElBackground from '@ued_fpi/element-ui/packages/background';
import ElScrollbar from '@ued_fpi/element-ui/packages/scrollbar';
const attrsValueToNumber = value => {
  return (parseInt(value, 10) || 0);
};
export default {
  name: 'ElBasicTemplate',
  props: templateProps,
  data() {
    return {
      treeMaxH: null, // tree最大高度
      tableMaxH: null, // 表格最大高度
      timer: false, // 是否存在定时器
      dragWidth: 0, // 拖拽后左侧树的宽度
      lastDragWidth: 0, // 上一次拖拽后左侧树的宽度
      minDragWidth: null, // 最小拖拽宽度
      maxDragWidth: null // 最大拖拽宽度
    };
  },
  computed: {
    // 当前控件尺寸
    size() {
      return (this.$ELEMENT || {}).size;
    },
    // 是否自定义title
    hasTitle() {
      return this.$slots.title || this.$scopedSlots.title;
    },
    // 是否有头部左侧交互
    hasActionLeft() {
      return this.$slots.actionLeft || this.$scopedSlots.actionLeft;
    },
    // 是否有头部右侧交互
    hasActionRight() {
      return this.$slots.actionRight || this.$scopedSlots.actionRight;
    },
    // 是否有左侧树
    hasTree() {
      return this.$slots.tree || this.$scopedSlots.tree;
    },
    // 是否有左侧大型树
    hasLargeTree() {
      return this.$slots.largeTree || this.$scopedSlots.largeTree;
    },
    // 是否有左侧过滤条件
    hasFilterLeft() {
      return this.$slots.filterLeft || this.$scopedSlots.filterLeft;
    },
    // 是否有右侧过滤条件
    hasFilterRight() {
      return this.$slots.filterRight || this.$scopedSlots.filterRight;
    },
    // 是否有统计项
    hasStatistic() {
      return this.$slots.statistic || this.$scopedSlots.statistic;
    },
    // 是否有默认填充
    hasDefault() {
      return this.$slots.default || this.$scopedSlots.default;
    }
  },
  // watch: {
  //   hasTree() {
  //     try {
  //       // 树隐藏/显示变化后，重置lastDragWidth
  //       if (this.hasTree) this.lastDragWidth = parseInt(getStyle(this.$refs.contentLeft.$el).width, 10);
  //     } catch (error) {
  //       console.log(error);
  //     }
  //   }
  // },
  components: {
    ElBackground,
    ElScrollbar
  },
  mounted() {
    if (this.$refs.default) {
      this.triggerMaxHeightRecalculate();
      window.addEventListener('resize', this.resizeFunc, false);
    }

    // 如果有左侧树，设定lastDragWidth
    if (this.hasTree || this.hasLargeTree) {
      const contentLeft = this.hasTree ? this.$refs.contentLeft.$el : this.$refs.contentLeft;
      const contentLeftWidth = parseInt(getStyle(contentLeft).width, 10);
      const halfContentWidth = parseInt(getStyle(this.$refs.content).width, 10) / 2;
      this.lastDragWidth = contentLeftWidth;
      this.dragWidth = this.lastDragWidth + 'px';
      // 设定拖拽的范围
      this.minDragWidth = contentLeftWidth;
      this.maxDragWidth = halfContentWidth;
    }
    addDragHandle(this.$refs.resizeHandle, (dx, dy, tickDx) => {
      // 边界判断
      if ((this.lastDragWidth + dx >= this.minDragWidth) && (this.lastDragWidth + dx <= this.maxDragWidth)) {
        this.dragWidth = this.lastDragWidth + dx + 'px';
        this.resizeFunc();
      }
    }, () => {
      this.lastDragWidth = parseInt(this.dragWidth, 10);
    });
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeFunc, false);
  },
  methods: {
    /**
     * 主动触发所有最大高度的重计算
     */
    triggerMaxHeightRecalculate() {
      this.getTableMaxH();
      this.getTreeMaxH();
    },
    /**
     * 计算table表单高度
    */
    getTableMaxH() {
      const defaultStyle = getStyle(this.$refs.default);
      // default总高度
      let height =
        window.innerHeight -
        getRect(this.$refs.default).top -
        attrsValueToNumber(defaultStyle.paddingTop) -
        attrsValueToNumber(defaultStyle.paddingBottom) -
        attrsValueToNumber(defaultStyle.marginTop) -
        attrsValueToNumber(defaultStyle.marginBottom);
      // 查找所有的直接子元素
      for (let i = 0; i < this.$refs.default.children.length; i++) {
        const item = this.$refs.default.children[i];
        const itemStyle = getStyle(item);
        // 是否存在className，防止split报错
        if (item.className.length < 0 || item.className.split(' ').filter(x => this.tableClass.includes(x))
          .length === 0) {
          // 如果是包含指定类名，跳过
          height =
              height -
              attrsValueToNumber(itemStyle.height) -
              attrsValueToNumber(itemStyle.paddingTop) -
              attrsValueToNumber(itemStyle.paddingBottom) -
              attrsValueToNumber(itemStyle.marginTop) -
              attrsValueToNumber(itemStyle.marginBottom);
        }
      }
      this.tableMaxH = height;
      this.$emit('contentResize', height);
    },
    /**
     * 获取树最大高度
     */
    getTreeMaxH() {
      if (this.hasTree || this.hasLargeTree) {
        const contentLeft = this.hasTree ? this.$refs.contentLeft.$el : this.$refs.contentLeft;
        const style = getStyle(contentLeft);
        this.treeMaxH =
                  attrsValueToNumber(style.height) -
                  attrsValueToNumber(style.paddingTop) -
                  attrsValueToNumber(style.paddingBottom) -
                  attrsValueToNumber(style.marginTop) -
                  attrsValueToNumber(style.marginBottom);
        this.$emit('treeResize', this.treeMaxH);
      }
    },
    /**
     * 窗口监听设置表格高度
    */
    resizeFunc() {
      if (this.timer) return;
      this.timer = true;
      setTimeout(() => {
        this.timer = false;
        this.triggerMaxHeightRecalculate();
      }, 100);
    }
  }
};
</script>
