import request from '@/utils/request'
import parseTime from '@/utils/index.js'

export function checkDates(data) {
  return request({
    url: '/authdata/checkDates',
    method: 'post',
    data
  })
}


export function GetDataByName(data) {
  return request({
    url: '/authdata/GetDataByName',
    method: 'post',
    data
  })
}


export function processAnalysist(data) {
  return request({
    url: '/authdata/processAnalysist',
    method: 'post',
    data
  })
}

export function ExeSqlJiade(data) {
  return request({
    url: '/authdata/exesql',
    method: 'post',
    data
  })
}
export function dashboardListJiade(data) {
  return request({
    url: '/authdata/Dashboards',
    method: 'post',
    data
  })
}
export function updateDashboardJiade(data) {
  return request({
    url: '/authdata/Updatedashboard',
    method: 'post',
    data
  })
}

export function GetReportform(data) {
  return request({
    url: '/authdata/GetReportform',
    method: 'post',
    timeout: 600000,
    data
  })
}
export function requestbyname(data, requestname) {
  return request({
    url: '/authdata/' + requestname,
    method: 'post',
    data
  })
}

export function GetDataByNameXlsx(data) {
  return request({
    url: '/authdata/GetDataByName',
    method: 'post',
    data,
    responseType: 'blob'
  })
}

export function GetDataByNames(data) {
  return request({
    url: '/authdata/GetDataByNames',
    method: 'post',
    data
  })
}

export function PostDataByName(data) {
  return request({
    url: '/authdata/PostDataByName',
    method: 'post',
    data
  })
}
export function GetUpkeepPlan(data) {
  return request({
    url: '/authdata/GetUpkeepPlan',
    method: 'post',
    data
  })
}
export function GetAccount(data) {
  return request({
    url: '/authdata/GetAccount',
    method: 'post',
    timeout: 600000,
    data
  })
}


export function postJson(url,data) {
  return request({
    url: process.env.VUE_APP_BASE_API + url,
    method: 'post',
    timeout: 600000,
    data
  })
}

export function postJson2(url,data) {
  return request({
    url: url,
    method: 'post',
    timeout: 600000,
    data
  })
}

export function getJson(url,data) {
  return request({
    url: process.env.VUE_APP_BASE_API + url + data,
    method: 'get'
  })
}

export function getData(url,data) {
  return request({
    url: url,
    method: 'post',
    timeout: 600000,
    data
  })
}

export function PostDataByNames(data) {
  return request({
    url: '/authdata/PostDataByNames',
    method: 'post',
    data
  })
}

export function ExecDataByConfig(data) {
  return request({
    url: '/authdata/ExecDataByConfig',
    method: 'post',
    data
  })
}

export function getDorm(data) {
  return request({
    url: '/authdata/getDorm',
    method: 'post',
    timeout: 6000000,
    data
  })
}

export function removeimage(data) {
  return request({
    url: '/authdata/removeimage',
    method: 'post',
    data
  })
}

export function getRecuData(data) {
  return request({
    url: '/authdata/GetRecuDataByName',
    method: 'post',
    data
  })
}
export function Autogeneration(data) {
  return request({
    url: '/authdata/autogeneration',
    method: 'post',
    data
  })
}
export function failproccess(data, notify) {
  if (data.data.includes('Duplicate')) {
    notify({
      title: '失败',
      message: '不可以录入重复数据',
      type: 'error',
      duration: 2000
    })
  } else {
    notify({
      title: '失败',
      message: '数据存在错误，请校验好重新录入，不可以录入数据',
      type: 'error',
      duration: 2000
    })
  }
}

export function UpdateDataRelation(data) {
  return request({
    url: '/authdata/UpdateDataRelation',
    method: 'post',
    data
  })
}

export function transData(a, idStr, pidStr, chindrenStr) {
  var r = []; var hash = {}; var id = idStr; var pid = pidStr; var children = chindrenStr; var i = 0; var j = 0; var len = a.length
  for (; i < len; i++) {
    hash[a[i][id]] = a[i]
  }
  for (; j < len; j++) {
    var aVal = a[j]; var hashVP = hash[aVal[pid]]
    if (hashVP) {
      !hashVP[children] && (hashVP[children] = [])
      hashVP[children].push(aVal)
    } else {
      r.push(aVal)
    }
  }
  return r
}

export function checkButtons(buttonsList, PermissionButtons) {
  console.log(PermissionButtons,'===888')
  console.log(buttonsList,'===888')
  for (let i = 0; i < buttonsList.length; i++) {
    // if (buttonsList[i].path === PermissionButtons && buttonsList[i].menu_id && buttonsList[i].path) { // path不为空且menu_id不为空时返回true
    if (buttonsList[i].path === PermissionButtons && buttonsList[i].editbutton == 1) { // path不为空且menu_id不为空时返回true
      return true
    }
  }
  return false
}

export function formatJson(filterVal, jsonData) {
  return jsonData.map(v =>
    filterVal.map(j => {
      if (j === 'timestamp') {
        return parseTime(v[j])
      } else {
        return v[j]
      }
    })
  )
}

export function DownloadExcel(data, filename) {
  const content = data
  const blob = new Blob([content])
  const fileName = filename + '.xlsx'
  if ('download' in document.createElement('a')) { // 非IE下载
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL 对象
    document.body.removeChild(elink)
  } else { // IE10+下载
    navigator.msSaveBlob(blob, fileName)
  }
}
// 取小数
// export function formatNum(f, digit) {
//   var m = Math.pow(10, digit);
//   return parseInt(f * m, 10) / m;
// }
export function formatNum(value, n) {
  console.log(value, n,'====')
  var f = Math.round(value*Math.pow(10,n))/Math.pow(10,n);
  var s = f.toString();
  var rs = s.indexOf('.');
  if(rs < 0) {
    if(n==0){
      s = s
    }else{
      s += '.';
    }
  }
  for(var i = s.length - s.indexOf('.'); i <= n; i++){
    s += "0";
  }
  return s;
}

