import Vue from "vue";
import {request} from "@/api/base";
import parentView from "_c/base/parent-view";
import Main from "_c/main";

/**
 * @desc   : 执行数据
 * @author : 周兴
 * @date   : 2022/12/14 11:14
 */
Vue.prototype.excute = function (service, method, params) {
  if (service && method) {
    let res = request(service.prefix + method, params)
    if (res) {
      return res;
    }
  }
}

/**
 * @desc   : 格式化
 * @author : 周兴
 * @date   : 2023/5/16 10:31
 */
Vue.prototype.format = function (value, digits = 3) {
  if (!value) return value;
  let returnValue = ''
  for (let i = 0; i < digits; i++) {
    returnValue += '0'
  }
  returnValue = returnValue + value;
  return returnValue.substring(returnValue.length - digits)
}

/**
 * @desc   : 执行数据(不带参数）
 * @author : 周兴
 * @date   : 2022/12/14 11:14
 */
Vue.prototype.excuteNoParams = function (service, method, params) {
  if (service && method) {
    let url = service.prefix + method;
    let par = ''
    params.forEach(it => {
      par += '/' + it
    })
    let res = request(url + par, params)
    if (res) {
      return res;
    }
  }
}

/**
 * @desc   : 清空校验信息
 * @author : 周兴
 * @date   : 2022/11/22 15:52
 */
Vue.prototype.clearErrMessage = function () {
  if (this && this.$parent && this.$parent.errorMessage) {
    if (this.$parent.$parent && this.$parent.$parent.FormInstance) {
      this.$parent.$parent.FormInstance.validate();
    }
  }
}

/**
 * @desc   : 引入文件夹中的文件
 * @author : 周兴
 * @date   : 2022/12/13 15:09
 */
Vue.prototype.importAll = function (r) {
  let cache = {}
  r.keys().forEach(key => cache[key] = r(key))
  return cache;
}

/**
 * @desc   : 行定位
 * @author : 周兴
 * @params  : VueComponent:列表对象；table:数据；searchText:查询的信息；fields需要定位的列
 * @date   : 2022/11/30 9:04
 */
Vue.prototype.rowPositioning = function (vueComponent, table, searchText, fields) {
  if (!vueComponent || !table || table.length == 0 || !searchText) {
    return;
  }
  // 获取当前行
  let currentRow = vueComponent.getCurrentRecord();
  let index = -1;
  if (currentRow) {
    index = vueComponent.getRowIndex(currentRow);
  }
  index = index + 1;
  if (!fields) {
    fields = []
    // 获取显示的列
    let tableColumns = vueComponent.getTableColumn()
    if (tableColumns && tableColumns.visibleColumn && tableColumns.visibleColumn.length > 0) {
      tableColumns.visibleColumn.forEach(it => {
        fields.pushNoRepeat(it.field);
      })
    }
  }
  let searchFlag = false;
  let currentIndex = index;
  for (let i = index; i < table.length; i++) {
    // 模糊查询
    if (this.hasValue(table[i], searchText, fields, false)) {
      currentIndex = i;
      searchFlag = true;
      break;
    }
  }
  if (searchFlag && table[currentIndex]) {
    vueComponent.setCurrentRow(table[currentIndex]);
    this.$nextTick(() => {
      vueComponent.scrollToRow(table[currentIndex]);
    });
  }
}

/**
 * 遍历列的所有内容，获取最宽一列的宽度
 * @param arr
 */
Vue.prototype.getMaxLength = function (arr) {
  return arr.reduce((acc, item) => {
    if (item) {
      let calcLen = this.getTextWidth(item)
      if (acc < calcLen) {
        acc = calcLen
      }
    }
    return acc
  }, 0)
}

/**
 * 使用span标签包裹内容，然后计算span的宽度 width： px
 * @param valArr
 */
Vue.prototype.getTextWidth = function (str) {
  let width = 0;
  let html = document.createElement('span');
  html.innerText = str;
  html.className = 'getTextWidth';
  document.querySelector('body').appendChild(html);
  width = document.querySelector('.getTextWidth').offsetWidth;
  document.querySelector('.getTextWidth').remove();
  return width;
}

/**
 * @desc   : 执行列定位
 * @author : 周兴
 * @date   : 2022/12/15 14:50
 */
Vue.prototype.handleColPosition = function (searchText) {
  let columns = this.$refs[this.name].getColumns();
  let width = 0;
  for (let i = 0; i < columns.length; i++) {
    width += columns[i].width.toString().replace('px', '').toNum(0);
    if (columns[i].title && columns[i].title.includes(searchText)) {
      this.$refs[this.name].setCurrentColumn(columns[i]);
      this.$nextTick(() => {
        this.$refs[this.name].scrollToColumn(columns[i])
      });
      break;
    }
  }
}

