<template>
  <!--  v-get-height-->
  <!--  :max-height="50 * (pageSize + 1)"-->
  <!--  :height="57 * (pageSize + 1) - 9"-->
  <el-table

    :header-cell-style="rowStyle"
    @row-click="clickTableTr"
    v-on="{...tableEventObj}"
    :height="isHeightEqualMaxHeight?maxHeight:undefined"
    :cell-style="rowStyle"
    ref="table"
    v-get-height
    @selection-change="selectChange"
    :size="size"
    :max-height="maxHeight"
    :data="(isSingleSelect || multiSelect)?myTableData.filter(filterMeothod):myTableData.filter(filterMeothod)"
    style="width: 100%"
    v-bind="$attrs"

  >
    <el-table-column width="60px" v-if="isSingleSelect">
      <template #default="scope">
        <!--        v-model="scope.row['checked']"-->
        <el-checkbox  v-bind="singleBoxAttr" @change="setSingleSelect(scope.row,$event)" :model-value="allSelected.indexOf(scope.row) !== -1"/>
      </template>
    </el-table-column>
    <el-table-column v-if="(!tableData?.find(i => i?.RN) && isHasOrder)" width="80px"   type="index" label="序号" :index="1" >
    </el-table-column>
    <slot name="selectionBefore" />
    <el-table-column
      v-if="hasSelection"
      type="selection"
      v-bind="columnAtrr"
      width="selectionWidth"
    >
    </el-table-column>
    <el-table-column v-if="multiSelect" width="55" v-bind="multiSelectAttrs">
      <template #header="scope">


        <!--        v-model="isAllSelect"-->
        <!--        :indeterminate="myTableData.filter(i => i.checked).length > 0 && myTableData.filter(i => i.checked).length < myTableData.length" -->
        <el-checkbox  :indeterminate="allSelected.length > 0 && allSelected.length < myTableData.length"  :model-value="allSelected.length  > 0 && (allSelected.length === myTableData.length)" @change="changeIsAllSelect(scope,$event,true)" v-bind="mulitAllSelectBoxAttr"   />
      </template>
      <template #default="scope">
        <!--        v-model="scope.row['checked']"-->

        <el-checkbox :model-value="isSelect(scope.row)" v-bind="mulitSelectBoxAttrSelect" @change="changeE(scope.row,$event,true)"   />
      </template>

    </el-table-column>
    <slot name="header" :header="headers">
      <el-table-column
        width="100px"
        v-if="tableData.find(i => i?.RN) &&isHasOrder"
        prop="RN"
        label="序号"
      >
        <template #default="scope">
          {{ scope.row['RN']|| (tableData.findLast(i => i.RN)?tableData.findLast(i => i.RN).RN+1:1) }}
        </template>
      </el-table-column>

      <el-table-column
        :key="index"
        class="cl"
        :width="header.width"
        v-for="(header, index) in headers"
        :prop="header.prop"
        :label="header.label"
        show-overflow-tooltip
        v-bind="headers.attrs"
      >
        <template #default="scope">
          <slot :name="header.prop" :data="scope.row" :index="scope.$index">
            {{ scope.row[header.prop] }}
          </slot>
        </template>
      </el-table-column>

    </slot>

    <el-table-column


      :width="operationWidth"




      @click.stop=""
      v-if="hasOperation"


      label="操作"
    >
      <template #default="scope">
        <slot name="operation" :data="scope.row" :index="scope.$index" />
        <!--        <div class="operation">-->
        <!--         -->
        <!--        </div>-->

        <!--        <span>{{scope.$index}}</span>-->
      </template>

    </el-table-column>
    <slot name="selectionAfter" />
  </el-table>
</template>

<script >
import {computed, nextTick, onMounted, ref, watch} from "vue";

