<template>
  <div>
    <el-row>
      <el-col class="btn-top" :span="12">
        <el-button type="primary" @click="saveData">设置范围</el-button>
        <el-button @click="clearData">清空</el-button>
      </el-col>
    </el-row>
    <el-tree
      :data="treeList"
      ref="tree"
      @check="checkChange"
      show-checkbox
      :default-checked-keys="choiceCheckList"
      :default-expanded-keys="choiceCheckList"
      node-key="code"
      :props="defaultProps"
    >
    </el-tree>
  </div>
</template>
<script>
import {
  major_sys,
  set_scope,
  get_scope,
  set_major_sys_scope,
} from "@/api/workScope.js";
export default {
  data() {
    return {
      treeList: [],
      choiceCheckList: [], //选中的树
      parentChecckList: [], //专业id
      defaultProps: {
        children: "children",
        label: "aliasName",
      },
    };
  },
  methods: {
    checkChange(node, choiceKey, v) {
      const list = [];
      let parentList = [];
      choiceKey.checkedNodes.forEach((item) => {
        if (item.children) {
          parentList.push({
            code: item.code,
            type: "major",
          });
        } else {
          list.push({
            code: item.code,
            type: "sys",
          });
        }
      });
      this.choiceCheckList = list;
      choiceKey.halfCheckedKeys.forEach((code) => {
        parentList.push({
          code: code,
          type: "major",
        });
      });
      this.parentChecckList = [...parentList];
      console.log(this.parentChecckList);
    },
    majorSys() {
      major_sys({ target: "rtn" }).then((res) => {
        this.treeList = res.rtn;
        this.readData();
      });
    },
    readData() {
      const data = { type: "sys", target: "rtn" };
      get_scope(data).then((res) => {
        this.choiceCheckList = res.rtn.map((a) => {
          return a.code;
        });
      });
    },
    // 保存数据
    saveData() {
      let data = {
        type: "sys",
        target: "action",
        codes: [...this.choiceCheckList, ...this.parentChecckList],
      };
      set_major_sys_scope(data).then(() => {
        this.readData();
      });
    },
    //清空
    clearData() {
      this.$confirm("是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.choiceCheckList = [];
          this.$refs.tree.setCheckedKeys([]);
          this.saveData();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  created() {
    this.majorSys();
  },
};
</script>
<style lang="less" scoped>
.btn-top {
  margin-bottom: 12px;
  display: flex;
  justify-content: flex-end;
}
</style>