<template>
  <div class="tool-bar-container">
    <el-dropdown trigger="click">
      <el-button icon="Setting" size="small" round :loading="loading">列设置</el-button>
      <template #dropdown>
        <el-dropdown-menu>
          <span class="title" style="margin: 4px 14px;">列设置</span>
          <Draggable class="t_table_column_setting_dropdown" v-model="state.columnSet" item-key="prop">
            <template #item="{element,index}">
              <div v-if="!element.regular && element.prop"><el-dropdown-item>
                <el-checkbox :checked="!element.hidden" @click.native.stop :disabled="element.checkBoxDisabled"
                  @change="checked => checkChanged(checked, index)">
                  {{element.label}}
                </el-checkbox>
              </el-dropdown-item></div>
            </template>
          </Draggable>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup name="ColumnSet">
import Draggable from 'vuedraggable'
import { watch, reactive } from 'vue'
const props = defineProps({
  columns: {
    type: Array,
    default: () => []
  },
  title: {
    type: String,
    default: ''
  },
  name: {
    type: String,
    default: ''
  },
  loading: {
    type: Boolean,
    default: false
  }
})
// 初始化
const initColumnSet = (arr) => {
  let columns = arr && arr.length ? arr : props.columns
  const columnSet = columns.map((col, index) => {
    return {
      label: col.label,
      prop: col.prop,
      hidden: col.hidden || false,
      regular: col.regular,
      checkBoxDisabled: false
    }
  })
  return columnSet
}
// 抛出事件
const emits = defineEmits(['columnSetting'])
const state = reactive({
  columnSet: []
})
watch(()=>props.columns, (columnsVal)=>{
  state.columnSet = initColumnSet(columnsVal)
},{deep:true, immediate:true})
// checkbox改变选中状态
const checkChanged = (checked, index) => {
  state.columnSet[index].hidden = !checked
  let obj = {}
  state.columnSet.map(val => {
    val.hidden in obj || (obj[val.hidden] = [])
    obj[val.hidden].push(val.hidden)
  })
  if (obj.false && obj.false.length < 2) {
    state.columnSet.map((val, key) => {
      if (!val.hidden) {
        state.columnSet[key].checkBoxDisabled = true
      }
    })
  } else {
    state.columnSet.map((val, key) => {
      if (!val.hidden) {
        state.columnSet[key].checkBoxDisabled = false
      }
    })
  }
  emits('columnSetting', state.columnSet)
}
</script>
<style lang="scss">
.tool-bar-container{
  width: 100%;
  text-align: right;
  margin-bottom: 6px;
}
.el-dropdown__popper .el-dropdown-menu{
  max-height: 400px;
  overflow: auto;
}
.el-dropdown-menu__item{
  padding: 0 16px;
}
</style>