import { Service } from '@zenview/micro-basic-library';
import { BaseStore } from '@zenview/micro-basic-library';
import { cache } from "@zenview/micro-utils";
import lamejs from 'lamejs'
import moment from 'moment'
export async function queryThemeConfig (mode) {
  if (mode === 'local') {
    return Service.$http({ url: `/micro-apps/micro-dep-librarys/config/themeConfig.json?${Date.now()}`, requestId: 'themeConfig' });
  }
  const res1 = await Service.$http({ url: '/api/micro/configure/v1/queryConfigureIsDefaultByType/1', requestId: 'themeConfig' }).catch(() => false);
  if (res1 && res1.data && res1.data.info) {
    return res1.data.info;
  }
  return Service.$http({ url: `/micro-apps/micro-dep-librarys/config/themeConfig.json?${Date.now()}`, requestId: 'themeConfig' });
}

function getHeaders () {
  return {
    Authorization: cache.getCache("token", "session")
  }
}

function getKvStore (data) {
  return Service.$http({
    method: "post",
    url: '/api/user/userKvStore/v1/getKvStore',
    headers: getHeaders(),
    data
  })
    .then(res => {
      if (res.data.storeValue) {
        try {
          res.data.json = JSON.parse(res.data.storeValue);
        } catch (e) {
          console.error(e);
        }
      }
      return res;
    })
    .catch(e => {
      return Promise.reject(e);
    });
}

function setUserKvStore (data) {
  data.storeValue = JSON.stringify(data.storeValue);
  return Service.$http({
    url: '/api/user/userKvStore/v1/setUserKvStore',
    method: "POST",
    headers: getHeaders(),
    data
  })
    .then(res => {
      return res;
    })
    .catch(e => {
      return Promise.reject(e);
    });
}

export const getVideoHistoryTimes = async () => {
  try {
    const res = await getKvStore({ userId: BaseStore.app.userInfo.id, storeKey: 'VIDEO_HISTORY_TIME' })
    if (res.data.storeValue) {
      const videoHistoryTime = JSON.parse(res.data.storeValue)
      return Promise.resolve([moment(videoHistoryTime[0]), moment(videoHistoryTime[1])])
    } else {
      return Promise.reject('无缓存数据')
    }
  } catch (error) {
    return Promise.reject(error)
  }
}

export const setVideoHistoryTimes = ([startTime, endTime]) => {
  const options = {
    userId: BaseStore.app.userInfo.id,
    storeKey: 'VIDEO_HISTORY_TIME',
    storeValue: [startTime, endTime]
  }
  return setUserKvStore(options)
}

 export const convertToMp3 = (wavDataView,recorder) => {
  // 获取wav头信息
  const wav = lamejs.WavHeader.readHeader(wavDataView); // 此处其实可以不用去读wav头信息，毕竟有对应的config配置
  const { channels, sampleRate } = wav;
  const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128);
  // 获取左右通道数据
  const result = recorder.getChannelData()
  const buffer = [];

  const leftData = result.left && new Int16Array(result.left.buffer, 0, result.left.byteLength / 2);
  const rightData = result.right && new Int16Array(result.right.buffer, 0, result.right.byteLength / 2);
  const remaining = leftData.length + (rightData ? rightData.length : 0);

  const maxSamples = 1152;
  for (let i = 0; i < remaining; i += maxSamples) {
    const left = leftData.subarray(i, i + maxSamples);
    let right = null;
    let mp3buf = null;

    if (channels === 2) {
      right = rightData.subarray(i, i + maxSamples);
      mp3buf = mp3enc.encodeBuffer(left, right);
    } else {
      mp3buf = mp3enc.encodeBuffer(left);
    }

    if (mp3buf.length > 0) {
      buffer.push(mp3buf);
    }
  }

  const enc = mp3enc.flush();

  if (enc.length > 0) {
    buffer.push(enc);
  }
  return new Blob(buffer, { type: 'audio/mp3' });
}