<template>
  <div class="bf-permissiontree">
    <!-- 权限树 -->
    <div class="cont">
      <div class="paren_header">
        <p>{{ title }}</p>
      </div>
      <div class="paren_type">
        <ul>
          <li>
            <div class="log"></div>
            <p>时效规则有</p>
          </li>
          <li>
            <div class="log"></div>
            <p>数据规则有</p>
          </li>
          <li>
            <div class="log"></div>
            <p>显示及编辑权限</p>
          </li>
          <li>
            <div class="log"></div>
            <p>显示权限</p>
          </li>
        </ul>
      </div>
      <!-- <div class="paren_list">
        <ul>
          <li v-for="(item, index) in treeTitles" :key="index">
            <div
              class="up_type"
              :class="active === index ? 'up_types' : 'up_type'"
              @click="upActive(item, index)"
            >
              {{ item.AuthName }}
            </div>
          </li>
        </ul>
      </div> -->
      <div class="paren_cont">
        <el-scrollbar style="height: 100%">
          <!-- <el-tree :data="data" show-checkbox :check-strictly="true" @check-change="currentChange" @node-click="handleNodeClick" :defaultProps="defaultProps" :expand-on-click-node="false" node-key="AuthId" default-expand-all ref="tree" highlight-current> -->
          <el-tree :data="data" show-checkbox @check-change="currentChange" :default-expanded-keys="defaultExpandedKeys" @node-click="handleNodeClick" :defaultProps="defaultProps" node-key="AuthId" ref="tree" highlight-current>
            <span class="custom-tree-node" slot-scope="{ data }">
              {{ data.AuthName }}
              <div class="logup">
                <div class="one" v-if="data.AuthList && data.AuthList.ValidBegin"></div>
                <div class="two" v-if="data.AuthList && data.AuthList.Action == '1'"></div>
                <div class="four" v-if="data.AuthList && data.AuthList.Action == '2'"></div>
                <div class="three" v-if="
                    data.AuthList &&
                    (data.AuthList.EditCol ||
                      data.AuthList.DeleteRow ||
                      data.AuthList.EditRow ||
                      data.AuthList.NewCol ||
                      data.AuthList.QueryCol ||
                      data.AuthList.QueryRow)
                  "></div>
              </div>
            </span>
          </el-tree>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>
