import { encryption } from '@/service/encrypt';
import store from '@/store';
import { smEvent } from '@/api/user.api';
import { uploadSMIDToKdsp } from '@/api/user.api';
import { sStorage } from '@/service/sessionStorage.service';

window.SMSdk;
window._smReadyFuncs = [];
const APP_ID =
  process.env === 'production' && (!process.env.QG_ENV || process.env.QG_ENV !== 'test')
    ? 'YXM'
    : 'YXM_TEST';
console.log(APP_ID);

export function shuMeiInit() {
  window._smConf = {
    organization: 'YGXboTJhF42EIELHANew',
    appId: APP_ID,
    publicKey:
      'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6Zl01PHYV2rG/WyfiBfhLDAfm2i1Wx1eiw9lkHiYNnD27c9rdy8OWZ/6DR7xmn7gDT4zyeDteBMVH226E/4gstNEOpt2ld3eOCLto+cdYYB8W0LtSE6mFHSFJk4YYxIGtTOoj/hEUWG9vwDFP6pli/c6iIVS+JZD5zyViFAzQXwIDAQAB'
  };
  (function() {
    window.SMSdk = {
      onBoxDataReady: function() {
        // console.log('sm box id =', boxData);
      },
      ready: function(fn) {
        fn && window._smReadyFuncs.push(fn);
      }
    };
  })();

  const url = 'https://misc.lkbang.net/common/shumei/fp.min.js';
  const sm = document.createElement('script');
  const s = document.getElementsByTagName('script')[0];
  sm.src = url;
  s.parentNode.insertBefore(sm, s);
}

export async function getSmDeviceId() {
  return new Promise(resolve => {
    let smDeviceId = '';
    let smDeviceIdReady = false;

    window.SMSdk.ready(async function() {
      if (window.SMSdk.getDeviceId) {
        smDeviceId = window.SMSdk.getDeviceId();
      }
      if (!smDeviceIdReady) {
        smDeviceIdReady = true;
      }
      store.commit('SET_SM_DEVICEID', smDeviceId);
      // 执行业务逻辑
      const [shumeiKey] = await uploadSMIDToKdsp({
        shumeiDeviceId: smDeviceId
      });
      if (shumeiKey) sStorage.setItem('shumeiKey', shumeiKey);
      resolve(shumeiKey);
    });
  });
}

export function dealSmDeviceId() {
  return new Promise(resolve => {
    let smDeviceId = '';
    let smDeviceIdReady = false;

    window.SMSdk.ready(function() {
      if (window.SMSdk.getDeviceId) {
        smDeviceId = window.SMSdk.getDeviceId();
      }
      if (!smDeviceIdReady) {
        smDeviceIdReady = true;
        // 执行业务逻辑
        resolve(smDeviceId);
      }
    });
  });
}

// 上报数美
export function smTrackEvent(data) {
  // data.appId = 'YXM_H5';
  let smDeviceId = '';
  let smDeviceIdReady = false;
  window.SMSdk.ready(async function() {
    if (window.SMSdk.getDeviceId) {
      smDeviceId = window.SMSdk.getDeviceId();
    }
    if (!smDeviceIdReady) {
      smDeviceIdReady = true;
    }
    if (!data || !smDeviceId) return false;
    data.shumeiDeviceId = smDeviceId;
    await smEvent(encryption(data));
    return true;
  });
}
