<template>
  <div class="bf-permissiontree">
    <!-- 权限树 -->
    <div class="cont">
      <div class="paren_header">
        <p class="manageTitle">{{ 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-change="currentChange" @node-click="handleNodeClick" :defaultProps="defaultProps" node-key="auth_id" default-expand-all ref="tree" highlight-current>
            <span class="custom-tree-node" slot-scope="{ data }">
              {{ data.auth_name }}
              <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 { Query, GeneralDataReception } from "@/api/dataIntegration";
import { organizationUptree, postUptree } from "@/api/postInterface";
export default {
  props: {
    title: {
      type: String,
      default: "",
    },
    //查询类型：queryType： all/获取全部权限树；job/根据岗位获取权限树；origin/根据组织获取权限树;group/根据帐号组获取权限树;
    queryType: {
      type: String,
      default: "all",
    },
    //要查询的查询ID
    queryId: {
      type: String | Number,
      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
      checkedKeys: []
    };
  },
  watch: {
    checkedKeys: {
      handler (val) {
        this.checkedList = val;
        this.$refs.tree.setCheckedKeys(this.checkedList);
      },
      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) {
        this.searchId = val;
        this.getDefaultDataList();
      },
      immediate: true,
      deep: true,
    },
    queryIds: {
      handler () {
        this.getDefaultDataList();
      },
      deep: true,
    },
  },
  created: function () {
    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);
    },
    //获取权限列表
    async getDataList () {
      const res = await Query({
        id: 40,
        dataContent: [""]
      });
      if (res.code === "0") {
        this.setData(res.returnData.listValues);
      } else {
        this.$message.error(res.message);
        this.loading = false;
      }
      this.setData(res);
    },
    async getDefaultDataList () {
      try {
        const res = await Query({
          id: DATACONTENT_ID.roleAuthId,
          dataContent: [this.searchId]
        });
        if (res.code == 0) {
          this.checkedKeys = [];
          res.returnData.listValues.forEach(item => {
            this.checkedKeys.push(item.AuthId)
            this.AuthArrList.forEach(item2 => {
              if (item.AuthId == item2.auth_id) {
                item2.AuthList = item
              }
            })
          })
          this.toTree()
        } else {
          this.$message.error(res.message);
          this.loading = false;
        }
      } catch (error) {
        console.log("出错了", error);
      }
    },
    setData (result) {
      if (result.code === "0" && result.returnData.listValues.length) {
        this.AuthArrList = [];
        result.returnData.listValues.forEach((item) => {
          item.flag = item.auth_status === true ? true : false;
          item["AuthList"] = null;
        });
        this.AuthArrList = _.cloneDeep(result.returnData.listValues);
        this.toTree();
      } else {
        this.$message.error(result.message);
      }
    },
    //数据转树形
    toTree () {
      this.data = [];
      this.dataObj = {};
      this.treeTitles = [];
      let arr = null;
      arr = translateDataToTreeAll(this.AuthArrList, "up_auth_id", "auth_id");
      let items = null;
      items = {
        auth_id: 0,
        auth_name: "所有权限",
        auth_status: 0,
        up_auth_id: 0,
        auth_type: 0,
        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;
      console.log(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].auth_id == 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.auth_id == item2.auth_id) {
              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;
      console.log(arr)
      arr.push(data);
      const datas = _.unionBy(arr, "auth_id");
      const newDatas = _.cloneDeep(datas);
      this.$store.dispatch("auth/changeAuthMsg", newDatas);
      this.$store.dispatch("auth/changeAuthArrs", datas);
      this.$store.dispatch("auth/changeAuthId", data.auth_id);
    },
    async setDisabledAll () {
      this.AuthArrList.forEach((item) => {
        item.disabled = true;
      });
    },
  },
};
</script>
<style lang="scss">
@import "./permissiontree.scss";
</style>
