



// 时间月份差
export function getMonth(startDate, endDate) {
  startDate = startDate.split("-");
  // 得到月数
  startDate = parseInt(startDate[0]) * 12 + parseInt(startDate[1]);
  // 拆分年月日
  endDate = endDate.split("-");
  // 得到月数
  endDate = parseInt(endDate[0]) * 12 + parseInt(endDate[1]);
  let times = Math.abs(startDate - endDate);
  return times;
}
//处理NVTAFF数据
export function handeNVTFFData(data) {
  let times = data;
  let itemTime = [];
  let itemData = [];
  // x 坐标赋值
  times.forEach((item) => {
    var now = item.time.split("T");
    itemTime.push(now[0]);
    itemData.push(item.NVTAdjFF90);
  });
  return itemData;
}

//处理NVTA数据
export function handeNVTAData(data) {
  let times = data;
  let itemTime = [];
  let itemData = [];
  // x 坐标赋值
  times.forEach((item) => {
    var now = item.time.split("T");
    itemTime.push(now[0]);
    itemData.push(item.NVTAdj90);
  });
  return itemData;
}

//处理MVRV数据
export function handelData(data) {
  let times = data;

  let itemTime = [];
  let itemData = [];
  // x 坐标赋值 
  times.forEach((item) => {
    var now = item.time.split("T");
    itemTime.push(now[0]);
    itemData.push(Number(item.value).toFixed(2));
  });

  return itemData;
}

//处理capReal数据
export function handelCapReal(data) {
  let times = data;

  // let itemTime = [];
  let itemData = [];
  // x 坐标赋值 
  times.forEach((item) => {
    // var now = item.time.split("T");
    // itemTime.push(now[0]);
    itemData.push(Number(item.capReal.toFixed(2)));
  });

  return itemData;
}

//取时间天数
export function getDiffDay(date_1, date_2) {
  let totalDays, diffDate;
  let myDate_1 = Date.parse(date_1);
  let myDate_2 = Date.parse(date_2);
  // 将两个日期都转换为毫秒格式，然后做差
  diffDate = Math.abs(myDate_1 - myDate_2); // 取相差毫秒数的绝对值
  totalDays = Math.floor(diffDate / (1000 * 3600 * 24)); // 向下取整
  return totalDays; // 相差的天数
}

//分组求和年月的数据
export function setGrouping(data) {
  //分组求和
  function groupBy(data) {
    //月
    let arrTime = [
      ...new Set(
        data.map((_) => {
          //用反射把时间格式统一为yyyy-MM 并分组
          Reflect.set(_, "time", formatDate(_.time));
          return _.time;
        })
      ),
    ].map((_) => {
      return { time: _, month: {}, sumMonth: {} };
    });

    //双重循环计算月合计

    arrTime.forEach((_) => {
      var sumMonth = 0;
      data.forEach((item) => {
        if (_.time == item.time) {
          sumMonth += item.CapMVRVCur;
          _.sumMonth = sumMonth;
          _.month = _.time.slice(-2);
        }
      });
    });

    //年

    let arr = [
      ...new Set(
        arrTime.map((_) => {
          //根据年分组
          return _.time.slice(0, 4);
        })
      ),
    ].map((_) => {
      return { year: _, sumYear: {}, months: [] };
    });
    //双重循环计算年合计
    arr.forEach((_) => {
      var sumYear = 0;
      arrTime.forEach((item) => {
        if (_.year == item.time.slice(0, 4)) {
          sumYear += item.sumMonth;
          _.sumYear = sumYear;
          _.year = _.year;
          _.months.push(item);
        }
      });
    });

    return arr;
  }
  //格式化时间
  function convertToDate(date) {
    if (isNaN(new Date(date).getTime())) {
      throw new Error(`${date} 不是一个有效的时间`);
    }
    if (!(date instanceof Date)) {
      date = new Date(date);
    }
    return date;
  }
  function formatDate(date, format = "yyyy-MM") {
    date = convertToDate(date);
    const o = {
      "y+": date.getFullYear(),
      "M+": date.getMonth() + 1,
      "d+": date.getDate(),
      "h+": date.getHours(),
      "m+": date.getMinutes(),
      "s+": date.getSeconds(),
    };
    for (let k in o) {
      if (new RegExp(`(${k})`).test(format)) {
        format = format.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : `0${o[k]}`.substr(-RegExp.$1.length)
        );
      }
    }
    return format;
  }
  return groupBy(data);
}