/**
 * @desc   : id parentId扁平结构转变为children层级结构
 * @author : 周兴
 * @date   : 2022/12/30 15:55
 */
Vue.prototype.convertToChildren = function (arr, pId = 'parentId', id = 'id', path = null) {
  if (!arr || arr.length === 0) return arr;
  let data = arr.filter(it => !it[pId]) // 获取最顶级
  if (data && data.length > 0) {
    data.forEach(it => {
      _convertToChildren(it, arr, it[id], pId, id, path);
    })
  }
  return data;
}

export function convertToChildrenMain(arr, pId = 'parentId', id = 'id', path = null) {
  if (!arr || arr.length === 0) return arr;
  let data = arr.filter(it => !it[pId]) // 获取最顶级
  if (data && data.length > 0) {
    data.forEach(it => {
      _convertToChildren(it, arr, it[id], pId, id, path);
    })
  }
  return data;
}

/**
 * @desc   : 转成children格式数据（私有方法）
 * @author : 周兴
 * @date   : 2022/12/30 17:06
 */
function _convertToChildren(item, arr, idValue, pId, id, path = null) {
  // console.log('t1',item,idValue,)
  let filters = [];
  if (path) {
    filters = arr.filter(it => it[pId] === idValue && (it.menuType != 2 || !it[path]));
  } else {
    filters = arr.filter(it => it[pId] === idValue);
  }
  // console.log('path',item, item.name, idValue, filters)
  if (!filters || filters.length === 0) {
    if (path) {
      filters =  arr.filter(it => it[pId] === idValue);
      let pFiter = arr.filter(it => it[id] === item[pId]);
      // console.log('item.children',item,item.children,pFiter)
      if(pFiter && pFiter.length > 0 && filters && filters.length > 0){
        if(!pFiter[0].children){
          pFiter[0].children = []
        }
        // 加入到父级的同级
        filters.forEach(cIt =>{
          pFiter[0].children.push(cIt);
        })
      }
    } else {
      return [];
    }
  } else {
    item.children = filters;
    item.children.forEach(it => {
      _convertToChildren(it, arr, it[id], pId, id, path);
    })
    return item;
  }
}

/**
 * @desc   : 处理菜单数据
 * @author : 周兴
 * @date   : 2023/1/9 16:18
 */
export function handleMenu(menu) {
  let list = []
  // 获取重复项的路由
  // let checkList = menu.map(item=>item.objectPaths).getRepeatItem('objectPaths')
  // let checkFlag = false;
  menu.forEach(item => {
    // checkFlag = false;
    // 路径没有或者只有一个
    let obj = {...item}
    obj.path = null;
    if (item.objectPath) {
      // if(checkList && checkList.includes(item.objectPaths)){
      // 多页页面对应同一个路由
      if (item.flgSameRoute) {
        obj.path = item.objectPath + '/' + item.objectCode
      } else {
        obj.path = item.objectPath
      }
    }
    obj = _setMenuItem(obj);
    // 如果有，那么需要在meta中增加formCode
    if (item.flgSameRoute) {
      obj.meta.formCode = obj.name
    }

    if ((obj.menuType == 1 || obj.menuType == 2) && !obj.path) {
      //是页面类型，但是未设置path的情况
      console.log('object path is null', obj)
    } else {
      list.push(obj);
    }
  })
  return list;
}

/**
 * @desc   : 设置菜单明细
 * @author : 周兴
 * @date   : 2023/1/10 16:00
 */
function _setMenuItem(item) {
  item.parentUuid = item.parentUuid ? item.parentUuid : null
  if (item.menuType === 0) {
    if (!item.path) {
      item.path = item.objectCode
    }
    item.component = item.parentUuid ? 'parentView' : 'Main'
  } else {
    item.component = item.path;
  }
  item.name = item.objectCode;
  item.title = item.menuName
  item.icon = item.icon ? item.icon : ''
  item.meta = {
    icon: item.icon,
    title: item.title,
    path: item.path,
    flgMenu: item.flgMenu,
    menuType:item.menuType,
    flgSameRoute: item.flgSameRoute,
    flgChooseId: item.flgChooseId,
    levelCode: item.levelCode,
    flgAutoQuery: item.flgAutoQuery,
    pageGridInfo:item.pageGridInfo,
    menuUuid: item.menuUuid,
    gradeCode:item.gradeCode,
    gradeLevel:item.gradeLevel,
    isVip:item.isVip,
    // 是否需要关闭询问
    closeQuestion: item.menuTags == undefined ? false : JSON.parse(item.menuTags.value).closeQuestion,
    notCache: false,
    appCode: item.appCode
  }
  return item;
}
