/*
 * vue全局方法
 */
import Vue from 'vue';
import store from '@/store/index.js';
// 打印全局方法
Vue.prototype.printPage = function (sid, stitle) {
  let oP = {};
  if (stitle) {
    oP.extraHead = '<div style="text-align: center; padding: 10px 0 20px 0; font-size: 20px;">' + stitle + '</div>';
  }
  $('#' + sid).printArea(oP);
};
// 全局过滤方法
Vue.prototype.filterColumn = function (value, row, column) {
  let propt = null;
  //  && (row[column.property] || parseInt(row[column.property]) === 0)
  console.log('数据', column.property)
  if (column && column.property) {
    propt = (row[column.property] || row[column.property] === 0) ? (row[column.property] + '') : '';
  } else {
    // console.log('执行了2', row[column.property])
    return false;
  }
  // if (value || parseInt(value) === 0) {
  // 修改全局過濾方法，过滤空白筛选
  return propt === value + '';
  // }
  // return false;
};
/**
 * @summary 表格列过滤
 * @param {Array} tableColumns 列数组对象（详情请console）
 * @param {Array} data 需要过滤的数据
 * @param {Array} columns 需要过滤的列名
 * @param {Object} desData 列名转义对象 e.g. {'1': '不横切', '2': '一切二', '3': '一切三'}
 * */
Vue.prototype.setFilterDatas = function (tableColumns = [], data = [], columns = [], desData = {}) {
  let objs = {};
  // 过滤数据，得到对象 {order_no: {'001': '001'}, ...}
  for (let fitem of data) {
    for (let fsitem of columns) {
      if (!objs[fsitem]) {
        objs[fsitem] = {};
      }
      if (fitem[fsitem] || fitem[fsitem] === 0) {
        // console.log('筛选', fitem[fsitem], objs[fsitem][fitem[fsitem]])
        objs[fsitem][fitem[fsitem]] = fitem[fsitem];
      } else {
        objs[fsitem][''] = '';
      }
    }
  }
  for (let [k_, v_] of Object.entries(objs)) {
    // k_ 为字段名；v_ 为{"0PAA10":"0PAA10","0PAA12":"0PAA12"}
    // objs[k_] = [];
    let aItem = [];
    for (let v2_ of Object.values(v_)) {
      let _test = v2_;
      // code -> name
      if (desData && desData[k_]) { _test = desData[k_][v2_]; }
      aItem.push({
        value: v2_,
        text: _test
      });
    }
    // 为列加入filters 并自定义 filterReset
    for (let tcitem of tableColumns) {
      if (tcitem.property === k_) {
        tcitem.filters = aItem;
        tcitem.filterReset = true;
        break;
      }
    }
  }
};

/**
 * 列表数据筛选联动监听
 * data 筛选后的数据
 * tableColumn需要变化的筛选条件
 */
Vue.prototype.filterColumnWatch = function (data = [], tableColumn = {}) {
  let filters = [];
  let property = tableColumn.property;
  for (let i in data) {
    let flag = true;
    for (let j in filters) {
      if ((filters[j].value + '') === (data[i][property] + '')) {
        flag = false;
        break;
      }
    }
    if (flag) {
      filters.push({
        value: data[i][property],
        text: data[i][property]
      })
    }
  }
  tableColumn.filters = filters;
}

/**
 * 表格合并列
 * @param {当前表格显示数据} tableData
 * @param {span-method自带参数*} param1
 * @param {需要合并的列，如果不传默认全部*} propertyList
 */