//清理echarts 避免重复生成
export function resetTheChart(_that) {
  if (
    _that.myChart != null &&
    _that.myChart != "" &&
    _that.myChart != undefined
  ) {
    _that.myChart.dispose();

  }
}
//处理ALL的数据
export function handelAllData(that, data, itemValueList) {

  function setGrouping(data) {
    //分组求和
    function groupBy(data) {
      //月
      let arrTime = [
        ...new Set(
          data.map((_) => {
            //用反射把时间格式统一为yyyy-MM 并分组
            Reflect.set(_, "time", formatDate(_.time));
            return _.time;
          })
        ),
      ].map((_) => {
        return { time: _, month: {}, sumMonth: {} };
      });

      //双重循环计算月合计

      arrTime.forEach((_) => {
        var sumMonth = 0;
        data.forEach((item) => {
          if (_.time == item.time) {
            sumMonth += item.CapMVRVCur;
            _.sumMonth = sumMonth;
            _.month = _.time.slice(-2);
          }
        });
      });

      //年

      let arr = [
        ...new Set(
          arrTime.map((_) => {
            //根据年分组
            return _.time.slice(0, 4);
          })
        ),
      ].map((_) => {
        return { year: _, sumYear: {}, months: [] };
      });
      //双重循环计算年合计
      arr.forEach((_) => {
        var sumYear = 0;
        arrTime.forEach((item) => {
          if (_.year == item.time.slice(0, 4)) {
            sumYear += item.sumMonth;
            _.sumYear = sumYear;
            _.year = _.year;
            _.months.push(item);
          }
        });
      });

      return arr;
    }
    //格式化时间
    function convertToDate(date) {
      if (isNaN(new Date(date).getTime())) {
        throw new Error(`${date} 不是一个有效的时间`);
      }
      if (!(date instanceof Date)) {
        date = new Date(date);
      }
      return date;
    }
    function formatDate(date, format = "yyyy-MM") {
      date = convertToDate(date);
      const o = {
        "y+": date.getFullYear(),
        "M+": date.getMonth() + 1,
        "d+": date.getDate(),
        "h+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds(),
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(format)) {
          format = format.replace(
            RegExp.$1,
            RegExp.$1.length === 1
              ? o[k]
              : `0${o[k]}`.substr(-RegExp.$1.length)
          );
        }
      }
      return format;
    }
    return groupBy(data);
  }
  let newData = setGrouping(data);
  let yearValue = []
  let monthsValue = []
  newData.forEach((yearItem) => {
    yearValue.push(+yearItem.sumYear.toFixed(3));
    yearItem.months.forEach((monthsItem) => {
      monthsValue.push(+monthsItem.sumMonth.toFixed(3));
    });
  });

  that.myChart = that.$echarts.init(document.getElementById("main"));
  let startTime = newData[0].months[0].time + "-01";
  let months = newData[newData.length - 1].months;
  let endTime =
    newData[newData.length - 1].months[months.length - 1].time + "-01";

  let base = +new Date(startTime);

  let oneDay = 24 * 31 * 3600 * 1000;
  let totalDay = getMonth(startTime, endTime);

  data = [[base, monthsValue[0]]];
  for (let i = 1; i < totalDay; i++) {
    let now = new Date((base += oneDay));
    if (i - 1 == 0) {
      data.push([+now, monthsValue[i]]);
      itemValueList.splice(0, 1);
    } else {
      data.push([+now, monthsValue[i - 1]]);
    }
  }

  return data;
}
//生成二维数组
export function handelTotalData(data, value) {
  let startTime = data[0].time.split("T")[0].replace(/-/g, ",");
  let endTime = data[data.length - 1].time.split("T")[0].replace(/-/g, ",");
  let base = +new Date(startTime);

  let oneDay = 24 * 3600 * 1000;
  let totalDay = getDiffDay(startTime, endTime) + 1;
  let date = [[base, value[0]]];
  for (let i = 1; i < totalDay; i++) {
    let now = new Date((base += oneDay));
    if (i - 1 == 0) {
      date.push([+now, value[i]]);
      value.splice(0, 1);
    } else {
      date.push([+now, value[i - 1]]);
    }
  }
  return date;
}




//K线图生成二维数组
export function handelKlineGraph(data, valueList) {

  let value = []
  let date
  if (valueList) {
    value = valueList
    let startTime = data[0].time.split("T")[0].replace(/-/g, ",");
    let endTime = data[data.length - 1].time.split("T")[0].replace(/-/g, ",");
    let base = +new Date(startTime);
    let oneDay = 24 * 3600 * 1000;
    let totalDay = getDiffDay(startTime, endTime) + 1;
    date = [[base, value[0]]];
    for (let i = 1; i < totalDay; i++) {
      let now = new Date((base += oneDay));
      if (i - 1 == 0) {
        date.push([+now, value[i]]);
        value.splice(0, 1);
      } else {
        date.push([+now, value[i - 1]]);
      }
    }
  } else {

    data.forEach((item) => {
      value.push([
        //series数据处理
        Number(item.openPrice).toFixed(2),
        Number(item.closePrice).toFixed(2),
        Number(item.lowestPrice).toFixed(2),
        Number(item.highestPrice).toFixed(2),
      ]);
    });
    let startTime = data[0].time.split("T")[0].replace(/-/g, ",");
    let endTime = data[data.length - 1].time.split("T")[0].replace(/-/g, ",");
    let base = +new Date(startTime);
    let oneDay = 24 * 3600 * 1000;
    let totalDay = getDiffDay(startTime, endTime) + 1;
    date = [[base, ...value[0]]];
    for (let i = 1; i < value.length; i++) {
      let now = new Date((base += oneDay));
      if (i - 1 == 0) {
        date.push([+now, ...value[i]]);
        value.splice(0, 1);
      } else {
        date.push([+now, ...value[i - 1]]);
      }

    }


  }


  return date;
}