<script>
// import treeData from "@/views/authorityManagement/minixs/treeData";
import { translateDataToTreeAll, deteleObject } from "@/utils/validate";
import { GetAuthTree } from "@/api/apiAuthority";
import { GetAuthTreeByGroup } from "@/api/AccountGroup";
import { organizationUptree, postUptree } from "@/api/postInterface";
export default {
  props: {
    title: {
      type: String,
      default: "",
    },
    checkedKeys: {
      //已选中
      type: Array,
      default: () => [],
    },
    //查询类型：queryType： all/获取全部权限树；job/根据岗位获取权限树；origin/根据组织获取权限树;group/根据帐号组获取权限树;
    queryType: {
      type: String,
      default: "all",
    },
    //要查询的查询ID
    queryId: {
      type: String,
      default: "",
    },
    queryIds: {
      type: Array,
      default: () => []
    },
    //要查询的查询ID
    isMainJob: {
      type: Boolean,
      default: true,
    },
  },
  data () {
    return {
      active: 0,
      data: [],
      treeTitles: [],
      defaultProps: {
        children: "children",
        label: "AuthName",
      },
      searchId: "",
      dataObj: {}, //上级权限指定树数据
      AuthArrList: [], //权限列表源数据
      AuthList: [], //权限规则列表
      checkedList: [], //选中的列表
      oldType: "",
      queryIdArr: [], //历史查询ID
      MainJobId: "",//主岗ID
      defaultExpandedKeys: [-1]
    };
  },
  watch: {
    checkedKeys: {
      handler (val) {
        this.checkedList = val;
        this.$refs.tree.setCheckedKeys(val);
      },
      deep: true,
    },
    "$store.state.auth.authList": {
      handler (val) {
        if (val && val.length) {
          this.AuthList = val;
          this.resetData();
        } else {
          this.getAuthList();
        }
      },
      immediate: true,
      deep: true,
    },
    queryId: {
      handler (val) {
        if (this.queryType == "job") {
          this.setDisabledAll();
          let ids = val.split(",");
          this.queryIdArr = [];
          this.$refs.tree.setCheckedKeys([]);
          if (this.isMainJob == true) {
            this.MainJobId = val;
          }
          if (this.MainJobId != "") {
            this.queryIdArr.push(this.MainJobId);
          }
          for (let i = 0; i < ids.length; i++) {
            if (_.indexOf(this.queryIdArr, ids[i]) == -1) {
              this.queryIdArr.push(ids[i]);
            }
          }
          for (let j = 0; j < this.queryIdArr.length; j++) {
            this.searchId = this.queryIdArr[j];
            this.getDefaultDataList();
          }
        } else {
          this.searchId = val;
          this.getDefaultDataList();
        }
      },
      deep: true,
    },
    queryIds: {
      handler () {
        this.getDefaultDataList()
      },
      deep: true
    }
  },
  created () {
    this.getDataList();
    this.searchId = this.queryId;
  },
  methods: {
    getAuthList () {
      let arr = [];
      setTimeout(() => {
        arr = this.$store.getters.authList;
        if (arr && arr.length) {
          this.AuthList = arr;
          this.resetData();
        } else {
          this.getAuthList();
        }
      }, 100);
    },
    //获取权限列表
    getDataList () {
      GetAuthTree({ QueryName: "" }).then((result) => {
        this.getDefaultDataList();
        this.setData(result);
      });
    },
    async getDefaultDataList () {
      if (this.queryType == "all" && this.searchId != "") {
        //获取全部权限树
        GetAuthTree({ QueryName: "" }).then((result) => {
          this.setUnDisabledData(result.returnData);
        });
      } else if (this.queryType == "job") {
        //根据岗位获取权限树
        postUptree({ JobId: this.searchId }).then((result) => {
          this.setUnDisabledData(result.returnData);
        });
      } else if (this.queryType == "origin") {
        //根据组织获取权限树
        this.AuthList = [];
        this.$refs.tree.setCheckedKeys([])
        organizationUptree({ OrganId: this.searchId }).then((result) => {
          this.setUnDisabledData(result.returnData);
        });
      } else if (this.queryType == "group") {
        //根据帐号组获取权限树
        if (this.searchId) {
          GetAuthTreeByGroup({ GroupIds: [this.searchId] }).then((result) => {
            this.setUnDisabledData(result.returnData);
          });
        } else if (this.queryIds.length && this.queryIds[0] !== -1) {
          GetAuthTreeByGroup({ GroupIds: this.queryIds }).then((result) => {
            this.setUnDisabledData(result.returnData)
          })
        }
      }
    },
    setData (result) {
      if (result.code === 0 && result.returnData.length) {
        this.AuthArrList = [];
        result.returnData.forEach((item) => {
          item.flag = item.Status === 1 ? true : false;
          item["AuthList"] = null;
          if (this.queryType != "all") {
            item["disabled"] = true;
          }
        });
        this.AuthArrList = _.cloneDeep(result.returnData);
        this.toTree();
      } else {
        this.$message.error(result.message);
      }
    },
    //数据转树形
    toTree () {
      this.data = [];
      this.dataObj = {};
      this.treeTitles = [];
      let arr = null;
      arr = translateDataToTreeAll(this.AuthArrList, "UpAuthId", "AuthId");
      let items = null;
      items = {
        AuthId: -1,
        AuthName: "所有权限",
        QueryTarget: 0,
        Status: 0,
        UpAuthId: -2,
        Type: 0,
        disabled: true,
        children: arr,
      };
      this.dataObj = _.cloneDeep(items);
      this.data = [items];
      let obj = null;
      obj = _.cloneDeep(items);
      let datas = null;
      datas = obj.children.filter((item) => item.Type === 1);
      datas.forEach((item) => {
        delete item.children;
      });
      delete obj.children;
      datas.unshift(obj);
      this.treeTitles = datas;
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedKeys(this.checkedList);
      }
    },
    //数据切换
    upActive (item, index) {
      this.active = index;
      this.decompose([this.dataObj], item.AuthId);
      this.$refs.tree.setCheckedKeys(this.checkedList);
    },
    // 树节点选中
    currentChange () {
      this.checkedList = [];
      const arr = this.$refs.tree.getCheckedNodes();
      arr.forEach((item) => {
        // if(item.disabled==false){
        this.checkedList.push(item.AuthId);
        // }
      });
      this.setDataObj(arr);
    },
    // 选中后设置初始数据
    setDataObj (arr) {
      arr.forEach((item) => {
        if (!item.AuthList) {
          item.AuthList = {
            AuthId: item.AuthId,
            ValidBegin: "",
            ValidEnd: "",
            Action: "1",
            QueryRow: "",
            QueryCol: "",
            NewCol: "",
            EditRow: "",
            EditCol: "",
            DeleteRow: "",
          };
        }
      });
      this.$emit("getTreeData", arr);
    },
    //获取指定数据
    decompose (data, id) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].AuthId == id) {
          this.data = [data[i]];
        } else if (data[i].children && data[i].children.length > 0) {
          this.decompose(data[i].children, id);
        }
      }
    },
    //获取权限规则 从新组合数据
    resetData () {
      if (this.AuthList) {
        this.AuthArrList.forEach((item1) => {
          item1["AuthList"] = null;
          this.AuthList.forEach((item2) => {
            if (item1.AuthId == item2.AuthId) {
              item1.AuthList = item2;
            }
          });
        });
      }
      this.toTree();
    },
    setUnDisabledData (data) {
      const ArrData = _.cloneDeep(data);
      this.AuthArrList.forEach((item1) => {
        if (this.queryType != "job") {
          item1.disabled = true;
        }
        ArrData.forEach((item2) => {
          if (item1.AuthId == item2.AuthId && item1.Type != 1) {
            item1.disabled = false;
          }
        });
      });
      this.toTree();
    },
    //获取点击目标
    handleNodeClick (data) {
      // this.toTree();
      const arr = this.$store.getters.authArrs;
      arr.push(data);
      const datas = _.unionBy(arr, "AuthId");
      const newDatas = _.cloneDeep(datas);
      this.$store.dispatch("auth/changeAuthMsg", newDatas);
      this.$store.dispatch("auth/changeAuthArrs", datas);
      this.$store.dispatch("auth/changeAuthId", data.AuthId);
    },
    async setDisabledAll () {
      this.AuthArrList.forEach(item => {
        item.disabled = true;
      })
    }
  },
};
</script>
<style lang="scss">
@import "./permissiontree.scss";
</style>
