import axios from 'axios';
import { uploadBlockFile } from '@/api/common';
import dayjs from 'dayjs';
import weekday from 'dayjs/plugin/weekday';
import 'dayjs/locale/zh-cn';
// rgb/rgba 转 16进制
export const rgb2hexify = (color) => {
  const values = color
    .replace(/rgba?\(/, '')
    .replace(/\)/, '')
    .replace(/[\s+]/g, '')
    .split(',');
  const a = parseFloat(values[3] || 1);
  const r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255);
  const g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255);
  const b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255);
  return (
    '#' +
    ('0' + r.toString(16)).slice(-2) +
    ('0' + g.toString(16)).slice(-2) +
    ('0' + b.toString(16)).slice(-2)
  );
};

// 16进制转rgba
export const color2Rgb = (colorHex, opacityVal = 1) => {
  // 16进制颜色值的正则
  const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  // 把颜色值变成小写
  let color = colorHex.toLowerCase();
  if (reg.test(color)) {
    // 如果只有三位的值，需变成六位，如：#fff => #ffffff
    if (color.length === 4) {
      let colorNew = '#';
      for (let i = 1; i < 4; i += 1) {
        colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
      }
      color = colorNew;
    }
    // 处理六位的颜色值，转为RGB
    const colorChange = [];
    for (let i = 1; i < 7; i += 2) {
      colorChange.push(parseInt('0x' + color.slice(i, i + 2)));
    }
    return 'rgba(' + colorChange.join(',') + ',' + opacityVal + ')';
  } else {
    return color;
  }
};

export function blob2Base64(data) {
  const blob = new Blob([data], { type: 'image/jpg' });

  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
  });
}

export function getStaticMapImg(paths, color = '0000ff', zoom = 13) {
  const fillColor = '0x' + (color.startsWith('#') ? color.slice(1) : color);
  let linePath = paths.reduce((pre, pathItem) => {
    return pre + pathItem[0] + ',' + pathItem[1] + ';';
  }, '3,' + fillColor + `,1,${fillColor},0.5:`);

  linePath += paths[0][0] + ',' + paths[0][1];
  // + color + ',1,,:'

  return axios({
    method: 'GET',
    url: 'https://restapi.amap.com/v3/staticmap',
    params: {
      zoom: Math.floor(zoom) - 1,
      size: '500*500',
      key: 'c1cde6636ea1812f213f97368bfb3ef7',
      paths: linePath
      // paths:
      //   '10,0x0000ff,1,,:116.31604,39.96491;116.320816,39.966606;116.321785,39.966827;116.32361,39.966957'
    },
    responseType: 'blob'
  }).then((res) => {
    if (!res.data || !(res.data instanceof Blob)) {
      return Promise.reject(new Error('生成数据出错'));
    }

    const formData = new FormData();
    formData.append('file', res.data);

    // return blob2Base64(res.data).then((response) => {
    //   console.log(response, '--------------- blob base64');
    //   return response;
    // });
    return uploadBlockFile(formData).then((response) => {
      const { resUrl, resId } = response.data || {};
      return {
        url: resUrl,
        resId: resId
      };
    });
  });
}

export function rangeDate(
  type = 'start',
  range = 'date',
  format = 'YYYY-MM-DD HH:mm:ss'
) {
  let result = '';
  if (type === 'start') {
    result = dayjs()
      .startOf(range)
      .set('hour', type === 'start' ? 0 : 23)
      .set('minute', type === 'start' ? 0 : 59)
      .set('second', type === 'start' ? 0 : 59)
      .format(format);
  } else {
    result = dayjs()
      .endOf(range)
      .set('hour', type === 'start' ? 0 : 23)
      .set('minute', type === 'start' ? 0 : 59)
      .set('second', type === 'start' ? 0 : 59)
      .format(format);
  }
  return result;
}

export function evil(fn) {
  var Fn = Function;

  return new Fn('return ' + fn)();
}

export function formateDate(date, pattern = 'YYYY-MM-DD') {
  if (!date) {
    return '-';
  }

  return dayjs(date).format(pattern);
}

export function formateNum(num) {
  const reg = /\B(?=(\d{3})+$)/g;

  return String(num).replace(reg, ',');
}