//K线图closePrice单独取出处理
export function handelClosePrice(data) {
  let closePrice = []
  data.forEach((item) => {
    closePrice.push(Number(item.closePrice).toFixed(2))
  });
  return closePrice;
}



//Jzr接口统一处理方法返回三项值的大数组
export function handelJzr(data) {
  let price = []
  let jzr60 = []
  let arr = []
  data.forEach(item => {
    jzr60.push(item.jzr60)
    price.push(item.price)
  })
  arr.push(jzr60, price)
  return arr
}

//生成二维数组
export function handelCddData(data, value) {
  let startTime = data[0].date.split("T")[0].replace(/-/g, ",");
  let endTime = data[data.length - 1].date.split("T")[0].replace(/-/g, ",");
  let base = +new Date(startTime);
 
  let oneDay = 24 * 3600 * 1000;
  let totalDay = getDiffDay(startTime, endTime) + 1;
  let date = [[base, value[0]]];
  for (let i = 1; i < value.length; i++) {
    let now = new Date((base += oneDay));
    if (i - 1 == 0) {
      date.push([+now, value[i]]);
      value.splice(0, 1);
    } else {
      date.push([+now, value[i - 1]]);
    }
  }
  return date;
}
//生成Profitrate二维数组
export function handelProfitrate(data, value) {

  let startTime = data[0].date.split("T")[0].replace(/-/g, ",");
  let endTime = data[data.length - 1].date.split("T")[0].replace(/-/g, ",");
  let base = +new Date(startTime);
  let oneDay = 24 * 3600 * 1000;
  let totalDay = getDiffDay(startTime, endTime) + 1;
  let date = [[base, value[0]]];
  for (let i = 1; i <= value.length; i++) {

    let now = new Date((base += oneDay));
    if (i - 1 == 0) {
      date.push([+now, value[i]]);
      value.splice(0, 1);
    } else {
      date.push([+now, value[i - 1]]);
    }
  }

  return date;
}
//生成USDT二维数组 dateTime
export function handelUsdt(data, value) {

  let startTime = data[0].dateTime.split("T")[0].replace(/-/g, ",");
  let endTime = data[data.length - 1].dateTime.split("T")[0].replace(/-/g, ",");
  let base = +new Date(startTime);
  let oneDay = 24 * 3600 * 1000;
  let totalDay = getDiffDay(startTime, endTime) + 1;
  let date = [[base, value[0]]];
  for (let i = 1; i < totalDay; i++) {
    let now = new Date((base += oneDay));
    if (i - 1 == 0) {
      date.push([+now, value[i]]);
      value.splice(0, 1);
    } else {
      date.push([+now, value[i - 1]]);
    }
  }

  return date;
}
//生成Profitrate二维数组
export function handelBigDeals(data, value) {

  let startTime = data[0].dataTime.split("T")[0].replace(/-/g, ",");
  let endTime = data[data.length - 1].dataTime.split("T")[0].replace(/-/g, ",");
  let base = +new Date(startTime);
  let oneDay = 24 * 3600 * 1000;
  let totalDay = getDiffDay(startTime, endTime) + 1;
  let date = [[base, value[0]]];
  for (let i = 1; i <totalDay; i++) {
  
    let now = new Date((base += oneDay));
    if (i - 1 == 0) {
      date.push([+now, value[i]]);
      value.splice(0, 1);
    } else {
      date.push([+now, value[i - 1]]);
    }
  }

  return date;
}

//生成BTC价格二维数组
export function handelBtcPrice(data, value) {
  let startTime = data[0].time.split("T")[0].replace(/-/g, ",")
  let endTime = data[data.length - 1].time.split("T")[0].replace(/-/g, ",");
  let base = +new Date(startTime);
  let oneDay = 24 * 3600 * 1000;
  let totalDay = getDiffDay(startTime, endTime) + 1;
  let date = [[base, value[0]]];
  for (let i = 1; i <= value.length; i++) {
    let now = new Date((base += oneDay));
    if (i - 1 == 0) {
      date.push([+now, value[i]]);
      value.splice(0, 1);
    } else {
      date.push([+now, value[i - 1]]);
    }
  }

  return date;
}
//生成二维数组
export function handelDimensionalArr(data, value) {
  let startTime = data[0].date.split("T")[0].replace(/-/g, ",")
  let endTime = data[data.length - 1].date.split("T")[0].replace(/-/g, ",");
  let base = +new Date(startTime);
  let oneDay = 24 * 3600 * 1000;

  let totalDay = getDiffDay(startTime, endTime) + 1;
  let date = [[base, value[0]]];
  for (let i = 1; i <= value.length; i++) {
    let now = new Date((base += oneDay));
    if (i - 1 == 0) {
      date.push([+now, value[i]]);
      value.splice(0, 1);
    } else {
      date.push([+now, value[i - 1]]);
    }
  }

  return date;
}

