import request from '@birt/funclib/AxiosUtil'
import {
  addPermission,
  getResData,
  getOrgData,
  getRoleData,
  getDataAccess
} from "@birt/api/user";
import t from 'deep-lu-trans';
export default {
  data() {
    return {
      resData: [],
      rData: [],
      schemeData: [],
      regs: [],
      allDataTree: [],
      resources: [],
      allData: [],
      roleData: [],
      orgData: [],
      orgfilter: []
    }
  },
  // mounted() {
  //   debugger
  //   this.$nextTick(() => {
  //     console.log('path', this.$route.path)
  //     if(this.$route.path == '/platf/permission/func/assign.func')
  //     this.getOrgData(-1);
  //   });
  // },
  methods: {
    getOrgData(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.getRoleData(data1);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    getRoleData(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.allDataTree = me.arrayToJson(copydata, "ID", "PID");
          me.$refs.BirtWorkBook_power.dataset.dsOrg.setData(me.allData);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    getResource() {
      getResData().then(res => {
        if (res.status == 200) {
          let list = res.dataPack;
          console.log('list', list)
          if(list && list.length > 0){
            t.arrKeysToUpper(list).then((_s) => {
                this.resData = _s;
                console.log('this.resData,',this.resData)
            });
          }
        }

        var data1 = {
          modelFilePath: "/platf/dataaccess/entity/SysDataaccessEntity.xml"
        };
        this.getScheme(data1);
      });
    },
    //匹配带参数的url
    getSchemeData(schemeData, fresurl) {
      debugger
      console.log('schemeData', schemeData)
      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 || "";
    },
    getScheme(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();
          }
        });
      });
    },
    addOpetionData(resData, rData) {
      debugger
      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 (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);
        }
        // newResData.push(w);
      });
    },
    saveResource(orgDatas, resList, chkClearorg, chkClearres, done, instance) {
      debugger;
      var sysResourceOrg = new Array();
      var sysResourceRole = new Array();
      var resDatas = new Array();
      this.getResList(resList, resDatas);
      for (var orgList of orgDatas) {
        if (orgList.NODETYPE !== "dir") {
          var guidName = orgList.NODETYPE == "role" ? "froleguid" : "forgguid";
          for (var resData of resDatas) {
            var obj = new Object();
            if (resData.FRESTYPE == "dir") {
              obj.FRESGUID = resData.FRESGUID;
              obj.FORGGUID = orgList.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;
              obj[guidName] = orgList.ID;
              if (guidName == "froleguid") {
                sysResourceRole.push(obj);
              } else {
                sysResourceOrg.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 = orgList.FORGGUID;
            obj.FRESNAME = resData.FRESNAME;
            if (resData.daPower && resData.daPower !== "") {
              for (var key in resData.daPower) {
                if (resData.daValue && 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;
            obj[guidName] = orgList.ID;
            if (guidName == "froleguid") {
              sysResourceRole.push(obj);
            } else {
              sysResourceOrg.push(obj);
            }
          }
        }
      }
      var saveData = {
        orgs: sysResourceOrg,
        roles: sysResourceRole,
        clean: chkClearorg,
        cleanRes: chkClearres,
      };
      addPermission(saveData)
        .then(res => {
          if (res.status == 200) {
            this.$message.success("添加权限成功");
            instance.confirmButtonLoading = false;
            instance.confirmButtonText = "保存";
            done();
          }
        })
        .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);
        }
      }
    },
    loadMethod(store, loadCdion, option, resolve) {
      let me = this;
      var data = {
        modelFilePath: "/birt/entity/platf/SysDataaccessEntity.xml"
      };
      me.getScheme(data, me).then(function (value) {
        getResData().then(res => {
          if (res.status == 200) {
            let list = res.dataPack;
            console.log('list', list)
            if(list && list.length > 0){
              t.arrKeysToUpper(list).then((_s) => {
                  me.resData = _s;
                  console.log('this.resData,',me.resData)
                  me.addOpetionData(me.resData, me.rData);
                  me.resources = me.resData;
                  option = option || {};
                  resolve.call(store, me.resources, option);
              });
            }
          }
        });
      })
    },
    //  树形表格过滤
    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;
    },
    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;
      }
    },
    getOrgDataOnAssign(data){
      return request({
        url:  this.$HI.queryUrl,
        method: 'post',
        data
      })
    }
  }
}
