<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 class="icon-gz">
            <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="currentChange" :default-expanded-keys="defaultExpandedKeys" @node-click="handleNodeClick" :defaultProps="defaultProps" node-key="auth_id" 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.EditCol ||
                      data.AuthList.DeleteRow || data.DeleteRow ||
                      data.AuthList.EditRow || data.EditRow ||
                      data.AuthList.NewCol || data.NewCol ||
                      data.AuthList.QueryCol || data.QueryCol ||
                      data.AuthList.QueryRow || data.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";
import { GeneralDataReception, Query } from '@/api/dataIntegration';
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 | Number,
      default: "",
    },
    queryIds: {
      type: Array,
      default: () => []
    },
    //要查询的查询ID
    isMainJob: {
      type: Boolean,
      default: true,
    },
  },
  data () {
    return {
      active: 0,
      data: [],
      treeTitles: [],
      defaultProps: {
        children: "children",
        label: "auth_name",
      },
      searchId: "",
      dataObj: {}, //上级权限指定树数据
      AuthArrList: [], //权限列表源数据
      AuthList: [], //权限规则列表
      checkedList: [], //选中的列表
      oldType: "",
      queryIdArr: [], //历史查询ID
      MainJobId: "",//主岗ID
      defaultExpandedKeys: [-1],
      treeChecks: [],
    };
  },
  watch: {
    checkedKeys: {
      handler (val) {
        this.checkedList = val;
        this.treeChecks = 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
    },
    treeChecks: {
      handler (val) {
        if (val && val.length) {
          this.$refs.tree.setCheckedKeys(val);
        }
      },
      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 () {
      Query({
        id: DATACONTENT_ID.authTreeId,
        dataContent: ['']
      }).then((result) => {
        // this.getDefaultDataList();
        this.setUnDisabledData(result.returnData.listValues);
        this.setData(result);
      });
    },
    async getDefaultDataList () {
      if (this.queryType == "all" && this.searchId != "") {
        //获取全部权限树
        Query({
          id: DATACONTENT_ID.authTreeId,
          dataContent: ['']
        }).then((result) => {
          this.setUnDisabledData(result.returnData.listValues);
        });
      } else if (this.queryType == "job") {
        //根据岗位获取权限树
        postUptree({ JobId: this.searchId }).then((result) => {
          this.setUnDisabledData(result.returnData.listValues);
        });
      } else if (this.queryType == "origin") {
        //根据组织获取权限树
        this.AuthList = [];
        this.$refs.tree.setCheckedKeys([])
        organizationUptree({ OrganId: this.searchId }).then((result) => {
          this.setUnDisabledData(result.returnData.listValues);
        });
      } else if (this.queryType == "group") {
        //根据帐号组获取权限树
        if (this.searchId) {
          GetAuthTreeByGroup({ GroupIds: [this.searchId] }).then((result) => {
            this.setUnDisabledData(result.returnData.listValues);
          });
        } else if (this.queryIds.length && this.queryIds[0] !== -1) {
          GetAuthTreeByGroup({ GroupIds: this.queryIds }).then((result) => {
            this.setUnDisabledData(result.returnData.listValues)
          })
        }
      }
    },
    setData (result) {
      if (result.code == 0 && result.returnData.listValues.length) {
        this.AuthArrList = [];
        result.returnData.listValues.forEach((item) => {
          item.flag = item.auth_status;
          item["AuthList"] = null;
          if (this.queryType != "all") {
            item["disabled"] = true;
          }
        });
        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: -1,
        auth_name: "所有权限",
        QueryTarget: 0,
        auth_status: 0,
        up_auth_id: -2,
        auth_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.auth_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.auth_id);
      this.$refs.tree.setCheckedKeys(this.checkedList);
    },
    // 树节点选中
    currentChange () {
      this.checkedList = [];
      const datas = this.$refs.tree.getCheckedNodes();
      // const arr = this.$refs.tree.getCheckedNodes();
      // const half = this.$refs.tree.getHalfCheckedNodes();
      // const halfAll = half.filter(item => item.auth_id != -1 && item.auth_name != '所有权限');
      // const datas = halfAll.concat(arr);
      // if (this.treeChecks && this.treeChecks.length) {
      //   const checks = [];
      //   datas.forEach(item => {
      //     checks.push(item.auth_id);
      //   })
      //   const handAll = [...checks, ...this.treeChecks].filter(t => {
      //     return !(checks.includes(t) && this.treeChecks.includes(t));
      //   })
      //   setTimeout(() => {
      //     handAll.map(item => {
      //       this.$refs.tree.setChecked(item, false);
      //       this.treeChecks = [];
      //     })
      //   }, 100);

      // }
      datas.forEach((item) => {
        // if(item.disabled==false){
        this.checkedList.push(item.auth_id);
        // }
      });
      this.setDataObj(datas);
    },
    // 选中后设置初始数据
    setDataObj (arr) {
      arr.forEach((item) => {
        if (!item.AuthList) {
          item.AuthList = {
            AuthId: item.auth_id,
            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.auth_id == item2.auth_id && item1.auth_type != 1) {
            item1.disabled = false;
          }
        });
      });
      this.toTree();
    },
    //获取点击目标
    handleNodeClick (data) {
      // this.toTree();
      const arr = this.$store.getters.authArrs;
      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>