//按小时渲染生成维数组
export function handelArhday(data, value) {
  let dayTime = []
  data.forEach(item => {
    let day = item.date.split("T")[0]
    let hours = item.date.split("T")[1].split(".")[0]
    dayTime.push(`${day} ${hours}`)
  })

  let date = [[dayTime[0], value[0]]];
  for (let i = 1; i < dayTime.length; i++) {
    date.push([dayTime[i - 1], value[i - 1].toFixed(2)]);
    // if (i - 1 == 0) {
    //   date.push([dayTime[i], value[i]]);
    //   value.splice(0, 1);
    // } else {
    //   date.push([dayTime[i-1], value[i - 1]]);
    // }
  }

  return date;
}

//按小时渲染生成维数组 Bi An Controller
export function handelbian(bianData, value) {
  let dayTime = []
  bianData.forEach(item => {
    let day = item.openTime.split("T")[0]
    let hours = item.openTime.split("T")[1].split(".")[0]
    dayTime.push(`${day} ${hours}`)
  })

  let date = [[dayTime[0], ...value[0]]];
  for (let i = 1; i < dayTime.length; i++) {
    date.push([dayTime[i - 1], ...value[i - 1]]);
  }
  return date;
}

//获取当前时间
export function getcurDate() {
  var today = new Date();
  var year = today.getFullYear();
  var month = today.getMonth() + 1;
  var date = today.getDate();

  var curDate = `${year}-${month}-${date}`
  return curDate;
}

//newAddress接口统一处理方法返回四项值的大数组
export function handelNewAddress(data) {
  let newAddress = []
  let activeAddress = []
  let receiveAddress = []
  let sendAddress = []
  let newAddressVolume = []
  let totalAddress = []
  let arr = []
  data.forEach(item => {
    newAddress.push(Number(item.newAddress.toFixed(2)))
    activeAddress.push(Number(item.activeAddress.toFixed(2)))
    receiveAddress.push(Number(item.receiveAddress.toFixed(2)))
    sendAddress.push(Number(item.sendAddress.toFixed(2)))
    newAddressVolume.push(Number(item.newAddressVolume.toFixed(2)))
    totalAddress.push(Number(item.totalAddress.toFixed(2)))

  })
  arr.push(newAddress, activeAddress, receiveAddress, sendAddress, newAddressVolume, totalAddress)
  return arr
}

//NewAddress生成二维数组
export function handelAddressData(data, value) {

  let startTime = data[0].date.split("T")[0].replace(/-/g, ",");

  let endTime = data[data.length - 1].date.split("T")[0].replace(/-/g, ",");
  let base = +new Date(startTime);

  let oneDay = 24 * 3600 * 1000;
  let totalDay = getDiffDay(startTime, endTime) + 1;
  let date = [[base, value[0]]];
  for (let i = 0; i < value.length; i++) {
    let now = new Date((base += oneDay));
    if (i - 1 == 0) {
      date.push([+now, value[i]]);
      value.splice(0, 1);
    } else {
      date.push([+now, value[i - 1]]);
    }
  }

  return date;
}


//blockAmount接口统一处理方法返回四项值的大数组
export function handelBlockAmount(data) {
  let amount = []
  let height = []
  let arr = []
  data.forEach(item => {
    amount.push(item.amount)
    height.push(item.height)

  })
  arr.push(amount, height)
  return arr
}


