<template>
  <div style="width: 100%" :ref="randomRef" :class="'c'+tableName">
    <!--表格栏-->
    <el-table :data="content" :highlight-current-row="highlightCurrentRow"
              :header-cell-style="{background:'#fafafa',color:'#333333',height:'48px',fontSize:'14px'}"
              :row-style="{color:'#606266'}" @row-click="handleClick"
              :row-key="rowKey"
              :show-summary="showSummary"
              ref="table"
              :default-expand-all="defaultExpandAll"
              @selection-change="selectionChange"
              @sort-change="sortChange"
              @filter-change="filterChange"
              :tree-props="treeOption"
              :row-class-name="rowClassName"
              :header-row-class-name="headerRowClassName"
              :header-cell-class-name="headerCellClassName"
              :cell-class-name="cellClassName"
              :height="height"
              @current-change="handleCurrentChange" v-loading="loading" :element-loading-text="'拼命加载中'" :border="border" :stripe="stripe"
              :max-height="maxHeight" :size="size" :align="align" :style="{'width':width}" >
      <slot v-if="!columns.length"></slot>
      <div v-if="columns.length">
        <el-table-column label=" " min-width="1px" max-width="1px" width="1px" prop="emt"></el-table-column>
        <template  v-for="(column,index) in columns">
          <el-table-column
            :type="index+1+''"
            :prop="column.prop" :label="column.label" :width="column.col+'px'" :min-width="column.col+'px'"
            :sortable="column.sortable" :fixed="column.fixed" :key="column.prop"
            :filters="column.filters" :filter-method="column.filterMethod" :filter-placement="column.filterPlacement">
            <template slot-scope="scope">
              <a v-if="column.isUrl&&column.isUrl==true" :href="scope.row[column.prop]" target="_blank" class="urlLink">{{scope.row[column.prop]}}</a>
              <span v-else>{{scope.row[column.prop]}}</span>
            </template>
          </el-table-column>
        </template>
      </div>
      <!--自动生成模版的表格操作栏-->
      <div v-if="operations.editClick||operations.delClick||operations.otherClick">
        <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">

            <al-button type="text" size="small" v-if="operations.editClick" @click="operations.editClick(scope.row)" v-text="operations.editButtonName?operations.editButtonName:'编辑'"></al-button>
            <al-button type="text" size="small" v-if="operations.delClick" @click="operations.delClick(scope.row)" v-text="operations.delButtonName?operations.delButtonName:'删除'"></al-button>
            <al-button type="text" size="small" v-if="operations.otherClick" @click="operations.otherClick(scope.row)" v-text="operations.otherButtonName?operations.otherButtonName:'其他'"></al-button>
          </template>
        </el-table-column>
      </div>
    </el-table>
    <div class="arrowFixed" v-if="headerShow">
      <div class="iconfont icon-auro-arrow-right" @click="fScroll(-100)" :style="{'left': leftArrowLeft+'px'}"></div>
      <div class="iconfont icon-auro-arrow-right" @click="fScroll(100)" :style="{'right': rightArrowRight+'px'}"></div>
    </div>
    <!--分页栏-->
    <div class="toolbar" style="padding:10px;text-align: right" v-if="data&&data.totalSize">
      <al-pagination layout="total, prev, pager, next, jumper" @current-change="refreshPageRequest"
                     :current-page="data.pageNum" :page-size="data.pageSize" :total="data.totalSize">
      </al-pagination>
    </div>
  </div>
</template>

