<template>
  <div>
    <Modal v-model="dialog" width="600px" title="数据列管理" @on-ok="onOk">
      <Row>
        <i-col :span="24">
          <Checkbox
            @on-change="setAll"
            style="margin-bottom: 5px;margin-left: 15px;"
            v-model="all"
            >全选</Checkbox
          >
        </i-col>
        <template v-for="column in columns">
          <i-col
            :span="8"
            :key="column.tkey || column.key"
            v-if="column.tkey || (column.key && column.type != 'expand')"
          >
            <Checkbox
              v-model="map[column.tkey || column.key]"
              style="margin-bottom: 5px;margin-left: 15px;"
              >{{ column.title }}</Checkbox
            >
          </i-col>
        </template>
      </Row>
    </Modal>
  </div>
</template>
<script>
export default {
  props: {
    name: String,
    visible: Boolean,
    columns: {
      default: []
    }
  },
  name: "z-table-column",
  data() {
    return {
      dialog: this.visible,
      map: {},
      all: true
    };
  },
  watch: {
    visible() {
      this.dialog = this.visible;
    },
    dialog() {
      this.$emit("update:visible", this.dialog);
      if (this.dialog) {
        this.initMap();
      }
    },
    map: {
      deep: true,
      handler() {
        this.initAll();
      }
    }
  },
  methods: {
    initMap() {
      let local = sessionStorage.getItem(this.name);
      if (local) {
        local = JSON.parse(local);
        local = local.columns;
      }
      this.columns.forEach(column => {
        if (local) {
          this.$set(
            this.map,
            column.tkey || column.key,
            local.findIndex(l => atob(l) == (column.tkey || column.key)) > -1
          );
        } else {
          this.$set(this.map, column.key, true);
        }
      });
    },
    onOk() {
      const columns = [];
      this.columns.forEach(column => {
        if (this.map[column.tkey || column.key]) {
          if (!column.minWidth && !column.width) {
            column.width = 80;
          }
          columns.push(column);
        } else if (column.type == "expand") {
          columns.push(column);
        }
      });
      sessionStorage.setItem(
        this.name,
        JSON.stringify({ columns: columns.map(c => btoa(c.tkey || c.key)) })
      );
      // 给最后一列不定宽度的空数据，使他充满整个屏幕宽度
      columns.push({ title: " ", minWidth: 10 });

      this.$emit("on-select", columns);
    },
    initAll() {
      let all = true;
      Object.keys(this.map).forEach(key => {
        if (this.map[key] == false) {
          all = false;
        }
      });
      this.all = all;
    },
    setAll(all) {
      Object.keys(this.map).forEach(key => {
        this.map[key] = all;
      });
    }
  }
};
</script>

<style></style>
