import common from './common.js'
let ajaxUrl = common.store().baseUrl;
let data = {
  wyyxajaxUrl: ajaxUrl,
  wyyxGet ($url = '', $parmas = {}, callback = () => { }, failback = () => { }) {
    let that = this,
      params = {};
    let promise = new Promise((resolve, reject) => {
      params = $parmas;
      resolve();
    });
    promise.then(() => {
      that.wyyxpostData($url, params, callback, failback, 'GET');
    }).catch();
  },
  wyyxPost ($url = '', $parmas = {}, callback = () => { }, failback = () => { }) {
    let that = this,
      params = {};
    let promise = new Promise((resolve, reject) => {
      params = $parmas;
      resolve();
    });
    promise.then(() => {
      that.wyyxpostData($url, params, callback, failback, 'POST');
    }).catch();
  },
  wyyxPut ($url = '', $parmas = {}, callback = () => { }, failback = () => { }) {
    let that = this,
      params = {};
    let promise = new Promise((resolve, reject) => {
      params = $parmas;
      resolve();
    });
    promise.then(() => {
      that.wyyxpostData($url, params, callback, failback, 'PUT');
    }).catch();
  },

  wyyxsetPublicParams () {
    let that = this,
      params = {},
      appName = '';
    let uuid_new = "";
    // #ifdef APP-PLUS
    // let mainActivity = plus.android.runtimeMainActivity();
    // let Settings = plus.android.importClass("android.provider.Settings");
    if (uni.getSystemInfoSync().osName == "android") {
      uuid_new = "from_android_applyAssistantUniapp"
    } else {
      uuid_new = "from_ios_applyAssistantUniapp"
    }
    // let uuid = Settings.Secure.getString(mainActivity.getContentResolver(),Settings.Secure.ANDROID_ID);
    // #endif

    // #ifdef MP-WEIXIN
    appName = uni.getStorageSync('miniApp-info').fullName || uni.getStorageSync('miniApp-info').agencyName  || '伯才供应链';

    // #endif


    params = {
			'requestComeFrom':'dandelion_platform_miniapp',
      // #ifdef APP-PLUS
      'g-open-env': 'APP-PLUS',
    	'g_open_env': 'APP-PLUS',
      appId: uuid_new,
      // 请求来源标识 1.小程序 2.app 3.网页
      appClassify: 2,
      appName: encodeURIComponent(appName)
      // #endif
      // #ifdef H5
      'g-open-env': 'H5',
    	'g_open_env': 'H5',
      appId: '',
      appClassify: 3,
      appName: encodeURIComponent(appName)
      // #endif
      // #ifdef MP-WEIXIN
      'g-open-env': 'MP-MINI',
    	'g_open_env': 'MP-MINI',
      appId: uni.getAccountInfoSync().miniProgram.appId,
      appClassify: 1,
      appName: encodeURIComponent(appName)
      // #endif
      // #ifdef MP-TOUTIAO
      'g-open-env': 'MP-TOUTIAO',
    	'g_open_env': 'MP-TOUTIAO',
      appId: tt.getEnvInfoSync().microapp.appId,
      subAppId: uni.getStorageSync('subAppId'),
      appClassify: 1,
      appName: encodeURIComponent(appName)
      // #endif
      // #ifdef MP-KUAISHOU
      'g-open-env': 'MP-KUAISHOU',
    	'g_open_env': 'MP-KUAISHOU',
      appId: "",
      appClassify: 1,
      appName: encodeURIComponent(appName)
      // #endif
    }
    return params
  },
  // 发送请求
  wyyxpostData ($url = '', $parmas = {}, callback = () => { }, failback = () => { }, $method) {
    let that = this,
      $header = {};
    // #ifdef MP-WEIXIN
    // 设置往服务器传的代理id
    uni.setStorageSync("AGENCY_ID", uni.getStorageSync('miniApp-info').id);
    // #endif
    if (uni.getStorageSync("apply-token")) {
      $header.Authorization = 'Bearer ' + uni.getStorageSync("apply-token");
      // 是否是该小程序对应代理的成员判断
      // if (uni.getStorageSync("AGENCY_ID") == uni.getStorageSync("apply-userinfo").user.agencyId) {
      //   uni.setStorageSync("IS_MINIAPP_MEMBER", true);
      // } else {
      //   uni.setStorageSync("IS_MINIAPP_MEMBER", false);
      // }

    }
    $header.inviteUserId = ''
    if (uni.getStorageSync("AGENCY_USER_ID")) {
      // $header.inviteUserId = uni.getStorageSync("AGENCY_USER_ID");
    }
    if ($parmas == '') {
      $parmas = {};
    }
    if (uni.getStorageSync("apply-agencyId")) {
      $header.AgencyId4A = uni.getStorageSync("apply-agencyId");
      // $parmas.agencyId = uni.getStorageSync("AGENCY_ID")
    }
    $header['content-type'] = 'application/json';
    // if ($parmas.formdata || $method == "POST" || $method == "PUT") {
    //   $header['content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    // }
    // console.log("公共参数，+++++", Object.assign($parmas, that.wyyxsetPublicParams()));
    // 检查网络信息, 避免网络引起的错误码
    uni.getNetworkType({
      success: function (res) {
        // console.log(res);
        if (res.networkType != 'none') {
          uni.request({
            url: $url.indexOf('https') > -1 ? $url : ajaxUrl + $url, // 加入http判断，如果传入的是整段的地址, 则不进行拼接
            data: Object.assign($parmas, that.wyyxsetPublicParams()),
            header: Object.assign($header, that.wyyxsetPublicParams()),
            method: $method,
            success: (res) => {
              // console.log('测试报错123123123123123123', res + '\n' + $url);
              // console.log('测试报错123123123123123123$url',$url);
              let resData = res.data;
              if (resData.status == 200) {// 正常
                callback(resData.data, resData.msg);
              } else if ($url.indexOf('matrix') > -1) { // 调用第三方地图接口的时候
                if (resData.status == 0) {
                  callback(resData);
                } else {
                  uni.showToast({
                    title: resData.message,
                    icon: "none"
                  });
                }
              } else if (resData.status == 9999) {// 登录过期或者身份变动等需要登录的场景
                uni.showToast({
                  title: resData.msg,
                  icon: "none"
                });
                setTimeout(() => {
                  uni.reLaunch({
                    url: '/root/login/index?path=' + that.wyyxgetPathCopy().path + '&level=' + that.wyyxgetPathCopy().level
                  }); 
                }, 1500);
              } else if (resData.status == 500 || resData.status == 502) {// 某种原因导致接口提示该状态码
                // if (resData.msg == '系统异常，请稍后') {
                //   uni.reLaunch({
                //     url: '/root/other/error'
                //   });
                // } else {
                uni.showToast({
                  title: resData.msg,
                  icon: "none"
                });
                failback(resData.msg);
                // }
              } else if (resData.status == 2002) {
                uni.showToast({
                  title: resData.msg,
                  icon: "none"
                });
                setTimeout(() => {
                  uni.reLaunch({
                    url: '/root/login/index?path=' + that.wyyxgetPathCopy().path + '&level=' + that.wyyxgetPathCopy().level
                  });
                }, 1500);
              } else {// 其他异常
                if (resData.status != 9998) {
                  uni.showToast({
                    title: resData.msg,
                    icon: "none"
                  });
                }
                failback(resData.msg);
              }
            },
            fail (error) {
              uni.showToast({
                title: error.errMsg,
                icon: "none"
              })
              failback(error);
            }
          });
        } else {
          uni.showToast({
            title: '网络异常，请检查网络',
            icon: "none"
          })
        }
      },
    });

  },

  /* 获取当前path
   */
  wyyxgetPathCopy () {
    const pages = getCurrentPages();
    if (pages.length > 0) {
      let _path = pages[pages.length - 1].route;
      return {
        path: _path,
        level: _path.slice(0, 4)
      }
    } else {
      return {
        path: '',
        level: ''
      };
    }
  },
};

export default data;