<style>
</style>

<template>
  <div>
    <Form ref="formInline">
      <FormItem prop="user" label="选择角色：" :label-width="100">
        <Input v-model="roleNames" @on-focus="openRoleSelect" placeholder="" />
      </FormItem>
      
    </Form>
    <Modal v-model="value" title="选择角色" @on-ok="ok" @on-cancel="closeModal">
      <div>
        <Tree
          ref="tree"
          :data="roleTree"
          :load-data="loadRoleData"
          show-checkbox
        ></Tree>
      </div>
    </Modal>
  </div>
</template>
<script>
export default {
  components: {},
  props: {
    checkedList: { type: Object, default: () => ({title: [], value: []}) },
    bizAttr: { type: Object },
  },
  data() {
    return {
      value: false,
      roleNames: this.checkedList.title,
      roleTree: [],
      formData: this.checkedList,
    };
  },
  mounted() {
  },
  methods: {
    queryRoleGroup() {
      GMS.$http.get(`/nvwa-authority-role/v1/query-group`).then((res) => {
        if (res.status == 200) {
          this.roleTree = this.formatTree(res.data);
        }
      });
    },
    loadRoleData(item, callback) {
      GMS.$http
        .get(`/nvwa-authority-role/v1/query-child`, {
          params: { value: item.id },
        })
        .then((res) => {
          if (res.status == 200) {
            callback(this.formatTree(res.data, item.children));
          }
        });
    },
    formatTree(data) {
      return data.map((element) => {
        var checked = this.formData.value && this.formData.value.includes(element.id);
        if (element.hasOwnProperty("leaf"))
          return {
            title: element.title,
            loading: false,
            id: element.id,
            leaf: false,
            children: [],
          };
        else
          return {
            title: element.title,
            id: element.id,
            checked: checked,
            leaf: true,
          };
      });
    },
    openRoleSelect() {
      this.queryRoleGroup();
      this.value = true;
    },
    ok() {
      var checkedNodes = this.$refs.tree
        .getCheckedNodes()
        .filter((node) => node.leaf)
        .map((node) => {
          return { id: node.id, name: node.title };
        });
      this.formData = {
        name: 'roles',
        title: checkedNodes.map((e) => e.name),
        value: checkedNodes.map((e) => e.id)
      }
      this.roleNames = checkedNodes.map((e) => e.name);
      this.$emit("on-ok", checkedNodes);
      this.closeModal();
    },
    closeModal() {
      this.value = false;
    },
  },
};
</script>

