<template>
  <div>
    <vxe-modal :value="isShow"
               show-footer
               :z-index="zIndex"
               title="绑定权限"
               show-confirm-button
               :width="600"
               :height="600"
               esc-closable
               @input="e => $emit('update:isShow',e)">
      <template>
        <Treeselect v-model="form.permission_id"
                    :options="tableData"
                    flat
                    always-open
                    multiple
                    clearable
                    noChildrenText="无子菜单"
                    :normalizer="node => ({
                        id: node.id,
                        label: node.name,
                        children: node.children,
                        isDefaultExpanded: true
                      })"></Treeselect>
      </template>

      <template #footer>
        <el-button type="primary" :loading="loading" @click="submit">确认</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
import { setPermissions, getPermissions } from "@/api/module"
import { PopupManager } from 'element-ui/lib/utils/popup'
export default {
  props: {
    moduleId: [String,Number],
    isShow: {
      type: Boolean,
      default: false,
      required: true
    }
  },
  data() {
    return {
      zIndex: PopupManager.nextZIndex(),
      loading: false,

      tableData: [],
      total: 0,
      form: {
        id: "",
        permission_id: []
      }
    }
  },
  methods: {
    /**
     * @param {array[string]} keys
     * @param {array[all]} values
     * @returns {void}
     */
    setForm (keys = [],values = []) {
      keys.forEach((key, index) => {
        this.form[key] = values[index]
      })
    },

    async getPermission () {
      const res = await getPermissions({
        module_id: this.moduleId
      })
      this.tableData = res;
    },

    async submit () {
      this.loading = true;
      try {
        this.form.id = this.moduleId
        await setPermissions(this.form)
        this.$emit("update:isShow",false)
        this.$emit("refresh")
        this.loading = false;
      } catch (err) {
        this.loading = false;
      }
    }
  },
  watch: {
    isShow(newVal) {
      if (newVal) {
        this.getPermission()
        this.zIndex = PopupManager.nextZIndex()
      }
    },
  },
  computed: {},
  created() {
    this.getPermission()
  }
}
</script>

<style scoped lang="scss">
.total {
  color: #666;
  text-align: right;
  line-height: 3;
}
</style>
