<template>
  <el-button
    :icon="Tools"
    color="#ac014d"
    class="column-set-button"
    @click="dialogShow"
  />
  <Dialog
    :flag="dialogFlag"
    width="1080px"
    msg-title="列设置"
    @submit-form="submitHandler"
    @reset-form="dialogHide"
  >
    <div class="dialog-content">
      <div v-for="columnGroup in columnGroups" :key="columnGroup.title">
        <div class="group-title">{{ columnGroup.title }}</div>
        <el-checkbox-group
          v-model="checkedGroups[columnGroup.title]"
          size="large"
        >
          <el-checkbox
            v-for="tableColumn in columnGroup.columns"
            :key="tableColumn.columnProp"
            :label="tableColumn.columnProp"
            >{{ tableColumn.columnName }}</el-checkbox
          >
        </el-checkbox-group>
      </div>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { Tools } from '@element-plus/icons-vue'
import Dialog from '@/components/dialog/index.vue'

export interface tableColumn {
  columnName: string
  columnProp: string
  groupTitle: string
}
export interface tableColumnGroup {
  title: string
  columns: tableColumn[]
}

const props = defineProps({
  tableColumns: {
    type: Array<tableColumn>,
    required: true,
  }
})

const emits = defineEmits(['checkedSubmit'])

const dialogFlag = ref(false)
const dialogShow = () => {
  dialogFlag.value = true
}
const dialogHide = () => {
  dialogFlag.value = false
}

const checkedGroups = computed(() => {
  const groups = {}
  props.tableColumns.forEach(({ columnProp, groupTitle }) => {
    if (groups[groupTitle] && groups[groupTitle] instanceof Array) {
      groups[groupTitle].push(columnProp)
    } else {
      groups[groupTitle] = [columnProp]
    }
  })
  return groups
})
const columnGroups = computed(() => props.tableColumns.reduce((pre: tableColumnGroup[], curr) => {
  const theGroup = pre.find(columnGroup => columnGroup.title === curr.groupTitle)
  if (theGroup) {
    theGroup.columns.push(curr)
  } else {
    pre.push({
      title: curr.groupTitle,
      columns: [curr]
    })
  }
  return pre
}, []))
const checkedColumnProps = computed<string[]>(() => Object.getOwnPropertyNames(checkedGroups.value).map(prop => checkedGroups.value[prop]).flat())

const submitHandler = () => {
  emits('checkedSubmit', checkedColumnProps.value)
  dialogHide()
}
</script>

<style scoped lang="scss">
.column-set-button {
  width: 30px;
  height: 30px;
  border-radius: 4px;
  font-size: 14px;
}

.dialog-content {
  padding: 0 22px;

  .group-title {
    font-size: 16px;
    font-family: Microsoft YaHei;
    font-weight: bold;
    color: #303133;
    margin-bottom: 22px;
  }
}
</style>
