<!-- eslint-disable vue/no-parsing-error -->
<template>
  <div class="hct-table" id="hct-table">
    <el-table v-if="tableHeader" ref="tableRef" scrollbar-always-on :max-height="maxHeight" v-bind="$attrs" border stripe v-on="$listener">
      <el-table-column v-if="tableHeader.length != 0 && showSelection" type="selection" label="" align="center"
        :width="80" />
      <el-table-column v-if="tableHeader.length != 0" type="index" label="序号" align="left" :width="indexWidth"
        fixed="left" />
      <!-- 操作列 -->
      <el-table-column v-if="showOperate" label="操作" align="left" :fixed="operateFixed" :width="minWidth">
        <template #header>
          <slot name="header">
            <div class="operate-flex-between" :style="
              numButton > 3
                ? 'justify-content:space-between;'
                : 'justify-content:left;'
            ">
              操作
              <div v-if="numButton > 3" class="hct-table-header_icon">
                <i :class="['iconfont', screenClick(showTextIcon, true)]" @click="textClick(showTextIcon, true, i)" />
                文字
                <i :class="['iconfont', screenClick(showTextIcon, false)]" @click="textClick(showTextIcon, false, i)" />
                图标
              </div>
            </div>
          </slot>
        </template>
        <template #default="scope">
          <div id="operate-num" :class="[
            showTextIcon == 1 ? 'show-icon' : '',
            showTextIcon == 2 ? 'show-text' : '',
          ]">
            <slot name="operate" v-bind="scope" />
          </div>
        </template>
      </el-table-column>
      <template v-for="(item, i) in tableHeader" :key="i">
        <el-table-column v-if="item.isShow" :type="item.type" :prop="item.fieldName" :label="item.showName"
          :min-width="item.colWidth" align="left" :fixed="isBoolen(item.isFixed)">
          <template #header>
            <div>
              <span class="hct-table-header_cell">
                {{ item.showName }}
              </span>
              <!-- 筛选项 -->
              <hct-screen v-if="item.isFilter">
                <template #reference>
                  <i class="icon-hctshaixuan iconfont icon" />
                </template>
              </hct-screen>
              <!-- 筛选项 -->
            </div>
          </template>
          <template v-if="item.fieldName != ''" #default="scope">
            <div>
              <slot :name="item.fieldName" v-bind="scope">
                {{ getSpecial(scope.row, item.fieldName) }}
              </slot>
            </div>
          </template>
        </el-table-column>
      </template>
      <slot name="tableCloumn" v-bind="$attrs" v-on="$listener" />
    </el-table>
    <el-table v-else ref="tableRef" scrollbar-always-on :max-height="maxHeight" v-bind="$attrs" border stripe v-on="$listener">
      <slot />
    </el-table>
  </div>