Vue.prototype.mergeColumn = function (tableData, { row, column, rowIndex, columnIndex }, propertyList) {
  let rowsPan = 1;
  let thisColomnData = row[column['property']];
  let thisMergeFlag = false;
  if (typeof (propertyList) === 'undefined') {
    thisMergeFlag = true;
  } else if (propertyList.includes(column['property'])) {
    thisMergeFlag = true;
  }
  if (thisMergeFlag && thisColomnData) {
    if (rowIndex > 0 && thisColomnData === tableData[rowIndex - 1][column['property']]) {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
    while (tableData[rowIndex + rowsPan] && thisColomnData === tableData[rowIndex + rowsPan][column['property']]) {
      rowsPan += 1
    }
    return {
      rowspan: rowsPan,
      colspan: 1
    };
  }
}

/**
 * 行拖动排序
 * @param {当前表格显示数据} tableData
 * @param {起始位置} startIndex
 * @param {结束位置} endIndex
 */
Vue.prototype.changeRowOrder = function (allRow, startIndex, endIndex) {
  let temp = [];
  for (let i = 0; i < allRow.length; i++) {
    if (i === startIndex) {
      continue;
    } else if (i === endIndex) {
      temp.push(allRow[endIndex]);
      temp.push(allRow[startIndex]);
    } else {
      temp.push(allRow[i]);
    }
  }
  return temp;
}

let privilegeData = [];

function getPrivilegeFlag (privilegeMark, privilegeData) {
  let privilegeFlag = false;
  privilegeData = window.top.localStorage.getItem('ownPrivilege') && window.top.localStorage.getItem('ownPrivilege') !== 'undefined' ? JSON.parse(window.top.localStorage.getItem('ownPrivilege')) : [];
  for (let i = 0; i < privilegeData.length; i++) {
    let menuPrivilege = privilegeData[i].pId + privilegeData[i].privilege
    if (privilegeData[i].menuType === '2' && privilegeMark === menuPrivilege) {
      privilegeFlag = true;
      break;
    } else if (privilegeData[i].children !== null && privilegeData[i].children.length > 0) {
      privilegeFlag = getPrivilegeFlag(privilegeMark, privilegeData[i].children);
      if (privilegeFlag) break;
      else continue;
    }
  }
  return privilegeFlag;
}

Vue.prototype.checkPrivilege = function (privilega) {
  privilegeData = window.top.localStorage.getItem('ownPrivilege') && window.top.localStorage.getItem('ownPrivilege') !== 'undefined' ? JSON.parse(window.top.localStorage.getItem('ownPrivilege')) : [];
  if (privilegeData.length === 0) {
    store.dispatch('generateRoutes').then(function (res) {
      privilegeData = window.top.localStorage.getItem('ownPrivilege') && window.top.localStorage.getItem('ownPrivilege') !== 'undefined' ? JSON.parse(window.top.localStorage.getItem('ownPrivilege')) : [];
      if (privilegeData.length > 0) {
        let privilegeFlag = getPrivilegeFlag(privilega, privilegeData);
        return privilegeFlag
      }
    }).catch(function () {
    });
  } else {
    privilegeData = window.top.localStorage.getItem('ownPrivilege') && window.top.localStorage.getItem('ownPrivilege') !== 'undefined' ? JSON.parse(window.top.localStorage.getItem('ownPrivilege')) : [];
    if (privilegeData.length > 0) {
      let privilegeFlag = getPrivilegeFlag(privilega, privilegeData);
      return privilegeFlag
    }
  }
}

// 新的权限指令封装
Vue.directive('privilege', {
  inserted: function (_el, _binding) {
    let menuId = window.activeMenu || window.top.localStorage.getItem('activeMenu');
    let checkFoo = (privilegeData, {el, binding} = {el: _el, binding: _binding}) => {
      let privilegeFlag = false;
      let privilegeMark = binding.value;
      // console.log({el, binding})
      for (let i = 0; i < privilegeData.length; i++) {
        if (privilegeData[i].privilege === privilegeMark || (menuId + privilegeData[i].privilege) === privilegeMark) {
          privilegeFlag = true;
          break;
        }
      }
      if (!privilegeFlag) {
        $(el).hide();
      }
    };
    if (window.privilegeData && window.privilegeData.length > 0) {
      checkFoo(window.privilegeData);
    } else {
      // 将待判断的项目添加至数组，等待数据获取完毕后再进行判断
      window.privilegeAwaitItem ? window.privilegeAwaitItem.push({el: _el, binding: _binding}) : window.privilegeAwaitItem = [{el: _el, binding: _binding}];
      if (!window.privilegeLoading) {
        window.privilegeLoading = true;
        getPrivilegeData(({arr, obj}) => {
          // console.log(window.privilegeAwaitItem)
          window.privilegeData = arr;
          for (let item of window.privilegeAwaitItem) {
            checkFoo(window.privilegeData, item);
          }
          window.privilegeAwaitItem = null;
          window.privilegeLoading = false;
          // console.log(window.privilegeAwaitItem)
        });
      }
    }
  },
  update: function (el, binding) {
    // TODO
  },
  componentUpdated: function (el, binding) {
    // todo
  }
})

Vue.prototype.getPrivilegeData = getPrivilegeData;
/**
 * 获取当前用户在当前页面内所拥有的所有权限
 * @param {Function} foo 回调函数，用于接收数据
 */
function getPrivilegeData (foo) {
  console.log(window.activeMenu)
  let menuId = window.activeMenu || window.top.localStorage.getItem('activeMenu');
  Vue.prototype.axios.get('pass/v1/sysmenus/findFunctionMenusByUserId?menuType=2&companyId=' + window.top.localStorage.getItem('companyId') + '&pId=' + menuId)
    .then(res => {
        if (res.code === '0') {
            let arr = [],
                obj = {};
            for (let item of res.data) {
              if (item.pId === menuId) {
                arr.push(item);
                obj[item.privilege] = true;
              }
            }
            foo({arr, obj});
        } else {
            foo({arr: [], obj: {}});
            this.$message.error(res.message)
        }
    }).catch(() => {
      foo({arr: [], obj: {}});
    });
}

Vue.prototype.toFixed = function (number, n) {
  if (n > 20 || n < 0) {
    throw new RangeError('toFixed() digits argument must be between 0 and 20');
  }
  // const number = this;
  if (isNaN(number) || number >= Math.pow(10, 21)) {
    return number.toString();
  }
  if (typeof (n) === 'undefined' || n === 0) {
    return (Math.round(number)).toString();
  }

  let result = number.toString();
  const arr = result.split('.');

  // 整数的情况
  if (arr.length < 2) {
    result += '.';
    for (let i = 0; i < n; i += 1) {
      result += '0';
    }
    return result;
  }

  const integer = arr[0];
  const decimal = arr[1];
  if (decimal.length === n) {
    return result;
  }
  if (decimal.length < n) {
    for (let i = 0; i < n - decimal.length; i += 1) {
      result += '0';
    }
    return result;
  }
  result = integer + '.' + decimal.substr(0, n);
  const last = decimal.substr(n, 1);

  // 四舍五入，转换为整数再处理，避免浮点数精度的损失
  if (parseInt(last, 10) >= 5) {
    const x = Math.pow(10, n);
    result = (Math.round((parseFloat(result) * x)) + 1) / x;
    result = result.toFixed(n);
  }
  return result;
};
