<template>
  <!-- 列设置 -->
  <el-drawer v-model="drawerVisible" title="列设置" size="450px" @close="saveColSetting">
    <div class="table-main">
      <el-table :data="colSetting" :border="true" row-key="prop" default-expand-all :tree-props="{ children: '_children' }">
        <el-table-column prop="label" align="center" label="列名" />
        <el-table-column v-slot="scope" prop="isShow" align="center" label="显示">
          <el-switch v-model="scope.row.isShow" @change="() => onSettingChange()"></el-switch>
        </el-table-column>
        <!-- <el-table-column v-slot="scope" prop="sortable" align="center" label="排序">
          <el-switch v-model="scope.row.sortable" @change="() => onSettingChange()"></el-switch>
        </el-table-column> -->
        <template #empty>
          <div class="table-empty">
            <img src="@/assets/images/notData.png" alt="notData" />
            <div>暂无可配置列</div>
          </div>
        </template>
      </el-table>
    </div>
  </el-drawer>
</template>

<script setup lang="ts" name="ColSetting">
import { ref, onMounted } from "vue";
import { ColumnProps } from "@/components/ProTable/interface";

const props = defineProps<{ colSetting: ColumnProps[] }>();

const drawerVisible = ref<boolean>(false);

// 生成缓存key
const getStorageKey = () => {
  const routePath = window.location.pathname;
  return `pro-table-col-setting-${routePath}`;
};

// 从localStorage读取列配置
const loadColSetting = () => {
  const storageKey = getStorageKey();
  const savedSetting = localStorage.getItem(storageKey);
  if (savedSetting) {
    try {
      const parsed = JSON.parse(savedSetting);
      props.colSetting.forEach(col => {
        const savedCol = parsed.find((item: any) => item.prop === col.prop);
        if (savedCol) {
          col.isShow = savedCol.isShow;
          col.sortable = savedCol.sortable;
        }
      });
    } catch (e) {
      console.error("加载列配置失败:", e);
    }
  }
};

// 保存列配置到localStorage
const saveColSetting = () => {
  const storageKey = getStorageKey();
  const settingToSave = props.colSetting.map(col => ({
    prop: col.prop,
    isShow: col.isShow,
    sortable: col.sortable
  }));
  localStorage.setItem(storageKey, JSON.stringify(settingToSave));
};

// 设置变更时自动保存
const onSettingChange = () => {
  saveColSetting();
};

const openColSetting = () => {
  drawerVisible.value = true;
};

onMounted(() => {
  loadColSetting();
});

defineExpose({
  openColSetting
});
</script>

<style scoped lang="scss">
.cursor-move {
  cursor: move;
}
</style>