export function compareSort(property){
  return function(a,b){
    var value1 = a[property];
    var value2 = b[property];
    return value1 - value2;
  }
}


//将日期转换成一年中的第几周
export function getYearWeek(date) {
  //按照国际标准
  let time,
    week,
    checkDate = new Date(date);
  checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
  time = checkDate.getTime();
  checkDate.setMonth(0);
  checkDate.setDate(1);
  week = Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
  return week;
}

//返回格式 2019年第23周，特别注意跨年一周的问题
export function getYearAndWeek(date, anotherDate) {
  let week = getYearWeek(date);
  let year = date.substring(0, 4);
  let anotherYear = anotherDate.substring(0, 4);
  //处理跨年特殊日期
  if (anotherDate > date) {
    let betweenDay = getBetweenDay(new Date(date), new Date(anotherDate));
    if (betweenDay == 7 && anotherYear != year) {
      if (week == 1) {
        year = parseInt(year) + 1;
      }
    }
  } else {
    let betweenDay = getBetweenDay(new Date(anotherDate), new Date(date));
    if (betweenDay == 7 && anotherYear != year) {
      if (week != 1) {
        year = parseInt(year) - 1;
      }
    }
  }
  return `${year}年第${week}周`;
}
export function getBetweenDay(beginDate, endDate) {
  let dateSpan = endDate - beginDate;
  dateSpan = Math.abs(dateSpan);
  let days = Math.floor(dateSpan / (24 * 3600 * 1000));
  return days + 1;
}
//获取当前count个周的起止日期，如：count=0 ,就是当前周，-1就是上周，以此类推
export function getWeekStartAndEnd(count, currentDate) {
  //起止日期数组
  let resultArr = new Array();
  let millisecond = 1000 * 60 * 60 * 24;
  currentDate = new Date(currentDate.getTime() + millisecond * 7 * count);
  let week = currentDate.getDay();

  //减去的天数
  let minusDay = week != 0 ? week - 1 : 6;
  //获得当前周的第一天
  let currentWeekFirstDay = new Date(
    currentDate.getTime() - millisecond * minusDay
  );
  //获得当前周的最后一天
  let currentWeekLastDay = new Date(
    currentWeekFirstDay.getTime() + millisecond * 6
  );

  resultArr.push(currentWeekFirstDay.format());
  resultArr.push(currentWeekLastDay.format());
  return resultArr;
}
Date.prototype.format = function() {
  let s = "";
  let mouth =
    this.getMonth() + 1 >= 10
      ? this.getMonth() + 1
      : "0" + (this.getMonth() + 1);
  let day = this.getDate() >= 10 ? this.getDate() : "0" + this.getDate();
  s += this.getFullYear() + "-"; // 获取年份。
  s += mouth + "-"; // 获取月份。
  s += day; // 获取日。
  return s; // 返回日期。
};

/**
 * @param date 传入的日期
 * @param num 加减的天数，加为正，减为负
 * @returns 格式化后的日期
 */
export function addDays(date, num) {
  date.setDate(date.getDate() + num);
  return date.format();
}

export function yearDay(long) {
  var time = new Date(long * 1000)
  var year = time.getFullYear()
  var month = (time.getMonth() + 1) < 10 ? '0' + (time.getMonth() + 1) : (time.getMonth() + 1)
  var date = time.getDate() < 10 ? '0' + time.getDate() : time.getDate()
  var yearday = { year, month, date }
  return yearday
}

// 计算一年中的每一周都是从几号到几号
// 第一周为1月1日到 本年的 第一个周日
// 第二周为 本年的 第一个周一 往后推到周日
// 以此类推 再往后推52周。。。
// 如果最后一周在12月31日之前，则本年有垮了54周，反之53周
// 12月31 日不论是周几，都算为本周的最后一天
// 参数年份 ，函数返回一个数组，数组里的对象包含 这一周的开始日期和结束日期
export function whichWeek(year) {
      var d = new Date(year, 0, 1)
      while (d.getDay() != 1) {
        d.setDate(d.getDate() + 1)
      }
      const arr = []
      const longnum = d.setDate(d.getDate())
      if (longnum > +new Date(year, 0, 1)) {
        const obj = yearDay(+new Date(year, 0, 1) / 1000)
        obj.last = yearDay(longnum / 1000 - 86400)
        arr.push(obj)
      }
      const oneitem = yearDay(longnum / 1000)
      oneitem.last = yearDay(longnum / 1000 + 86400 * 6)
      arr.push(oneitem)
      var lastStr
      for (var i = 0; i < 51; i++) {
        const long = d.setDate(d.getDate() + 7)
        const obj = yearDay(long / 1000)
        obj.last = yearDay(long / 1000 + 86400 * 6)
        lastStr = long + 86400000 * 6
        arr.push(obj)
      }
      if (lastStr < +new Date(year + 1, 0, 1)) {
        const obj = yearDay(lastStr / 1000 + 86400)
        obj.last = yearDay(+new Date(year + 1, 0, 1) / 1000 - 86400)
        arr.push(obj)
      } else {
        arr[arr.length - 1].last = yearDay(+new Date(year + 1, 0, 1) / 1000 - 86400)
      }
      return arr
    }
    
    export function getUUID(len, radix) {
      var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
      var uuid = []
      var i
      radix = radix || chars.length
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
      } else {
        var r
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
        uuid[14] = '4'
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | Math.random() * 16
            uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
          }
        }
      }
      return uuid.join('')
    }