//BlockAmount生成二维数组
export function handelBlock(data, value) {

  let year = data[0].dateTime.split("T")[0];
  let hours = data[0].dateTime.split("T")[1].split(".")[0]
  let startTime = `${year} ${hours}`
  let endYear = data[data.length - 1].dateTime.split("T")[0];
  let endHours = data[data.length - 1].dateTime.split("T")[1].split(".")[0];
  let endTime = `${endYear} ${endHours}`
  let base = +new Date(startTime);

  let oneDay = 24 * 3600 * 1000;
  let totalDay = getDiffDay(startTime, endTime) + 1;
  let date = [[base, value[0]]];
  for (let i = 1; i < value.length; i++) {
    let now = new Date((base += oneDay));
    if (i - 1 == 0) {
      date.push([+now, value[i]]);
      value.splice(0, 1);
    } else {
      date.push([+now, value[i - 1]]);
    }
  }

  return date;
}
//时间
export function getDate(type = null, number = 0) {
  var nowdate = new Date();
  switch (type) {
    case "day": //取number天前、后的时间
      nowdate.setTime(nowdate.getTime() + 24 * 3600 * 1000 * number);
      var y = nowdate.getFullYear();
      var m =
        nowdate.getMonth() + 1 >= 10
          ? nowdate.getMonth() + 1
          : "0" + (nowdate.getMonth() + 1);
      var d =
        nowdate.getDate() >= 10
          ? nowdate.getDate()
          : "0" + nowdate.getDate();
      var retrundate = `${y}-${m}-${d}`;
      break;
    default:
      //取当前时间
      var y = nowdate.getFullYear();
      var m =
        nowdate.getMonth() + 1 >= 10
          ? nowdate.getMonth() + 1
          : "0" + (nowdate.getMonth() + 1);
      var d =
        nowdate.getDate() >= 10
          ? nowdate.getDate()
          : "0" + nowdate.getDate();
      var retrundate = `${y}-${m}-${d}`;
  }
  return retrundate;


}
//时间戳转换成时间
export function getDateTime(timer) {

  let curDate = new Date(timer);
  let Y = curDate.getFullYear();
  let M = curDate.getMonth() + 1 < 10 ? `0${curDate.getMonth() + 1}` : `${curDate.getMonth() + 1}`;
  let D = curDate.getDate() < 10 ? `0${curDate.getDate()}` : `${curDate.getDate()}`;
  let H = curDate.getHours() < 10 ? `0${curDate.getHours()}` : `${curDate.getHours()}`;
  let Min = curDate.getMinutes() < 10 ? `0${curDate.getMinutes()}` : `${curDate.getMinutes()}`;
  let S = curDate.getSeconds() < 10 ? `0${curDate.getSeconds()}` : `${curDate.getSeconds()}`;

  return `${Y}-${M}-${D} ${H}:${Min}:${S}`


}
//echats 图表折线图切换对数显示还是Linear 显示
export function handelLineType(option, type) {
  let options = JSON.parse(JSON.stringify(option))
  let oldyAxis
  if (type) {
    oldyAxis = [...type] //深拷贝一开始传入的Y轴
  }


  if (Array.isArray(options.yAxis)) {

  
    if (options.yAxis.some(item => item.type == "value")) {

      options.yAxis.forEach(i => i.type = "log")
    } else {//当Y轴都是log的时候点击按钮  进来就把Y轴换成
      options.yAxis.forEach(i => i.type = "value")
      // options.yAxis.forEach(i=> i.type ="value")
      // if (oldyAxis) {
      //   options.yAxis = oldyAxis
      // } else {
      //   options.yAxis.forEach(i => i.type = "value")
      // }



    }



  } else {
    if (options.yAxis.type == "value") {
      options.yAxis.type = "log"
    } else {
      options.yAxis.type == "value"
      // if (oldyAxis) {
      //   options.yAxis = oldyAxis
      // } else {
      //   options.yAxis.type == "value"
      // }
      options.yAxis.min=(value)=>{
        if (value.min <= 0) {
          
          return 0.0001;
        } else {
          return value.min;
        }
      }



    }
  }

  options.yAxis.forEach((item1)=>{//更改对数刻度 避免0和负数情况 线条超出页面
  
    item1.axisLabel = {
      formatter: (value) => {
        let data
        if (value >= 1000000000) {
          data = `${(value / 1000000000).toFixed(2)}B`
        } else if (value >= 1000000) {
          data = `${(value / 1000000).toFixed(2)}M`
        } else if (value >= 1000) {
          data = `${(value / 1000).toFixed(2)}K`
        } else if (value <= -1000000000) {
          data = `${(value / 1000000000).toFixed(2)}B`
        } else if (value <= -1000000) {
          data = `${(value / 1000000).toFixed(2)}M`
        } else if (value <= -1000) {
          data = `${(value / 1000).toFixed(2)}K`
        } else {
          data = value


        }


        return data
      }
    }
    //  if (item1.type == "value") {
    //     item1.min="dataMin"
    //  }else{
    //   item1.min=(value)=>{
    //     if (value.min <= 0) {
    //       return 0.0001;
    //     } else {
    //       return value.min;
    //     }
    //   }
    //  }




  })
  //根据type类型修改数据 含0的都修改
  if (options.yAxis.some(item => item.type == "log") && options.xAxis.type == "time") {
    options.series.forEach((seriesItem) => {
      seriesItem.data.forEach(itemData=>{
        if (itemData[1] == 0) {
         
          itemData[1]=0.1
        }
      })
      

    })
  }else if (options.yAxis.some(item => item.type == "value")){
   
  }

 
  return options
}