</template>
<script setup>
import hctScreen from "./hct-screen.vue";
import { ref, reactive, onMounted, nextTick, watch } from "vue";
let props = defineProps({
  tableHeader: Array,
  showOperate: { // 展示操作
    type: Boolean,
    default: false,
  },
  showSelection: { // 展示多选
    type: Boolean,
    default: false,
  },
  indexWidth: { // 自定义序号列宽
    type: Number,
    default: 80,
  },
  operateWidth: { // 自定义操作列宽
    type: Number,
    default: 80,
  },
  isAuto: { // 自动计算操作列宽
    type: Boolean,
    default: true,
  },
  isAutoTable: { // 自动适配列表高
    type: Boolean,
    default: false,
  },
  operateFixed: { // 操作栏位置
    type: [String,Boolean],
    default: 'left', // true / 'left' / 'right'
  }
});
let minWidth = ref(props.operateWidth); // 最小宽度
let hiddTextIcon = ref(true); //是否展示文字图标
let numButton = ref(0); // 操作列按钮数量
let showTextIcon = ref(0); //操作文字图标
let showOperate = ref(props.showOperate); // 是否显示操作列
const operateFixed = ref(props.operateFixed) // 操作列固定
const tableHeader = reactive(props.tableHeader);
const maxHeight = ref('auto')
const hctId = ref([])
//计算操作按钮
onMounted(async () => {
  await nextTick()
  if (props.isAuto && tableHeader) {
    nextTick(() => {
      setTimeout(() => {
        if (document.getElementsByTagName('tbody')[0]) {
          numButton.value = document.getElementsByTagName('tbody')[0].getElementsByClassName('el-table__row')[0].getElementsByTagName('button').length
          minWidth.value = 60 + calcWidth(numButton.value);
        }
      }, 200);
    });
  }
  nextTick(() => {
    hctId.value = document.getElementById('hct-table')
  })
});
// 计算table高
const calcHeight = () => {
  if(!document.getElementById('hct-table')) return
    let me = document.getElementById('hct-table') // 自己
    let fa = me?.parentNode // 父元素
    let bro = me?.nextSibling // 兄弟元素
    let grn = bro?.nextSibling // 兄弟元素的兄弟
    let footer = document.getElementsByClassName('el-table__footer') // table是否有合计
    // 如果兄弟元素为注释或者文本或者不存在
    if (bro?.nodeName != '#text' && bro?.nodeName != '#comment' && bro?.nodeName) {
      let meHeight = me?.offsetTop
      let nextSibling = bro?.offsetTop
      let marTop = getComputedStyle(bro, null)?.marginTop.replace('px', '')
      fa.style.height = (nextSibling - meHeight - 80) + 'px'
      maxHeight.value = nextSibling - meHeight - 80
    } else {
      if (grn?.nodeName != '#text' && grn?.nodeName != '#comment' && grn?.nodeName) {
        let meHeight = me?.offsetTop
        let nextSibling = grn?.offsetTop
        let marTop = getComputedStyle(grn, null).marginTop.replace('px', '')
        fa.style.height = (nextSibling - meHeight - 80) + 'px'
        maxHeight.value = nextSibling - meHeight - 80
      } else {
        // 父元素的高度
        let faHeight = fa.offsetTop
        // 
        let nextSibling = fa.nextSibling.offsetTop
        // let marTop = getComputedStyle(nextSibling, null).marginTop
        if(footer) {
          fa.style.height = (nextSibling - faHeight - 170) + 'px'
          maxHeight.value = nextSibling - faHeight - 170
        } else {
          fa.style.height = (nextSibling - faHeight - 120) + 'px'
          maxHeight.value = nextSibling - faHeight - 120
        }
      }

    }
  
}
// 计算操作宽
const calcWidth = (num) => {
  switch (num) {
    case 3:
      return 70 * num;
      break;
    case 4:
      return 82 * num;
      break;
    case 5:
      return 92 * num;
      break;
    case 6:
      return 92 * num;
      break;
    default:
      if (num > 5) {
        return 92 * num;
      } else {
        return 60 * num;
      }

      break;
  }
};
// 返回特殊字段处理
const getSpecial = (row, val) => {
  // item.fieldName.indexOf('-')<0? (scope.row[item.fieldName] || "-") : 
  if (val.indexOf('-') < 0) {
    return row[val]
  } else {
    let list = val.split('-');
    let label = (row[list[0]] || '') + '-' + (row[list[1]] || '')
    return label
  }

}
// 数字转Boolean
const isBoolen = (i) => {
  let type = typeof i;
  if (type == "number") {
    if (i) {
      return true;
    } else {
      return false;
    }
  } else {
    return i;
  }
};
// 展示文字图标
const screenClick = (i, type) => {
  if (type) {
    if (i == 1) {
      return "icon-hctyincang";
    } else {
      return "icon-hctxianshi";
    }
  } else {
    if (i == 2) {
      return "icon-hctyincang";
    } else {
      return "icon-hctxianshi";
    }
  }
};
// 是否显示文字图标
const textClick = (index, type, i) => {
  if (type) {
    if (index == 1) {
      showTextIcon.value = 0;
    } else {
      if (index == 2) {
        showTextIcon.value = 1;
      } else {
        showTextIcon.value = 1;
      }
    }
  } else {
    if (index == 2) {
      showTextIcon.value = 0;
    } else {
      if (index == 1) {
        showTextIcon.value = 2;
      } else {
        showTextIcon.value = 2;
      }
    }
  }
};
let tableRef = ref(null) // table ref
watch(() => hctId.value, (newVal, oldVal) => {
  if (props.isAutoTable) {
    nextTick(() => {
      setTimeout(() => {
        window.onresize = function () {
          calcHeight()
        }
        calcHeight()
      }, 200);
    })
  }
})
//导出事件
defineExpose({
  tableHeader,
  showTextIcon,
  tableRef,
});
</script>
<script>
export default {
  name: "HctTable",
};
</script>
<style scoped lang='scss'>
.hct-table {
  .hct-table-header {
    .el-icon {
      margin-left: 12px;
    }
  }

  .icon {
    // font-size: 14px;
    width: 14px;
    height: 14px;
    vertical-align: baseline;
  }

  .hct-flex {
    display: flex;
    justify-content: space-between;
  }

  .hct-flex-icon {
    display: flex;
    align-items: center;
  }

  .hct-table-header_cell {
    margin-right: 10px;
    display: inline-block;
  }

  .hct-table-header_icon {
    display: inline-block;
    // color: #999999;
  }

  .operate-flex-between {
    display: flex;
    justify-content: space-between;
  }

  :deep(.el-button.is-text) {
    padding: 0;
  }

  :deep(.el-table__cell .cell) {
    white-space: nowrap;
  }

  .show-icon {
    :deep(.el-button i) {
      display: none !important;
    }
  }

  .show-text {
    :deep(.el-button span > span) {
      display: none !important;
    }
  }
}
</style>