<template>
  <el-button @click="showDialog = true">
    <el-icon><Setting /></el-icon>
    表头配置
  </el-button>

  <el-dialog
    v-model="showDialog"
    title="表头配置"
    width="700px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    align-center
    :close-close="handleClose"
    @open="initFields"
  >
    <el-checkbox-group v-model="selectedFields">
      <el-row>
        <el-col
          v-for="field in props.fields"
          :key="field.field"
          :span="4"
          style="margin-bottom: 10px"
        >
          <el-checkbox :label="field.field" :value="field.field">
            {{ field.name }}
          </el-checkbox>
        </el-col>
      </el-row>
    </el-checkbox-group>

    <template #footer>
      <el-button @click="showDialog = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Setting } from '@element-plus/icons-vue';

  defineOptions({
    name: 'TableFieldConfig',
  });

  interface Field {
    name: string;
    field: string;
  }

  const props = withDefaults(
    defineProps<{
      fields: Field[];
      modelValue?: string[];
    }>(),
    {
      fields: () => [],
      modelValue: () => [],
    }
  );

  const emit = defineEmits(['update:modelValue', 'change']);

  const showDialog = ref(false);
  const originalFields = ref<string[]>([]);
  const selectedFields = ref<string[]>([]);

  // 初始化字段数据
  const initFields = () => {
    // 初始化选中的字段
    selectedFields.value =
      props.modelValue.length === 0
        ? props.fields.map((field) => field.field)
        : [...props.modelValue];
    // 保存原始状态用于重置
    originalFields.value = [...selectedFields.value];
  };

  // 确认配置
  const handleConfirm = () => {
    if (selectedFields.value.length === 0) {
      ElMessage.warning('请至少选择一个字段');
      return;
    }
    emit('update:modelValue', selectedFields.value);
    emit('change', selectedFields.value);
    showDialog.value = false;
  };

  // 关闭弹窗
  const handleClose = (done: () => void) => {
    // 恢复到打开弹窗前的状态
    selectedFields.value = [...originalFields.value];
    done();
  };
</script>