//echats  //默认判断显示对数/线性
export function handelSwitchs(data, switchs) {

  //判断子级option是不是数组 并改变默认值（线性/对数）
  if (Array.isArray(data.yAxis)) {
   
  
    if (data.yAxis.some(item => item.type == "value")) {
     
     
      switchs = "home.switch1";

    } else {

      switchs = "home.switch2";
     
    }
  } else {

    data.yAxis.axisLabel = {
      formatter: (value) => {
        let data
        if (value >= 1000000000) {
          data = `${(value / 1000000000).toFixed(2)}B`
        } else if (value >= 1000000) {
          data = `${(value / 1000000).toFixed(2)}M`
        } else if (value >= 1000) {
          data = `${(value / 1000).toFixed(2)}K`
        } else if (value <= -1000000000) {
          data = `${(value / 1000000000).toFixed(2)}B`
        } else if (value <= -1000000) {
          data = `${(value / 1000000).toFixed(2)}M`
        } else if (value <= -1000) {
          data = `${(value / 1000).toFixed(2)}K`
        } else {
          data = value


        }


        return data
      }
    }

    if (data.yAxis.type == "value") {
    
      switchs = "home.switch1";
    } else {

      switchs = "home.switch2";
    }
  }


  return switchs
}
//防抖函数
export function debounce(fn, wait) {
  let timeout = null;
  wait = wait || 600;
  return function () {
    let that = this;
    if (timeout !== null) clearTimeout(timeout);
    timeout = setTimeout(() => {
      fn.apply(that);
    }, wait);
  }
}
//点击BTC按钮请求
export async function fetchBtcPrice(radius, option, start, end, methods, that, flag, series0, visualMap) {
  let btcPrice
  var series0Data = series0
  var visualMap1 = visualMap
  if (flag) {
    //请求BTC价格
    const price = await that.$API.getBtcPrice2(radius, start, end);
  
    btcPrice = price.data.data
    if (btcPrice.length == 0) {//价格未查询到数据的情况              
      option.data.length = 0
      that.$message({
        type: 'warning',
        message: that.$t(`home.ethPrice`)
      });
      return
    } else {

      let priceValueList = []
      let newPriceData = []
      btcPrice.forEach(price => {
        priceValueList.push(Number(parseInt(price.value * 100) / 100))
        newPriceData.push(price)
      })
    
     if (option&&option.data) {
      option.data = handelBtcPrice(newPriceData, priceValueList)
     }
      

    }
  } else {
    option.data.length = 0
  }




  methods()
  return false

}
//点击ETH按钮请求
export async function fetchEthPrice(radius, option, start, end, methods, that, flag, page) {

  if (flag) {

    //请求ETH价格
    const price = await that.$API.getBtcPrice2(radius, start, end);
    let ethPrice = price.data.data
    if (ethPrice.length==0) {//价格未查询到数据的情况 
                   
      // option.data.length = 0
      that.$message({
        type: 'warning',
        message: that.$t(`home.ethPrice`)
      });
      return
    } else {

      let priceValueList = []
      let newPriceData = []
      ethPrice.forEach(price => {
        priceValueList.push(Number(price.value.toFixed(2)))
        newPriceData.push(price)
      })
     
      option.data = handelBtcPrice(newPriceData, priceValueList)

    }


  } else {
    option.data.length = 0
  }

  methods()


}
//根据日期筛选对应的数据
export function getDateArray(startDate, endDate, data) {
  var dateArray = []
  let currentDate = new Date(startDate)
  let lastDay = new Date(endDate)

  data.forEach((item, index) => {
    let time = new Date(item.time.split("T")[0])

    if (currentDate <= time && lastDay >= time) {
      dateArray.push(item)
    }
  })

  return dateArray;
}
//渲染平均线
export function handelSmaData(smaData, option, methods, start, end, zoomStart, zoomEnd) {

  let newsmaData = smaData
  if (start) {
    //根据日期渲染对应数据
    function getDateArray(startDate, endDate, data) {
      var dateArray = []
      let currentDate = new Date(startDate)
      let lastDay = new Date(endDate)

      data.forEach((item, index) => {
        let time = new Date(item.time.split("T")[0])

        if (currentDate <= time && lastDay >= time) {
          dateArray.push(item)
        }
      })

      return dateArray;
    }
    //按照日期筛选出新的数据
    newsmaData = getDateArray(start, end, smaData,)
  }


  let smaValueList = []
  newsmaData.forEach(item => {
    smaValueList.push(Number(item.value.toFixed(2)))
  })
  //生成二维数组
  function handelBtcPrice(data, value) {
    let startTime = data[0].time.split("T")[0].replace(/-/g, ",")
    let endTime = data[data.length - 1].time.split("T")[0].replace(/-/g, ",");
    let base = +new Date(startTime);
    let oneDay = 24 * 3600 * 1000;

    let totalDay = getDiffDay(startTime, endTime) + 1;
    let date = [[base, value[0]]];
    for (let i = 1; i < value.length; i++) {
      let now = new Date((base += oneDay));
      if (i - 1 == 0) {
        date.push([+now, value[i]]);
        value.splice(0, 1);
      } else {
        date.push([+now, value[i - 1]]);
      }
    }

    return date;
  }

  option.data = handelBtcPrice(newsmaData, smaValueList)




  methods()
}

