import XEUtils from "xe-utils"
import cal from '@/utils/calculation'
import{getDictValue} from '@/utils/dict'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export  function getBMBM(bm,dict) {
  for (const b in dict) {
    if (dict[b].departCode === bm) {
      return dict[b].departName;
    }
  }
  return ''
}
// 续签单位
export  function getXQBMBM(bm,dict) {
  for (const b in dict) {
    if (dict[b].ddepartCode === bm) {
      return dict[b].ddepartName;
    }
  }
  return ''
}
// 根据 code 和名字去查找
export  function getAllBm(bm,dict,code,name) {
  for (const b in dict) {


    if (dict[b][code] === bm) {

      return dict[b][name];

    }
  }
  return ''
}

export  function getZHBM(bm,dict) {
  for (var b in dict) {
    if (dict[b].itemCode === bm) {
      return dict[b].itemValue
    }
  }
  return ''
}



export function getSumAdd(list, field){

    let count = 0
    list.forEach(item => {
      let num = Number(item[field])
      if (!XEUtils.isNumber(num) || isNaN(num)) {
        num = 0
      }
      count = cal.accAdd(count, num)
    })
    return count

}

export function  getSumAddDicByName1(list,field,...rest) {
  let count = 0
  const cache = [];
  let t;
  function check(item) {
    let trueList = [];
    let args;
    for(args of rest) {
      trueList.push(item[args] === t[args])
    }
    return trueList.every(item => item)
  }
  for (t of list) {
    if (cache.find(check)) {
      continue;
    }
    cache.push(t);
  }
  for( let qc of cache){
    let num = Number(qc[field])
    if (!XEUtils.isNumber(num) || isNaN(num)) {
      num = 0
    }
    count = cal.accAdd(count, num)
  }
  return count
}
//根据属相去重相加
export function  getSumAddDicByName(list,...rest) {
  let count = 0
  const cache = [];
  let t;
  function check(item) {
    let trueList = [];
    let args;
    for(args of rest) {
      trueList.push(item[args] === t[args])
    }
    return trueList.every(item => item)
  }
  for (t of list) {
    if (cache.find(check)) {
      continue;
    }
    cache.push(t);
  }
  for( let qc of cache){
    count = cal.accAdd(count, 1)
  }
  return count
}

export  function newObj(originObj) {
  console.log(originObj)
   new Proxy(originObj, {
    get: (target,paramKey) =>{
      if(target[paramKey]===null){

       return target[paramKey]=''
      }else{
        return  target[paramKey]
      }
    }
  })
}
// 字段null转字符串''
export function null2str(data) {
  for (let x in data) {
    if (data[x] === null) {
      // 如果是null 把直接内容转为 ''
      data[x] = "";
    } else {
      if (Array.isArray(data[x])) {
        // 是数组遍历数组 递归继续处理
        data[x] = data[x].map((z) => {
          return null2str(z);
        });
      }
      if (typeof data[x] === "object") {
        // 是json 递归继续处理
        data[x] = null2str(data[x]);
      }
    }
  }
  return data;
}

/**
 * 计算2个日期相差的天数，不包含今天，如：2016-12-13到2016-12-15，相差2天
 * @param startDateString
 * @param endDateString
 * @returns
 */
export function dateDiff(startDateString, endDateString){
  console.log(startDateString)
  console.log(endDateString)
  var separator = "/"; //日期分隔符
  var startDates = startDateString.split(separator);
  var endDates = endDateString.split(separator);
  var startDate = new Date(startDates[0], startDates[1]-1, startDates[2]);
  var endDate = new Date(endDates[0], endDates[1]-1, endDates[2]);
  return parseInt(Math.abs(endDate - startDate ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
};



/**
 * 计算2个日期相差的天数，包含今天，如：2016-12-13到2016-12-15，相差3天
 * @param startDateString
 * @param endDateString
 * @returns
 */
export function dateDiffIncludeToday(startDateString, endDateString){
  var separator = "/"; //日期分隔符
  var startDates = startDateString.split(separator);
  var endDates = endDateString.split(separator);
  var startDate = new Date(startDates[0], startDates[1]-1, startDates[2]);
  var endDate = new Date(endDates[0], endDates[1]-1, endDates[2]);
  return parseInt(Math.abs(endDate - startDate ) / 1000 / 60 / 60 /24) + 1;//把相差的毫秒数转换为天数
};

export function changeData(s) {

  //如果存在ArrayBuffer对象(es6) 最好采用该对象
  if (typeof ArrayBuffer !== 'undefined') {

    //1、创建一个字节长度为s.length的内存区域
    var buf = new ArrayBuffer(s.length);

    //2、创建一个指向buf的Unit8视图，开始于字节0，直到缓冲区的末尾
    var view = new Uint8Array(buf);

    //3、返回指定位置的字符的Unicode编码
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;

  } else {
    var buf = new Array(s.length);
    for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
}

/***
 *
 * @param tableColumn 类名
 * @param tableData 数据
 * @param index 类名重第几个开始 （去掉复选框）
 * @param name
 */
export  function exportByExcel(tableColumn,tableData,index,name) {
  let wopts = {
    bookType: 'xlsx',
    bookSST: true,
    type: 'binary'
  };
  let workBook = {
    SheetNames: ['Sheet1'],
    Sheets: {},
    Props: {}
  };
  let table =[];

  //let num=0;
  if(tableData.length===0){
    return
  }
  let xh=1;
  for (let i = 0; i < tableData.length; i++) {
    let obj = {}
    for (let j = index; j < tableColumn.length; j++) {

      if (tableColumn[j].title === '序号') {
        obj[tableColumn[j].title] = xh++

      } else if (tableColumn[j].formatter !== undefined) {

        let code = tableColumn[j].formatter[1]
        let name = tableColumn[j].formatter[0]
        let value = tableData[i][tableColumn[j].field]
        if(name==='deptFormat'){
          // console.log(tableData[i][tableColumn[j].field])
        }

        obj[tableColumn[j].title] = getDictValue(name, code, value);


      } else {
        obj[tableColumn[j].title] = tableData[i][tableColumn[j].field] == undefined ? '' : tableData[i][tableColumn[j].field]
      }
    }
    table[i] = obj
  }

  workBook.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(table);
  FileSaver.saveAs(new Blob([changeData(XLSX.write(workBook, wopts))], {type: 'application/octet-stream'}), name)
}



