import request from '@birt/funclib/AxiosUtil'
import {
  getResData,
  getOrgData,
  getRoleData,
  editPermissionByAll,
  getDataAccess
} from "@birt/api/user";
export default {
  data() {
    return {
      resDatas: [],
      orgTreeData: [],
    }
  },
  // mounted() {
  //   this.$nextTick(() => {
  //     console.log('执行混入')
  //     if (this.$route.path == '/platf/permission/func/modify.func')
  //     this.getOrgDataM(-1);
  //   });
  // },
  methods: {
    getOrgDataM(pid) {
      var __body = "";
      if (pid) {
        __body = JSON.stringify({
          queryCdions: {
            join: "and",
            items: [{
              sign: "eq",
              name: "PID",
              desc: "",
              dataType: "string",
              value: pid.toString(),
              enabled: true
            }]
          }
        });
      }
      var data = {
        modelFilePath: "/platf/org/entity/SysOrgListEntity.xml",
        __body: __body
      };
      getOrgData(data)
        .then(res => {
          if (res.status == 200) {
            this.orgData = res.dataPack.rows;
            this.orgData.forEach(val => {
              val.hasChildren = val.childrenCount > 0;
              val.isAssign = false;
            });
          }
          var data1 = {
            modelFilePath: "/platf/role/entity/SysRoleListEntity.xml",
            __body: __body
          };
          this.getRoleDataM(data1);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    getRoleDataM(data) {
      var me = this;
      getRoleData(data)
        .then(res => {
          me.roleData = res.dataPack.rows;
          me.roleData.forEach(val => {
            val.hasChildren = val.childrenCount > 0;
            val.isAssign = false;
          });
          me.allData = me.orgData.concat(me.roleData);
          me.allData.forEach(recd => {
            recd.isAssign = false;
          });
          var copydata = me.deepCopy(me.allData);
          me.orgTreeData = me.arrayToJson(copydata, "id", "pid");
          this.$refs.BirtWorkBook_modify.dataset.dsOrgTree.setData(me.allData);
          this.$refs.BirtWorkBook_modify.dataset.dsOrg.setData(me.allData);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    //匹配带参数的url
    getSchemeDataM(schemeData, fresurl) {
      var scheme = schemeData[fresurl];
      if (!scheme) {
        //   schemeData.forEach((key,value) =>{
        //       if(fresurl.indexOf(key)>=0){
        //           scheme=value;
        //       }
        //   });
        $.each(schemeData, function (key, value) {
          if (fresurl.indexOf(key) >= 0) {
            scheme = value;
          }
        });
      }
      return scheme || "";
    },
    getSchemeM(data, me) {
      // getOrgData(data).then(res => {
      return new Promise(function (resolve, reject) {
        getDataAccess(data).then(res => {
          if (res.status == 200) {
            var list = res.dataPack,
              list1 = [];
            for (var i = 0; i < list.length; i++) {
              if (list[i].dataAccess) {
                var list2 = list[i].dataAccess;
                for (var j = 0; j < list2.length; j++) {
                  list1.push({
                    funcUrl: list[i].funcUrl,
                    name: list2[j].desc,
                    value: list2[j].schemeid,
                    TYPE: list2[j].schemeid,
                    fdaguid: list2[j].schemeid
                  });
                }
              }
            }
            me.schemeData = list1;
            me.schemeData.forEach((v, i) => {
              v.isOther = i;
              var key = v.funcUrl;
              var data1 = me.rData.hasOwnProperty(key) ?
                me.rData[key] :
                new Object();
              if (
                v.TYPE.indexOf("other") !== -1 ||
                (v.TYPE.indexOf("other") == -1 &&
                  me.rData[v.TYPE] != undefined)
              ) {
                var other = data1.other || new Array();
                other.push(v);
                data1.other = other;
              } else {
                data1[v.TYPE] = v;
              }
              me.rData[key] = data1;
            });
            resolve();
          } else {
            reject();
          }
        });
      });
    },
    addDapower(resData,rData, fresurl){
      resData.forEach((w, j) => {
       if (w.frestype !== "dir") {
         w.opPower = {
           add: {
             value: 0
           },
           edit: {
             value: 0
           },
           delete: {
             value: 0
           },
           export: {
             value: 0
           }
         };
       }
       w.daValue = w.fdaschemeid || "";
       if (fresurl) {
         w.daPower = this.getSchemeDataM(rData, fresurl);
       } else {
         w.daPower = "";
       }
       if (w.foperates) {
         w.opAdd = w.foperates.indexOf(1) > -1;
         w.opDelete = w.foperates.indexOf(4) > -1;
         w.opEdit = w.foperates.indexOf(2) > -1;
         w.opExport = w.foperates.indexOf(8) > -1;
       }
     });
    },
    addOpetionDataM(resData, rData) {
      resData.forEach((w, j) => {
        var fresurl = w.fresurl;
        if (w.frestype !== "dir") {
          w.opPower = {
            add: {
              value: 0
            },
            edit: {
              value: 0
            },
            delete: {
              value: 0
            },
            export: {
              value: 0
            }
          };
        }
        w.daValue = w.fdaschemeid || "";
        if (fresurl) {
          w.daPower = this.getSchemeData(rData, fresurl);
        } else {
          w.daPower = "";
        }
        if (w.foperates) {
          w.opAdd = w.foperates.indexOf(1) > -1;
          w.opDelete = w.foperates.indexOf(4) > -1;
          w.opEdit = w.foperates.indexOf(2) > -1;
          w.opExport = w.foperates.indexOf(8) > -1;
        }
        // if (rData[fresurl]) {
        //   var other = rData[fresurl].other;
        //   if (other) {
        //     var defaultSchemeData = "";
        //     $.each(other, function() {
        //       if (this.name == "默认权限") {
        //         defaultSchemeData = this.value;
        //       }
        //     });
        //     if (defaultSchemeData != "") {
        //       w.daValue = defaultSchemeData;
        //     } else {
        //       w.daValue = "";
        //     }
        //   }
        // }
        if (w.children && w.children.length > 0) {
          this.addOpetionData(w.children, rData);
        }
      });
      },
      //  删除所有权限
      delAllPermisson(node, done, instance) {
        let url = node.nodeType == "role" ?
          "/sys/auth/update-batch-role" :
          "/sys/auth/update-batch-org";
        let guidName = node.nodeType == "role" ? "froleguid" : "forgguid";
        var data = {}
        data[guidName] = node.id
        data.list = [];
        editPermissionByAll(data, url)
          .then(res => {
            if (res.status == 200) {
              this.$message.success("修改权限成功");
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "保存";
              done();
            } else {
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "保存";
            }
          })
          .catch(e => {
            instance.confirmButtonLoading = false;
            instance.confirmButtonText = "保存";
          });
      },
      saveResourceM(saveData, done, instance, clearAuth, saveDirtyData) {
        let list = new Array();
        var list1 = new Array();
        var datas = new Array();
        if (saveData.length) {
          list1 = saveData;
        } else {
          list1 = saveDirtyData;
        }
        this.getResList(list1, datas);
        let guidName = datas[0].assignType == "role" ? "froleguid" : "forgguid";
        let url =
          datas[0].assignType == "role"
            ? "/sys/auth/update-batch-role"
            : "/sys/auth/update-batch-org";
        for (let resData of datas) {
          var obj = new Object();
          if (resData.frestype == "dir") {
            obj.fresguid = resData.fresguid;
            obj.forgguid = resData.forgguid;
            obj.fresname = resData.fresname;
            if (resData.daPower && resData.daPower !== "") {
              for(var key in resData.daPower){
                    if(resData.daValue.indexOf(key) != -1){
                      if(Array.isArray(resData.daPower[key])){
                        for(let item of resData.daPower[key]){
                          if(item.value == resData.daValue){
                            obj.fdaschemename = item.name;
                            obj.fdaguid = item.fdaguid;
                            obj.fdaschemeid = item.value;
                          }
                        }
                      }else{
                        obj.fdaschemename = resData.daPower[key].name;
                        obj.fdaguid = resData.daPower[key].fdaguid;
                        obj.fdaschemeid = resData.daPower[key].value;
                      }
                    }
                  }
            } else {
              obj.fdaguid = "";
              obj.fdaschemeid = "";
              obj.fdaschemename = "";
            }
            obj.guidName = guidName;
            var foperates = new Array();
            var dataOperateName = new Array();
            if (resData.opAdd) {
              foperates.push(1);
              dataOperateName.push("添加");
            }
            if (resData.opEdit) {
              foperates.push(2);
              dataOperateName.push("修改");
            }
            if (resData.opDelete) {
              foperates.push(4);
              dataOperateName.push("删除");
            }
            if (resData.opExport) {
              foperates.push(8);
              dataOperateName.push("导出");
            }
            obj.foperates = foperates;
            obj.fresguid = resData.fresguid;
            list.push(obj);
            continue;
          } else if (
            resData.frestype == "func" &&
            (resData.daValue == undefined || resData.daValue == "")
          ) {
            //弹出独立型功能必须选择权限,然后直接return
            // this.$message({
            //   type: "error",
            //   message: "功能 " + resData.fresname + " 为独立型功能，必须选择权限"
            // });
            // instance.confirmButtonLoading = false;
            // done();
            // return;
          }
          obj.fresguid = resData.fresguid;
          obj.forgguid = resData.forgguid;
          obj.fresname = resData.fresname;
          if (resData.daPower && resData.daPower !== "") {
          for(var key in resData.daPower){
                    if(resData.daValue.indexOf(key) != -1){
                      if(Array.isArray(resData.daPower[key])){
                        for(let item of resData.daPower[key]){
                          if(item.value == resData.daValue){
                            obj.fdaschemename = item.name;
                            obj.fdaguid = item.fdaguid;
                            obj.fdaschemeid = item.value;
                          }
                        }
                      }else{
                        obj.fdaschemename = resData.daPower[key].name;
                        obj.fdaguid = resData.daPower[key].fdaguid;
                        obj.fdaschemeid = resData.daPower[key].value;
                      }
                    }
                  }
          } else {
            obj.fdaguid = "";
            obj.fdaschemeid = "";
            obj.fdaschemename = "";
          }
          var foperates = new Array();
          var dataOperateName = new Array();
          if (resData.opAdd) {
            foperates.push(1);
            dataOperateName.push("添加");
          }
          if (resData.opEdit) {
            foperates.push(2);
            dataOperateName.push("修改");
          }
          if (resData.opDelete) {
            foperates.push(4);
            dataOperateName.push("删除");
          }
          if (resData.opExport) {
            foperates.push(8);
            dataOperateName.push("导出");
          }
          obj.foperates = foperates;
          obj.fresguid = resData.fresguid;
          list.push(obj);
        }
        var data = new Object();
        data[guidName] = datas[0].assignId || datas[0].assignGuid;
        data.list = list;
        editPermissionByAll(data, url)
          .then(res => {
            if (res.status == 200) {
              this.$message.success("修改权限成功");
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "保存";
              done();
            } else {
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "保存";
            }
          })
          .catch(e => {
            instance.confirmButtonLoading = false;
            instance.confirmButtonText = "保存";
          });
      },
      delAllPermissonByFun(node, done, instance) {
        let url = "/sys/auth/update-batch-res";
        var data = {}
        data.fresguid = node.fresguid
        data.list = [];
        editPermissionByAll(data, url)
          .then(res => {
            if (res.status == 200) {
              this.$message.success("修改权限成功");
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "保存";
              done();
            } else {
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "保存";
            }
          })
          .catch(e => {
            instance.confirmButtonLoading = false;
            instance.confirmButtonText = "保存";
          });
      },
      saveResourceByFun(saveData, done, instance, clearAuth, saveDirtyData) {
        let list = new Array();
        var list1 = new Array();
        var datas = new Array();
        if (saveData.length) {
          list1 = saveData;
        } else {
          list1 = saveDirtyData;
        }
        this.getResList(list1, datas);
        let url = "/sys/auth/update-batch-res";
        for (let resData of datas) {
          var obj = new Object();
          if (resData.frestype == "dir") {
            obj.fresguid = resData.fresguid;
            obj.forgguid = resData.forgguid;
            obj.fresname = resData.fresname;
            obj.daValue = resData.daValue;
            if (resData.daPower && resData.daPower !== "") {
              for (var key in resData.daPower) {
                if (resData.daValue.indexOf(key) != -1) {
                  if (Array.isArray(resData.daPower[key])) {
                    for (let item of resData.daPower[key]) {
                      if (item.value == resData.daValue) {
                        obj.fdaschemename = item.name;
                        obj.fdaguid = item.fdaguid;
                        obj.fdaschemeid = item.value;
                      }
                    }
                  } else {
                    obj.fdaschemename = resData.daPower[key].name;
                    obj.fdaguid = resData.daPower[key].fdaguid;
                    obj.fdaschemeid = resData.daPower[key].value;
                  }
                }
              }
            } else {
              obj.fdaguid = "";
              obj.fdaschemeid = "";
              obj.fdaschemename = "";
            }
            var foperates = new Array();
            var dataOperateName = new Array();
            if (resData.opAdd) {
              foperates.push(1);
              dataOperateName.push("添加");
            }
            if (resData.opEdit) {
              foperates.push(2);
              dataOperateName.push("修改");
            }
            if (resData.opDelete) {
              foperates.push(4);
              dataOperateName.push("删除");
            }
            if (resData.opExport) {
              foperates.push(8);
              dataOperateName.push("导出");
            }
            obj.foperates = foperates;
            obj.fresguid = resData.fresguid;
            list.push(obj);
            continue;
          } else if (
            resData.frestype == "func" &&
            (resData.daValue == undefined || resData.daValue == "")
          ) {
            // //弹出独立型功能必须选择权限,然后直接return
            // this.$message({
            //   type: "error",
            //   message: "功能 " + resData.fresname + " 为独立型功能，必须选择权限"
            // });
            // instance.confirmButtonLoading = false;
            // done();
            // return;
          }
          obj.fresguid = resData.fresguid;
          obj.forgguid = resData.forgguid;
          obj.fresname = resData.fresname;
          obj.daValue = resData.daValue;
          if (resData.daPower && resData.daPower !== "") {
            for (var key in resData.daPower) {
              if (resData.daValue.indexOf(key) != -1) {
                if (Array.isArray(resData.daPower[key])) {
                  for (let item of resData.daPower[key]) {
                    if (item.value == resData.daValue) {
                      obj.fdaschemename = item.name;
                      obj.fdaguid = item.fdaguid;
                      obj.fdaschemeid = item.value;
                    }
                  }
                } else {
                  obj.fdaschemename = resData.daPower[key].name;
                  obj.fdaguid = resData.daPower[key].fdaguid;
                  obj.fdaschemeid = resData.daPower[key].value;
                }
              }
            }
          } else {
            obj.fdaguid = "";
            obj.fdaschemeid = "";
            obj.fdaschemename = "";
          }
          var foperates = new Array();
          var dataOperateName = new Array();
          if (resData.opAdd) {
            foperates.push(1);
            dataOperateName.push("添加");
          }
          if (resData.opEdit) {
            foperates.push(2);
            dataOperateName.push("修改");
          }
          if (resData.opDelete) {
            foperates.push(4);
            dataOperateName.push("删除");
          }
          if (resData.opExport) {
            foperates.push(8);
            dataOperateName.push("导出");
          }
          obj.foperates = foperates;
          obj.fresguid = resData.fresguid;
          list.push(obj);
        }
        var data = new Object();
        data.fresguid = datas[0].fresguid
        data.list = list;
        editPermissionByAll(data, url)
          .then(res => {
            if (res.status == 200) {
              this.$message.success("修改权限成功");
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "保存";
              done();
            } else {
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "保存";
            }
          })
          .catch(e => {
            instance.confirmButtonLoading = false;
            instance.confirmButtonText = "保存";
          });
      },
      getResList(resList, resDatas) {
        for (var resData of resList) {
          if (resData.children && resData.children.length > 0) {
            resDatas.push(resData);
            this.getResList(resData.children, resDatas); //如果还是数组继续递归调用
          } else {
            resDatas.push(resData);
          }
        }
      },
      loadMethodM(store, loadCdion, option, resolve) {
        let me = this;
        var data = {
          modelFilePath: "/platf/dataaccess/entity/SysDataaccessEntity.xml"
        };
        me.getSchemeM(data, me).then(function (value) {
          getResData().then(res => {
            if (res.status == 200) {
              me.resData = res.dataPack;
              me.addOpetionDataM(me.resData, me.rData);
              me.resources = me.resData;
              option = option || {};
              // me.$refs.BirtWorkBook_power.dataset.dsRes2.setData(resources);
              resolve.call(store, me.resources, option);
              // this.$refs.BirtWorkBook_modify.dataset.dsRes.setData(resources);
            }
          });
        })
      },
      //  树形表格过滤
      handleTreeData(treeData, searchValue) {
        if (!treeData || treeData.length === 0) {
          return [];
        }
        const array = [];
        for (let i = 0; i < treeData.length; i += 1) {
          let match = false;
          // if(typeof(treeData[i].fresname)=='string'){
          //     match |= treeData[i].fresname.includes(searchValue);
          //     if(match) break;
          //   }
          for (let pro in treeData[i]) {
            if (typeof treeData[i][pro] == "string") {
              match |= treeData[i][pro].includes(searchValue);
              if (match) break;
            }
          }
          if (
            this.handleTreeData(treeData[i].children, searchValue).length > 0 ||
            match
          ) {
            array.push({
              ...treeData[i],
              children: this.handleTreeData(treeData[i].children, searchValue)
            });
          }
        }
        return array;
      },
      // 将过滤好的树形数据展开
      setExpandRow(handleTreeData) {
        if (handleTreeData.length) {
          for (let i of handleTreeData) {
            this.expandRow.push(i.id);
            if (i.children.length) {
              this.setExpandRow(i.children);
            }
          }
        }
      },
      arrayToJson1(treeArray, id, pid) {
        var r = [];
        var tmpMap = {};
        for (var i = 0, l = treeArray.length; i < l; i++) {
          // 以每条数据的id作为obj的key值，数据作为value值存入到一个临时对象里面
          tmpMap[treeArray[i][id]] = treeArray[i];
        }
        for (i = 0, l = treeArray.length; i < l; i++) {
          var key = tmpMap[treeArray[i][pid]];
          //循环每一条数据的pid，假如这个临时对象有这个key值，就代表这个key对应的数据有children，需要Push进去
          //如果这一项数据属于哪个数据的子级
          if (key) {
            // 如果这个数据没有children
            if (!key["children"]) {
              key["children"] = [];
              key["children"].push(treeArray[i]);
              // 如果这个数据有children
            } else {
              key["children"].push(treeArray[i]);
            }
          } else {
            //如果没有这个Key值，就代表找不到属于哪个数据，那就代表没有父级,直接放在最外层
            r.push(treeArray[i]);
          }
        }
        return r;
      },
      arrayToJson(data, id, pid) {
        let result = [];
        if (!Array.isArray(data)) {
          return result;
        }
        let map = {};
        data.forEach(item => {
          map[item[id]] = item;
        });
        data.forEach(item => {
          let parent = map[item[pid]];
          if (parent) {
            (parent.children || (parent.children = [])).push(item);
          } else {
            result.push(item);
          }
        });
        return result;
      },
      //  tree转数组
      jsonToArray(nodes) {
        var r = [];
        if (Array.isArray(nodes)) {
          for (var i = 0, l = nodes.length; i < l; i++) {
            r.push(nodes[i]); // 取每项数据放入一个新数组
            if (
              Array.isArray(nodes[i]["children"]) &&
              nodes[i]["children"].length > 0
            )
              // 若存在children则递归调用，把数据拼接到新数组中，并且删除该children
              r = r.concat(this.jsonToArray(nodes[i]["children"]));
            delete nodes[i]["children"];
          }
        }
        return r;
      },
      deepCopy(obj) {
        var object;
        // 深度复制数组
        if (Object.prototype.toString.call(obj) == "[object Array]") {
          object = [];
          // for (var i = 0; i < obj.length; i++) {
          //   object.push(deepCopy(obj[i]));
          // }
          for (var o of obj) {
            object.push(this.deepCopy(o));
          }
          return object;
        }
        // 深度复制对象
        if (Object.prototype.toString.call(obj) == "[object Object]") {
          object = {};
          for (var p in obj) {
            object[p] = obj[p];
          }
          return object;
        }
      },
      getPermissionByRes(params) {
        return request({
          url: '/sys/auth/query-by-res?pn=birt',
          method: 'post',
          data: params
        })
      },
      //  根据用户查询反查
      getPermissionByUer(params) {
        return request({
          url: '/sys/auth/query-all-user?pn=birt',
          method: 'post',
          data: params
        })
      },
      //  根据功能查询反查
      getPermissionByResAll(params) {
        return request({
          url: '/sys/auth/query-all-res?pn=birt',
          method: 'post',
          data: params
        })
      },
      // 根据机构和岗位查询权限
      getPermissionByAll(params, url) {
        return request({
          url: url,
          method: 'post',
          data: params
        })
      },
      getOrgDataByUrl(data){
        return request({
          url:  this.$HI.queryUrl,
          method: 'post',
          data
        })
      }
    }
}