import { Base64 } from 'js-base64';
// #ifdef H5
import wx from 'weixin-jsapi'
// #endif
let path = "";
let appIp = "";
let dsHost = "";
// #ifdef H5
let pathname = location.pathname.split('/')[1]; //二级目录
pathname = pathname ? '/' + pathname : '';
let protocolName = document.location.protocol; //http协议
let wsName = protocolName === 'http:' ? 'ws' : 'wss'; //ws协议
let url_temporary = '';
if(pathname === '/app'){
  url_temporary = `${location.origin}`;//无二级目录
}else{
  url_temporary = `${location.origin}${pathname}`;//二级目录
}
export const baseUrl = url_temporary;
path = `${baseUrl}/service`;
dsHost = location.hostname;
// #endif
uni.setStorageSync('path', path);

// get方法
export function get(url, data = {}) {
  url = path + url;
  return new Promise((resolve, reject) => {
    uni.request({
      url,
      data,
      header: {
        'Cache-Control': 'no-cache',
        'Ds-Host': dsHost,
      },
      success(res) {
        resolve(res.data);
      },
      fail(err) {
        uni.showToast({
          icon: 'none',
          title: '请求数据失败！'
        });
      }
    })
  });
}
// post方法
export function post(url, data = {}) {
  if(url.includes('/workerOrder/orderSign/')){
    let code = url.replace('/workerOrder/orderSign/', '');
    url = '/workerOrder/orderSign/' + Base64.encode(code);
  }
  url = path + url;
  return new Promise((resolve, reject) => {
    uni.request({
      method: 'POST',
      url,
      data,
      header: {
        'Cache-Control': 'no-cache',
        'Ds-Host': dsHost,
      },
      success(res) {
        resolve(res.data);
      },
      fail(err) {
        reject(err);
        uni.showToast({
          icon: 'none',
          title: '请求数据失败！'
        });
      }
    })
  });
}
// delete方法
export function deleteIt(url, data = {}) {
  url = path + url;
  return new Promise((resolve, reject) => {
    uni.request({
      method: 'DELETE',
      url,
      data,
      header: {
        'Cache-Control': 'no-cache',
        'Ds-Host': dsHost,
      },
      success(res) {
        resolve(res.data);
      },
      fail(err) {
        uni.showToast({
          icon: 'none',
          title: '请求数据失败！'
        });
      }
    })
  });
}
// 扫一扫
export function SM() {
  // #ifndef H5
  return new Promise((resolve, reject) => {
    uni.scanCode({
      onlyFromCamera: true,
      success: function(res) {
        let str = res.result.replace(/[\s\/]/g, '') || 'none';
        str = str.replace(/CODABAR,/i, '');
        str = str.replace(/CODE_128,/i, '');
        resolve(str);
      },
      fail(err) {
        reject(err);
      }
    });
  });
  // #endif
  // #ifdef H5
  return new Promise((resolve, reject) => {
    let param = {
      requestUrl: location.href.split('#')[0]
    };
    post("/wechat/getJsConfig", param).then(res => {
      if (res) {
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: res.appId, // 必填，企业号的唯一标识，此处填写企业号corpid
          timestamp: res.timestamp, // 必填，生成签名的时间戳
          nonceStr: res.nonceStr, // 必填，生成签名的随机串
          signature: res.signature, // 必填，签名，见附录1
          jsApiList: res.jsApiList // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        wx.ready(function() {
          wx.scanQRCode({
            desc: "scanQRCode desc",
            needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
            scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
            success: function(res) {
              // 当needResult 为 1 时，扫码返回的结果
              let str = res.resultStr.replace(/[\s\/]/g, '') || 'none';
              str = str.replace(/CODABAR,/i, '');
              str = str.replace(/CODE_128,/i, '');
              resolve(str);
            },
            cancel(err){
              reject(err);
            }
          });
        });
      }
    })
  });
  // #endif
}
// 修改接口域名
export function changeIP(ip) {
  console.log(ip)
  path = `${ip}/service`;
  appIp = ip;
	uni.setStorageSync('ip', ip);
  uni.setStorageSync('path', path);
}
// 建立websocket
export function webHandle(cate, type, ipe) {
  // uni.closeSocket();
  // 屏蔽语音播报
  if (cate !== 'no') {
    uni.navigateTo({
      url: `../${cate}/${cate}`
    })
  }
  return;
  // 屏蔽语音播报
  if (getApp().$ws) {
    return;
  }
  console.log(getApp().$ws)
  let clientid, ip, wws;
  if (type === 'app') {
    clientid = uni.getStorageSync('clientid'); //获取cid
    ipe = ipe || appIp;
    ip = ipe.split(':')[1]; //过滤掉端口
    wws = ipe.split(':')[0] == 'http' ? 'ws' : 'wss';
  } else if (type === 'wx') {
    ip = document.domain; //过滤掉端口
    // ip = '192.168.3.108'; //过滤掉端口
    console.log(ip)
    wws = wsName;
  }
  console.log(getApp())
  getApp().$ws = uni.connectSocket({
    url: `${wws}://${ip}:8080/webSocket/message/app`,
    header: {
      'content-type': 'application/json'
    },
    success(result) {
      console.log(result);
      // 监听WebSocket连接打开事件
      uni.onSocketOpen(res1 => {
        console.log(res1, 'websocket连接成功');
        // 通过 WebSocket 连接发送数据
        let obj = {};
        if (type === 'app') {
          obj = {
            userCount: uni.getStorageSync('userData').user.id,
            clientId: clientid
          };
        } else if (type === 'wx') {
          obj = {
            userCount: uni.getStorageSync('userData').user.id
          };
        }
        console.log(JSON.stringify(obj))
        uni.sendSocketMessage({
          data: JSON.stringify(obj),
          success(res2) {
            console.log(res2)
          }
        });
        // 监听WebSocket接受到服务器的消息事件
        uni.onSocketMessage(res3 => {
          console.log('收到服务器内容：' + res3.data);
          // 连接成功后跳转到待接单列表baba
          if (res3.data !== 'X') {
            let objData = JSON.parse(res3.data);
            if (objData.status == 200) {
              if (cate !== 'no') {
                uni.navigateTo({
                  url: `../${cate}/${cate}`
                })
              }
            } else {
              // 播报 start
              let msg = objData.content;
              msg = msg.replace(/【[0-9]*】/g, function(word) {
                return word.substring(0, 2) + ' ' + word.substring(2);
              });
              console.log(getApp().audios)
              getApp().audios = getApp().audios || [];
              getApp().audios.push(msg);
              if (getApp().audios.length === 1) {
                startAudio();
              }
              // 播报 end
            }
          }
        });
      });
      uni.onSocketClose(function() {
        console.log('WebSocket 已关闭！');
      });
    }
  })
}
// 语音播放
function startAudio() {
  let arr = getApp().audios;
  console.log(arr);
  if (arr.length === 0) {
    return;
  } else {
    const innerAudioContext = uni.createInnerAudioContext();
    innerAudioContext.autoplay = true;
    innerAudioContext.src = 'http://fanyi.baidu.com/gettts?lan=zh&text=' + arr[0] +
      '&spd=5&source=web';
    innerAudioContext.onEnded(() => {
      arr.shift();
      startAudio();
    })
  }







  // innerAudioContext.src = 'http://192.168.3.108/tts1.mp3';
  // uni.request({
  //     url: 'http://fanyi.baidu.com/gettts?lan=zh&text=这是一个测试&spd=5&source=web',
  //     success: (res) => {
  //         console.log(res.data);
  //     }
  // });
}

/**
 * 上传附件
 */
export function api_uploadAttachment(type, id){
  return `${path}/common/common/uploadAttachment/${type}/${id}/${id}`
}