<script>
    // 表格实例列表
    class tableObserverList {
        constructor() {
            this.observerList = []
        }
        add(observer) {
            return this.observerList.push(observer);
        }
        remove(observer) {
            this.observerList = this.observerList.filter(ob => ob !== observer);
        }
        count() {
            return this.observerList.length;
        }
        get(index) {
            return this.observerList[index];
        }
    }
    class alTableTarget {
        constructor() {
            this.scrollDoms=[];
            this.tableObservers = new tableObserverList();
        }
        addObserver(tbObserver) {
            this.tableObservers.add(tbObserver);
            if(this.scrollDoms.indexOf(tbObserver.targetDom)==-1){
                this.scrollDoms.push(tbObserver.targetDom);
                this.addListener(tbObserver.targetDom);
            }
        }
        removeObserver(tbObserver) {
            this.tableObservers.remove(tbObserver);
        }
        addListener(dom){
            var _that=this;
            dom.addEventListener("scroll",function(e){
                _that.notify(this,e)
            })
        }
        notify(scrollDom,...args) {
            console.log(scrollDom)
            let obCount = this.tableObservers.count();
            for (let index = 0; index < obCount; index++) {
                if(this.tableObservers.get(index).targetDom==scrollDom){
                    this.tableObservers.get(index).onScroll(...args);
                }
            }
        }
    }
  //position: fixed;
  //   top: 60px;
  //   right: 21px;
  //   z-index: 10000000;
  //   width: 1150px;
  import alPagination from '../Pagination'
    export default {
        name: 'AlTable',
        components:{
            alPagination
        },
        props: {
            fixedHeader:{
                default:false
            },
            leftArrowLeft:{
                default:"36"
            },
            rightArrowRight:{
                default:"36"
            },
            fixedLeft:{
                default:"36"
            },
            fixedTop:{
                default:"60"
            },
            showPostions:{
                type:Array,
                default(){
                    return [100,500]
                }
            },
            targetDomId:{
                default:''
            },
            autoFindPage:{
                type:Boolean,
                default:true
            },
            //自动生成模版的表格操作栏
            operations:{
                type:Object,
                default(){
                    return {}
                }
            },
            multipleValue:{
                type:Array,
                default(){
                    return []
                }
            },
            columns:{
                type:Array,
                default(){
                    return []
                }
            },
            rowClassName:{
                type:Function,
                default(){
                    return ({row, rowIndex})=>{
                        return ''
                    }
                }
            },
            headerRowClassName:{
                type:Function,
                default(){
                    return ({row, rowIndex})=>{
                        return ''
                    }
                }
            },
            cellClassName:{
                type:Function,
                default(){
                    return ({row, column, rowIndex, columnIndex})=>{
                        return ''
                    }
                }
            },
            headerCellClassName:{
                type:Function,
                default(){
                    return ({row, column, rowIndex, columnIndex})=>{
                        return ''
                    }
                }
            },
            data: Object, // 表格分页数据
            size: { // 尺寸样式
                type: String,
                default: 'medium'
            },
            align: {  // 文本对齐方式
                type: String,
                default: 'left'
            },
            maxHeight: {  // 表格最大高度
                type: Number,
                default: 3000
            },
            height: {  // 表格最大高度
                default: undefined
            },
            width: {  // 表格最大高度
                type: String,
                default: '100%'
            },
            border: {  // 是否显示边框
                type: Boolean,
                default: false
            },
            stripe: {  // 是否显示斑马线
                type: Boolean,
                default: false
            },
            highlightCurrentRow: {  // // 是否高亮当前行
                type: Boolean,
                default: false
            },
            loading:{         //加载状态
                type: Boolean,
                default: false
            },
            pageRequest:{       //分页查询的参数
                type: Object,
                default(){
                    return null
                }
            },
            rowKey:{
                type:String,
                default:""
            },
            showSummary:{
                type:Boolean,
                default:false
            },
            defaultExpandAll:{
                type:Boolean,
                default:false
            },
            columnsShow:{
                type:Array,
                default(){
                    return []
                }
            }
        },
        computed:{
            randomRef(){
                return 'al_table_'+Math.round(Math.random()*10000);
            },
            treeOption(){
                // if(this.rowKey){
                    return {children: 'children', hasChildren: 'hasChildren'}
                // }else{
                //     return null;
                // }
            },
            col(){
                return this.columns
            },
            content(){
                if(this.data&&this.data.content){
                    return this.data.content
                }else{
                    return []
                }

            }
        },
        watch:{
            targetDomId:{
                immediate:true,
                handler(){
                    console.log('我tm拿到id了')
                    console.log(this.targetDomId)
                    if(this.targetDomId!=''){
                        this.domTimer=setInterval(()=>{
                            console.log(document.getElementById(this.targetDomId))
                            if(document.getElementById(this.targetDomId)){
                                this.targetDom=document.getElementById(this.targetDomId);
                                clearInterval(this.domTimer);
                                this.domTimer=null;
                                this.scrollInit();
                            }
                        },200)
                    }else{
                        return null
                    }
                }
            },
            col:{
                handler(){
                    if(this.columns&&this.columns.length){
                        this.refreshPageRequest(1)
                    }
                }
            },
            columnsShow:{
                immediate:true,
                deep:true,
                handler(){
                    this.checkColumns();
                }
            }
        },
        data() {
            return {
                headerShow:false,
                domTimer:null,
                targetDom:null,
                selections: [],  // 列表选中列
                tableName:Math.floor(Math.random()*10000),
                tWdith:0
            }
        },
        methods: {
            fScroll(num){
                console.log(this.$refs[this.randomRef])
                this.$refs[this.randomRef].getElementsByClassName("el-table__body-wrapper")[0].scrollLeft+=num;
            },
            filterChange(filters){
                this.$emit("filterChange",filters)
            },
            checkColumns(){
                // console.log(this.$slots);
                //重置表格
                if(this.$refs.table&&this.$refs.table.$children){
                    for(var j=0;j<this.$refs.table.$children.length;j++){
                            this.$refs.table.$children[j].disableColumns=true;
                    }
                }
                //遍历配置，关闭对应字段
                if(this.columnsShow&&this.columnsShow.length){
                    for(var i=0;i<this.columnsShow.length;i++){
                        if(this.$refs.table&&this.$refs.table.$children){
                            for(var j=0;j<this.$refs.table.$children.length;j++){
                                if(this.$refs.table.$children[j].prop&&this.$refs.table.$children[j].prop==this.columnsShow[i]){
                                    // console.log("same:");
                                    // console.log(this.$refs.table.$children[j])
                                    this.$refs.table.$children[j].disableColumns=false;
                                }
                            }
                        }
                    }
                }
                if(this.$refs.table){
                    // console.log(this.$refs.table);
                    this.$refs.table.doLayout();
                }
            },
            //多选选择
            handleSelectionChange(v){
                this.$emit('input',v)
            },
            // 筛选条件更改
            sortChange: function ({column, prop, order}) {
                this.$emit('sortChange', {column:column, prop:prop, order:order})
            },
            // 行点击
            handleClick:function(row){
                this.$emit('handleClick',{row:row})
            },
            // 分页查询
            findPage: function (pageNum) {
                this.$emit('findPage',pageNum?pageNum:undefined)
            },
            // 选择切换
            selectionChange: function (selections) {
                this.selections = selections
                this.$emit('selectionChange', {selections:selections})
            },
            // 选择切换
            handleCurrentChange: function (val) {
                this.$emit('handleCurrentChange', {val:val})
            },
            // 换页刷新
            refreshPageRequest: function (pageNum) {
                this.findPage(pageNum)
            },
            watchWidth(){
                this.tWdith=document.getElementsByClassName('c'+this.tableName)[0].clientWidth;
            },
            scrollInit(){
                if(!window.alTableTarget){
                    window.alTableTarget=new alTableTarget();
                }
                window.alTableTarget.addObserver(this)
            },
            onScroll(e){
                console.log("我是"+this.randomRef+",滚动目标id为"+this.targetDomId);
                console.log(this.$refs);
                if(this.fixedHeader){
                    var d_el_table__header_wrapper = this.$refs[this.randomRef].getElementsByClassName("el-table__header-wrapper")[0];
                    var d_el_table__body_wrapper = this.$refs[this.randomRef].getElementsByClassName("el-table__body-wrapper")[0];
                    if(e.target.scrollTop>=this.showPostions[0]&&e.target.scrollTop<this.showPostions[1]&&this.headerShow==false){
                        this.headerShow=true;
                        console.log(d_el_table__header_wrapper.className)
                        var width=this.$refs[this.randomRef].getElementsByClassName("el-table__body-wrapper")[0].clientWidth;
                        d_el_table__body_wrapper.setAttribute("style","margin-top:"+d_el_table__header_wrapper.clientHeight+"px");
                        d_el_table__header_wrapper.setAttribute("style","position: fixed;top: "+this.fixedTop+"px;left: "+this.fixedLeft+"px;z-index: 2000;width: "+width+'px')
                        d_el_table__header_wrapper.className += ' hideGutter'
                    }
                    if(e.target.scrollTop<this.showPostions[0]||e.target.scrollTop>=this.showPostions[1]){
                        if(this.headerShow==true){
                            d_el_table__header_wrapper.setAttribute("style"," ")
                            d_el_table__body_wrapper.setAttribute("style","");
                        }
                        this.headerShow=false;
                    }
                }
            }
        },
        mounted() {
            this.checkColumns();
            // console.log(this.$refs.table)
            // for(var i=0;i<this.$refs.table.columns.length;i++){
            //     console.log(this.$refs.table.columns[i].property)
            // }
            window.addEventListener("resize",this.watchWidth);
            this.tWdith=document.getElementsByClassName('c'+this.tableName)[0].clientWidth;
            if(this.autoFindPage){
                this.refreshPageRequest(1)
            }
        },
        beforeDestroy(){
            if(window.alTableTarget){
                window.alTableTarget.removeObserver(this);
            }
            window.removeEventListener("resize",this.watchWidth);
        }
    }
