<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="eqList"
      show-checkbox
      ref="tree"
      node-key="aliasCode"
      @check="checkChange"
      :default-checked-keys="choiceCheckList"
      :default-expanded-keys="choiceCheckList"
      :props="defaultProps"
    >
    </el-tree>
  </div>
</template>
<script>
import {
  sys_eq,
  set_scope,
  get_scope,
  sys_eq_for_scope,
} from "@/api/workScope.js";

export default {
  data() {
    return {
      eqList: [],
      defaultProps: {
        children: "children",
        label: "aliasName",
      },
      choiceCheckList: [],
    };
  },
  methods: {
    checkChange(node, choiceKey, v) {
      const list = [];
      choiceKey.checkedKeys.forEach((msg) => {
        if (msg != undefined) {
          list.push(msg);
        }
      });
      this.choiceCheckList = list;
    },
    // 专业系统设备树
    getSys_eq_tree() {
      sys_eq_for_scope({ target: "rtn" }).then((res) => {
        this.eqList = res.rtn;
        this.readData();
      });
    },
    readData() {
      const data = { type: "device", target: "rtn" };
      get_scope(data).then((res) => {
        this.choiceCheckList = res.rtn.map((a) => {
          return a.code;
        });
      });
    },
    // 保存数据
    saveData() {
      let data = {
        type: "device",
        target: "action",
        codes: this.choiceCheckList,
      };
      set_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.getSys_eq_tree();
  },
};
</script>
<style lang="less" scoped>
.btn-top {
  margin-bottom: 12px;
  display: flex;
  justify-content: flex-end;
}
</style>