<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>
        <i-col
          :span="8"
          v-for="column in columns"
          :key="column.key"
          v-if="column.key"
        >
          <Checkbox
            v-model="map[column.key]"
            style="margin-bottom: 5px;margin-left: 15px;"
          >
            {{ column.title }}</Checkbox
          >
        </i-col>
      </Row>
    </Modal>
  </div>
</template>
<script>
import $ls from "../libs/store";
export default {
  props: {
    name: String,
    visible: Boolean,
    columns: {
      default: []
    },
    defaultFields: {
      type: Array,
      default: () => []
    }
  },
  name: "f-col",
  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 = $ls.get(this.name);
      if (local == undefined && this.defaultFields.length > 0) {
        local = this.defaultFields;
      }

      this.columns.forEach(column => {
        if (local) {
          this.$set(
            this.map,
            column.key,
            local.findIndex(l => l == column.key) > -1
          );
        } else {
          this.$set(this.map, column.key, true);
        }
      });
    },
    onOk() {
      const columns = [];
      this.columns.forEach(column => {
        if (this.map[column.key]) {
          columns.push(column);
        }
      });
      $ls.set(this.name, columns.map(c => c.key));
      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>