const getHeightDirective = (el, binding, ele) => {

  // nextTick(() => {
  //   let _this = ele.dirs[0].instance
  //   let scrollEle = el.querySelector(".el-table__body-wrapper")
  //   if (_this.pageSize) {
  //     // 如果传了pageSize
  //     let myMax = (_this.pageSize + 1) * _this.eachTrHeight
  //
  //     if ((+myMax < el.parentElement.clientHeight) && !_this.isHeightByAuto) {
  //
  //       myMax = +el.parentElement.clientHeight
  //     }
  //     _this.maxHeight = myMax
  //     // ele.style['max-height'] = (ele.context.pageSize + 1) * 50+ 'px'
  //     scrollEle.style["max-height"] = myMax - _this.eachTrHeight + "px"
  //   } else {
  //     if (!_this.isHeightByAuto) {
  //       _this.maxHeight = el.parentElement.clientHeight
  //     } else {
  //       //不滚动,没有最大高度这种
  //       _this.maxHeight = 10000
  //     }
  //
  //     scrollEle.style["max-height"] =
  //       _this.maxHeight - _this.eachTrHeight + "px"
  //   }
  // })

  nextTick(() => {
    let _this = ele.dirs[0].instance
    let scrollEle = el.querySelector(".el_scrollbar_warp")
    if (_this.pageSize) {
      // 定死
      // 如果传了pageSize
      let myMax = (_this.pageSize + 1) * _this.eachTrHeight
      // isHeightByAuto高度是否自动撑开
      if ((+myMax < el.parentElement.clientHeight) && !_this.isHeightByAuto) {

        myMax = +el.parentElement.clientHeight
      }
      _this.maxHeight = myMax
      // ele.style['max-height'] = (ele.context.pageSize + 1) * 50+ 'px'
      // scrollEle.style["max-height"] = myMax - _this.eachTrHeight + "px"
    } else {
      if (!_this.isHeightByAuto) {
        _this.maxHeight = el.parentElement.clientHeight
      } else {
        //不滚动,没有最大高度这种
        _this.maxHeight = 100000
      }
    }
  })
}
export default {
  name: "MyTable",

  props: {
    isHasOrder:{
      default:true
    },
    mulitAllSelectBoxAttr:{
      //   多选checkbox
    },
    mulitSelectBoxAttrSelect:{

    },
    multiSelectAttrs:{

    },
    multiSelect:{
      // 是否可以多选
    },
    filterMeothod:{
      default() {
        return (data) => {
          return  true
        }
      }
    },
    columnAtrr:{

    },
    singleBoxAttr:{

    },
    isSingleSelect:{
      default:false
    },
    isSelectHeight: {
      default: false
    },
    pageSize: {},
    tableData: {},
    headers: {},
    hasSelection: {
      default: false,
      type: Boolean
    },
    hasOperation: {
      default: false,
      type: Boolean
    },
    selectionWidth: {
      default: 55
    },
    operationWidth: {
      default: 240
    },
    size: {
      default() {
        return "default"
      }
    },
    eachTrHeight: {
      default: 50
    },
    //父元素没有设置高度,height也没有flex1这种
    isHeightByAuto: {
      default: true
    },
    isImmediate:{
      default:true
    },
    tableEventObj:{
      default() {
        return {

        }
      }
    },
    isHeightEqualMaxHeight:{
      default:false
    }
  },

  setup(props,{emit}) {
    const table = ref(null)
    const allSelected = ref([])
    function selected(row) {
      return false
    }

    function clickTableTr(row, column, event) {
      emit("clickTableTr", row, column, event)
    }
    onMounted(() => {

      if (!props.pageSize && !props.isHeightByAuto) {
        window.addEventListener("resize", () => {
          let el = table.value?.$el
          if (!el) return
          if (props.pageSize) {

            // 定死
            // 如果传了pageSize
            let myMax = (props.pageSize + 1) * props.eachTrHeight
            // isHeightByAuto高度是否自动撑开
            if ((+myMax < el.parentElement.clientHeight) && !props.isHeightByAuto) {

              myMax = +el.parentElement.clientHeight
            }
            maxHeight.value = myMax
            // ele.style['max-height'] = (ele.context.pageSize + 1) * 50+ 'px'
            // scrollEle.style["max-height"] = myMax - _this.eachTrHeight + "px"
          } else {
            if (!props.isHeightByAuto) {
              maxHeight.value = el.parentElement.clientHeight
            } else {
              //不滚动,没有最大高度这种
              maxHeight.value = 100000
            }
          }
        })
      }

    })
    function selectChange(select,isUserSelect2) {
      console.log('改变的值',select,isUserSelect2)

      // let find
      allSelected.value = select
      emit("getCheckedTable", select,isUserSelect2)
    }
    const isSelect = ref(function (row) {
      return allSelected.value.indexOf(row) !== -1
    })
    // function isSelect(row) {
    //
    // }
    function changeIsAllSelect(s,isChecked,isUserSelect2) {
      // console.log('allisChecked',s,isChecked)
      // myTableData.value.forEach(i => {
      //   i.checked = Boolean(isAllSelect.value)
      // })
      //
      // selectChange(myTableData.value.filter(i => i.checked).map(i => {
      //   let obj = {...i}
      //   delete obj.checked
      //   return obj
      // }))
      console.log('allisChecked',isChecked)
      allSelected.value = []
      if (isChecked) {
        myTableData.value.forEach(i => {
          allSelected.value.push(i)
        })

      }
      selectChange(allSelected.value)

    }
    function changeE(row,isChecked,isUserSelect2) {
      // let isNotAllSelect = myTableData.value.find(i => !i.checked)
      // isAllSelect.value = !isNotAllSelect
      // selectChange(myTableData.value.filter(i => i.checked).map(i => {
      //    let obj = {...i}
      //    delete obj.checked
      //    return obj
      // }))
      console.log('isChecked',isChecked,row)
      if (isChecked) {
        allSelected.value.push(row)
      }else {

        allSelected.value.splice(allSelected.value.indexOf(row),1)
      }
      selectChange(allSelected.value,isUserSelect2)


    }

    const isAllSelect = ref(false)
    let myTableData = ref([])
    const isUserChange = ref(false)

    const  maxHeight= ref(0)

    watch(() => props.tableData,(value,oldValue) => {
      myTableData.value = []



      ;(value||[]).forEach(i => {
        let obj = i
        // if (props.isSingleSelect || props.multiSelect) {
        //   obj.checked=i.checked || false
        // }

        myTableData.value.push(obj)
      })
      allSelected.value = []
      if (props.isSingleSelect) {

        emit("getSingleCheckedChange", {})

      }else if (props.multiSelect){
        selectChange(allSelected.value)
      }else if (props.hasSelection){
        selectChange(allSelected.value)
      }
      // myTableData.value = value.map(i =>({
      //   ...i,
      //   checked:i.checked || false,
      //   myId:uuidv4()
      // }))
    },{
      deep:true,
      immediate:props.isImmediate
    })
    function setMulitiSelect(row,isChecked=true,isUser){
      let isEqual =  myTableData.value.find(item => {
        return Object.keys(row).every(key => row[key] === item[key])
      })
      if (isEqual) {
        console.log('找到了的',isEqual.CODE,isChecked)
      }

      // setMulitiSelect(isEqual,isChecked)
      // ;(isEqual&&(isEqual.checked = isChecked))
      changeE(isEqual,isChecked,isUser)

    }
    function setSingleSelect(row) {
      let equalObject = null
      // 后来写法
      let findItem = myTableData.value.find(item => {
        return Object.keys(row).every(key => row[key] === item[key])
      })
      // 原来写法
      // myTableData.value.forEach(item => {
      //   let isEqual = Object.keys(row).every(key => row[key] === item[key])
      //   if (isEqual) {
      //
      //
      //     equalObject = item
      //   }
      //   item.checked = Boolean(isEqual)
      //
      // })
      allSelected.value = [findItem]
      emit("getSingleCheckedChange", findItem)
    }
    const rowStyle = computed(() => {
      return {
        height:props.eachTrHeight + 'px'
      }
    })

    return {
      myTableData,
      setSingleSelect,
      maxHeight,
      isAllSelect,
      changeIsAllSelect,  // function rowStyle(){
      //   console.log(props.eachTrHeight,'props.eachTrHeight')
      //  return {
      //
      //  }
      // }lect,
      changeE,
      selectChange,
      setMulitiSelect,
      clickTableTr,
      selected,
      table,
      allSelected,
      isSelect,
      isUserChange,
      rowStyle
    }
  },
  directives: {
    getHeight:getHeightDirective,
    getOperationWidth(el, binding, ele){
      nextTick(() => {
        console.log('年到二',el,el.parentNode,el.offsetWidth,ele)
      })
    }
  }
}
</script>
<style scoped lang="scss">
//:deep{
//  .el-table__body-wrapper{
//    .cell{
//      height: 100%;
//      line-height: 50px;
//
//    }
//    overflow: auto;
//  }
//}
.el-table {
  :deep{
    .btn-td{
      .cell{
        white-space: nowrap;

        //width: max-content !important;
      }
    }
  }
  //min-height: 100% !important;
  &.el-table--striped {
    :deep {
      .el-table__body tr.el-table__row--striped td {

      }
    }
  }
  :deep {
    tr.active,
    .tr.active:hover {
      td.el-table__cell {
        background: transparent !important;
      }

    }
    th {
      //background-color: rgba(63, 159, 255, 0.2);
      font-size: 13px;


      font-weight: bolder;
    }
    td {
      font-size: 14px;
    }
    td,
    th {
      color: #676a6c;
      height: 100%;
      //line-height: 50px;
      box-sizing: border-box;
      //height: 50px;
      padding: 0;
    }
  }
}
.operation{
  width: 200px;
}
.el-table:before {
  height: 0;
}
</style>
