<template>
  <div>
    <a-button html-type="submit" type="text" @click="openModel" class="open-btn">
      <template #icon>
        <setting-outlined/>
      </template>
      字段设置
    </a-button>
    <!-- 字段设置对话框 -->
    <a-modal v-model:visible="columnsSettingsVisible" title="字段设置" width="600px">
      <!-- 字段列表 -->
      <div>
        <a-checkbox-group v-model:value="checkedColumnsList">
          <div class="check-div">
            <a-checkbox v-for="(item, index) in tableColumns" :key="index" :value="item.key"
                        :disabled="item.isDisabled">
              {{ item.title }}
            </a-checkbox>
          </div>
        </a-checkbox-group>
      </div>
      <!-- 功能按钮 -->
      <template #footer>
        <div style="width:100%;display: flex; justify-content: space-between">
          <div>
            <a-button key="back" @click="onCheckAll(true)">全选</a-button>
            <a-button key="back" @click="onCheckAll(false)">反选</a-button>
          </div>
          <div>
            <a-button key="back" @click="onClose">取消</a-button>
            <a-button key="submit" type="primary" @click="onSubmit">确定</a-button>
          </div>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {ref} from "vue";

const props = defineProps(["tableColumns", "checkedTableColumns"]);
const emits = defineEmits(["onCheck"]);

// 对话框开关
const columnsSettingsVisible = ref<boolean>(false)
// 已选择的表格列
const checkedColumnsList = ref<Array<any>>([]);

// 开启对话框
function openModel() {
  columnsSettingsVisible.value = true;
  checkedColumnsList.value = props.checkedTableColumns.map((item: any) => item.key);
}

// 全选 or 反选
function onCheckAll(isChecked: boolean) {
  if (isChecked) {
    checkedColumnsList.value = props.tableColumns.map((item: any) => item.key);
  } else {
    checkedColumnsList.value = props.tableColumns.map((item: any) => {
      if (checkedColumnsList.value.findIndex((x: any) => x == item.key)<0) {
        return item.key;
      }
    });
  }
}

// 关闭对话框
function onClose() {
  columnsSettingsVisible.value = false;
  checkedColumnsList.value = []
}

// 确定选择
function onSubmit() {
  emits("onCheck", JSON.parse(JSON.stringify(checkedColumnsList.value)));
  onClose();
}
</script>

<style scoped>
.open-btn {
  display: flex;
  align-items: center;
  color: #6b6b6b;
}

.check-div {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  column-gap: 8px;
  row-gap: 12px;

  .ant-checkbox-wrapper {
    margin-left: 8px !important;
  }
}
</style>