</script>

<style scoped lang="scss">
  .el-table{
    /deep/{
      .hideGutter{
        .gutter{
          display: none;
        }
      }
    }
  }
  .urlLink{
    color: #1ACCBD;
    &:hover{
      text-decoration: underline;
    }
  }
  .el-table{
    /*padding-right: 30px;*/
    /*th{*/
    /*  /deep/{*/
    /*    .cell{*/
    /*      font-size: 14px;*/
    /*    }*/
    /*  }*/
    /*}*/
    /deep/{
      th>.cell{
        padding-left: 17px;
        font-size: 14px;
      }
      .cell{
        padding-left: 17px;
        font-size: 14px;
      }
      .caret-wrapper{
        height: 23px;
        vertical-align: top;
        .ascending{
          top: 0;
        }
        .descending{
          bottom: 0;
        }
      }
      thead{
        th:first-child{
          .cell{
            padding-left: 24px;
          }
        }
      }
      tbody{
        tr{
            td:first-child{
              .cell{
                padding-left: 24px;
              }
            }
        }
      }
    }
  }
  .el-table--medium{
    /deep/{
      td,th{
        padding: 12px 0;
      }
    }
  }
  /deep/ .el-table-column--selection .cell{
    text-align: center;
    padding-left: 14px!important;
    padding-right: 14px!important;
  }
  /deep/ .el-table__column-filter-trigger{
    margin-left: 5px;
    vertical-align: top;
    line-height: 23px;
  }
</style>
<style lang="scss">
  .arrowFixed{
    div{
      position: fixed;
      top: 50%;
      left: 0;
      width: 32px;
      height: 32px;
      border-radius: 50%;
      overflow: hidden;
      background: #979797;
      line-height: 32px;
      text-align: center;
      font-size: 18px;
      color: #fff;
      cursor: pointer;
      &:first-child{
        transform: rotate(180deg)
      }
      &:last-child{
        right: 0;
        left: auto;
      }
      z-index: 2000;
    }
  }
  .el-table-filter{
    border-radius:3px;
    &:before{
      content: '';
      position: absolute;
      width: 6px;
      height: 6px;
      border-top: 1px solid #EBEEF5;
      -webkit-transform: rotate(-45deg);
      transform: rotate(-45deg);
      top: -4px;
      right: 10px;
      background: #fff;
      border-right: 1px solid #EBEEF5;
    }
  }
</style>