//添加水印
export function handelWatermark(option, r, t) {

  option.graphic = [//添加水印
    {
      type: 'group',
      // rotation: Math.PI / 2,
      bounding: 'raw',
      right: "50%",
      top: "40%",
      // z: 10,
      // rotation: 6,
      children: [
        {
          type: 'text',
          left: 'center',
          top: 'center',

          silent: true,//不影响鼠标事件

          style: {
            fill: `rgba(0,0,0,0.1)`,
            text: `coinbus.cc`,
            font: 'bold 80px sans-serif',

          }
        }
      ]
    }

  ]
  // 高点选中的线条 
  option.series.forEach(item => {
   
    if (item.name == "Price[BTC]") {
      item.itemStyle.color = "#000"
      item.lineStyle.color = "#000"
      item.markLine={}
      item.yAxisIndex=1
    }else if(item.name== "Price [ETH]"){
      item.yAxisIndex=1
      item.markLine={}
    }
    item.emphasis = {
      focus: 'series',
      blurScope: 'coordinateSystem'

    }
    item.smooth = false
    //圆点大小及样式
    if (item.type == "line") {
      item.symbolSize = 10
      item.itemStyle.borderColor = "rgba(0,0,0,0.1)"
    }

    //加粗线条宽度
    if (item.lineStyle) {
      if (Number(item.lineStyle.width)) {//判断有线条的才加粗

        item.lineStyle.width = "2"
      }
    }

   
   


  })
  if (Array.isArray(option.yAxis)) { //判断Y轴是数组的情况下 每个Y轴加上单位
    option.yAxis.forEach((item,index) => {
      //统一处理 Y轴的0、1项显示其他隐藏
      if (index==0) {
        // item.show = true //统一处理 Y轴的0、1项显示其他隐藏
        item.position="left"
      }else if(index==1){
        // item.show = true //统一处理 Y轴的0、1项显示其他隐藏
        item.position="right"
      }else{
        // item.show = false //统一处理 Y轴的0、1项显示其他隐藏
      }
      item.axisLabel = {
        formatter: (value) => {
          let data
          if (value >= 1000000000) {
            data = `${(value / 1000000000).toFixed(2)}B`
          } else if (value >= 1000000) {
            data = `${(value / 1000000).toFixed(2)}M`
          } else if (value >= 1000) {
            data = `${(value / 1000).toFixed(2)}K`
          } else if (value <= -1000000000) {
            data = `${(value / 1000000000).toFixed(2)}B`
          } else if (value <= -1000000) {
            data = `${(value / 1000000).toFixed(2)}M`
          } else if (value <= -1000) {
            data = `${(value / 1000).toFixed(2)}K`
          } else {
            data = value


          }


          return data
        }
      }
    })
  } else {
    option.yAxis.axisLabel = {
      formatter: (value) => {
        let data
        if (value >= 1000000000) {
          data = `${(value / 1000000000).toFixed(2)}B`
        } else if (value >= 1000000) {
          data = `${(value / 1000000).toFixed(2)}M`
        } else if (value >= 1000) {
          data = `${(value / 1000).toFixed(2)}K`
        } else if (value <= -1000000000) {
          data = `${(value / 1000000000).toFixed(2)}B`
        } else if (value <= -1000000) {
          data = `${(value / 1000000).toFixed(2)}M`
        } else if (value <= -1000) {
          data = `${(value / 1000).toFixed(2)}K`
        } else {
          data = value


        }


        return data
      }
    }
  }
  // 鼠标移动添加十字线
  option.tooltip.axisPointer = {

    label: {
      show: false,
      // precision: 0, //坐标轴保留的位数
    },


    type: "cross",

    // crossStyle: {
    //     //十字轴横线
    //     // opacity: "0",
    //     width: 1,
    // },
    // lineStyle: { //十字准星的竖线
    //     opacity: 0,
    // },
  }
  //限制初始滚动范围 只对折线图 数据量较大
  if (Array.isArray(option.dataZoom) && option.series[0].type == "line") {
   
    option.dataZoom[0].start = 80
    option.dataZoom[0].end = 100
  }
 
  // 限制滚动范围
  if (Array.isArray(option.xAxis)) {//判断是否多个X轴
    option.xAxis.forEach(item => {
      if (!option.dataZoom) return

      if (item.type == "time") {//最小滚动到7天就不能继续放大

        option.dataZoom[0].minValueSpan = 3600 * 24 * 1000 * 7
      } else {
        option.dataZoom[0].minValueSpan = 6
      }
    })
  } else {//单个X轴 类型判断

    if (!option.dataZoom) return
   
    if (option.xAxis.type == "time") {
      option.dataZoom[0].minValueSpan = 3600 * 24 * 1000 * 7
    } else {
      option.dataZoom[0].minValueSpan = 6
    }
  }

  //所有页面legend 默认只显示前1条数据和价格线对比
 
  // let legendObj = {}
  // if (option.series.length > 2 ) {
  //   for (let i = 0; i < option.series.length; i++) {
  //     if (i > 0 && (option.series[i].name !== `Price[BTC]` && option.series[i].name !== `Price [ETH]`)&&option.series[i].type !== `bar`) {
  //       legendObj[option.series[i].name] = false
  //     }
  //   }
  // }
  // if (option.legend) {
  //   option.legend.selected = legendObj
  // }
  // 滚动条文字处理
  if (option.xAxis.type == "time"  && option.dataZoom[1]) { 
   
    option.dataZoom[1].labelFormatter = (time)=>{
    
      const date = new Date(time);
      
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      let newTime =  `${year}-${month}-${day}`;
      return newTime
    }
  }else if(option.dataZoom){
 
    
    option.dataZoom[1].labelFormatter={}
  }
  
  
  return option
}

//监听localstorage
export const $addStorageEvent = function (type, key, data) {
  // localStorage
  if (type === 1) {
    // 创建一个StorageEvent事件
    var newStorageEvent = document.createEvent('StorageEvent');
    const storage = {
      setItem: function (k, val) {
        localStorage.setItem(k, val);
        // 初始化创建的事件
        newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);
        // 派发对象
        window.dispatchEvent(newStorageEvent);
      }
    }
    return storage.setItem(key, data);
  } else {
    // sessionStorage
    // 创建一个StorageEvent事件
    var newStorageEvent = document.createEvent('StorageEvent');
    const storage = {
      setItem: function (k, val) {
        sessionStorage.setItem(k, val);
        // 初始化创建的事件
        newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);
        // 派发对象
        window.dispatchEvent(newStorageEvent);
      }
    }
    return storage.setItem(key, data);
  }
}


//记录滚动位置
export function handelZoom(myChart, option, that, start, end) {
  if (!myChart) {
    return
  }

  if (Number(start) && Array.isArray(option.dataZoom)) {

    option.dataZoom[0].start = start
    option.dataZoom[0].end = end
  } else if (Number(start) && !Array.isArray(option.dataZoom)) {
    option.dataZoom.start = start
    option.dataZoom.end = end
  }



  myChart.on("dataZoom", (e) => {

    // start = e.start || e.end || e.batch[0].end;
    // end = e.batch[0].end;
   
    if (!e || (!e.start && !e.batch?.[0]?.start)) {
      return;
  }

    start = e.start || e.batch[0].start;
      end = e.end || e.batch[0].end;
      // localStorage.setItem( "zoomStart", e.start || e.end || e.batch[0].end)
      // localStorage.setItem( "zoomEnd",  e.batch[0].end)
      that.$addStorageEvent(1, "zoomStart", start);
      that.$addStorageEvent(1, "zoomEnd", end);
   



  });
  return option


}
/**
 * @desc 防抖函数
 * @param {()=>void} fn 接收一个需要防抖的函数
 * @param {number} delay 延迟时间，单位 ms。默认为 0。 可选参数，表示重复执行的时间间隔，
 * @returns {()=>void} 返回一个实际执的函数
 */

export function Debounce(fn, delay) {
  let timer = null;
  return function () {
    let context = this;
    let args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
}
import * as echarts from "echarts";
import elementResizeDetectorMaker from "element-resize-detector";
//echarts 图表根据页面宽度适应
export function chartsWidth(id, that) {

  //   let erd = elementResizeDetectorMaker();//监听元素大小变化
  //   var chartContainer = document.getElementById(id);


  //   // 定义节流函数
  //   function throttle(fn, delay) {
  //     var timer = null;
  //     return function () {
  //       if (!timer) {
  //         timer = setTimeout(function () {
  //           fn.apply(this, arguments);
  //           timer = null;
  //         }, delay);
  //       }
  //     };
  //   }

  //    // 注册回调函数，并进行节流处理
  // erd.listenTo(chartContainer, throttle(function(element){

  //   let dom = echarts.init(chartContainer).resize();
  //   if (dom) {
  //     dom.clear()
  //   }

  // }, 200)); // 设置节流延迟时间为 100 毫秒
  // --------------------------

  const chartContainer = document.getElementById(id);
  const resizeObserver = new ResizeObserver(entries => {
    for (let entry of entries) {
      if (entry.target === chartContainer) {
        // 元素大小发生变化时，重新调整 echarts 大小
        setTimeout(() => {
          const chart = echarts.getInstanceByDom(chartContainer);
          if (chart) {
            chart.resize();
          }
         
          // resizeChart();
        },0)
       
      }
    }
  });
  if (chartContainer) {
    resizeObserver.observe(chartContainer);
  }
 

  // 调整 echarts 大小的方法
  function resizeChart() {
    const chart = echarts.getInstanceByDom(document.getElementById(id));
    if (chart) {
     
      chart.resize();
    }
  }




}

//对数线性切换含有0的数据替换成0.1
export function logyAxis(data) {
  let newData = []
  data.forEach(item => {
    if (item == 0) {
      item = 0.1

    } else {
      item = item
    }
    newData.push(item)
  })

  return newData

}

//空数据处理
export function emptyData(data, series, inCharts, that) {

  if (data && data.length === 0) {//空数据处理

    that.$message({
      message: that.$t(`home.NoData`),
      type: 'warning'
    });


    if (Array.isArray(series)) {
      series.forEach(item => {
        item.data = []
      })
    } else {
      series.data = []
    }

    inCharts()


    return true
  }else if (!data) {
    if (Array.isArray(series)) {
      series.forEach(item => {
        item.data = []
      })
    } else {
      series.data = []
    }

    inCharts()
    return true
  }



}


//数据条数是否一致
export function dataLength(option, num, inCharts, that) {

      let length =num
      let flag =false
     for (let i = 0; i < option.series.length; i++) {
          if (option.series[i].data.length == 0 ) {
          
            flag=false
          
          }else if (option.series[i].data.length !=length) {
            flag=true
          }
      
     }
     if (num== 0) {
        flag =false
      
     }

   
    
     return flag


}









