import Qs from "qs";
import axios from "axios";
import C from "./c.js";
import utils from "./utils.js";
import apis from "./api.js";
import CryptoJS from "crypto-js";
const CryptoJSKey = CryptoJS.enc.Utf8.parse("1234123412ABCDEF"); //十六位十六进制数作为密钥
const CryptoJSiv = CryptoJS.enc.Utf8.parse("ABCDEF1234123412"); //十六位十六进制数作为密钥偏移量
const net = {
  commonParams: () => {
    let systemInfo = {};
    if (window) {
      systemInfo = window.navigator || {};
    }
    let params = {
      language: "cn", // 语言参数
      deviceType: "h5", // 接口调用来源参数
      deviceId: systemInfo.appCodeName + " " + systemInfo.appName, // 设备唯一标识码
      apiVersion: "1.0.0", // api版本号
      systemVersion: systemInfo.appVersion // 操作系统及版本号
    };
    let loginUserInfo = utils.getLoginUserInfo();
    if (loginUserInfo) {
      loginUserInfo = JSON.parse(decodeURIComponent(loginUserInfo));
      let token = loginUserInfo.token;
      if (token) {
        params.userToken = token; // 用户登录凭证token
      }
    }
    return params;
  },
  paramsSign: (params, url) => {
    /* 参数签名 */
    let key = "2a78ed76450c3cb42320882b3e055b31";
    if (url && url.indexOf("/common/") === 0) {
      key = "b15681f74461af9642ab5356fba7962b";
    }
    let allKeys = [];
    let paramsLower = {};
    let sArr = [];
    let res = "";
    for (let k in params) {
      let kLower = k;
      allKeys.push(kLower);
      paramsLower[kLower] = params[k];
    }
    allKeys.sort();
    allKeys.forEach(v => {
      sArr.push(`${v}=${paramsLower[v]}`);
    });
    sArr.push(`key=${key}`);
    res = sArr.join("&");
    res = CryptoJS.MD5(res).toString();
    return res.toLowerCase();
  },
  req: (params, vm) => {
    if (!params) {
      return new Promise((resolve, reject) => {
        reject(new Error("请设置请求参数"));
      });
    }
    if (!params.url) {
      return new Promise((resolve, reject) => {
        reject(new Error("请设置请求url"));
      });
    }
    return new Promise((resolve, reject) => {
      params.data = Object.assign({}, net.commonParams(), params.data);
      //   params.data = params.data
      params.data.signToken = net.paramsSign(params.data, params.url);
      let loginUserInfo = utils.getLoginUserInfo();
      if (loginUserInfo) {
        loginUserInfo = JSON.parse(decodeURIComponent(loginUserInfo));
        const { token } = loginUserInfo;
        params.data.token = token;
      }
      if (!params.method) {
        params.method = "post";
      }
      let config = {
        url: params.url,
        method: params.method,
        headers: {
          // 'X-Requested-With': 'XMLHttpRequest',
          "Content-Type": "application/x-www-form-urlencoded"
        },
        responseType: params.responseType || "json",
        timeout: 30000,
        paramsSerializer: function(params) {
          return Qs.stringify(params, {
            arrayFormat: "brackets"
          });
        },
        transformRequest: [
          function(data) {
            return Qs.stringify(data, {
              arrayFormat: "brackets"
            });
          }
        ]
      };
      if (params.method.toLowerCase() === "get") {
        Object.assign(config, {
          params: Object.assign(params.data, {
            timestamp: Date.parse(new Date()) / 1000
          })
        });
      } else {
        Object.assign(config, {
          // params: {
          //   timestamp: Date.parse(new Date()) / 1000
          // },
          data: params.data
        });
      }
      axios(config)
        .then(response => {
          C.DEBUG && console.log(`${params.url}---response--->`, response);
          let { data, status } = response;
          if (parseInt(status) === 200) {
            let { code } = data;
            code = parseInt(code);
            if (parseInt(code) === 0) {
              resolve(data);
            } else if (C.CODE_NOT_LOGIN === code) {
              utils.storage.remove("loginUserInfo");
              utils.storage.remove("userToken");
              if (vm) {
                const { params } = vm.$route;
                let { fullPath } = vm.$route;
                const { lang } = params;
                if (fullPath.indexOf(`/${lang}`) === 0)
                  fullPath = fullPath.substring(lang.length + 1);
                window.location.href = `/${
                  vm.$route.params.lang
                }/login?next=${encodeURIComponent(fullPath)}`;
              }
            } else {
              reject(data);
            }
          } else {
            vm.$Dialog
              .alert({
                title: "提示",
                message: "网络错误，请联系管理员"
              })
              .then(() => {});
            reject(response);
          }
        })
        .catch(e => {
          C.DEBUG && console.log(`${params.url}---catch--->`, e);
          reject(e);
        });
      C.DEBUG && console.log(`${params.url}---params--->`, config);
    });
  },
  login: (account, password, success, fail) => {
    let params = {};
    params.url = apis.api_admin_login;
    params.data = {
      suEmail: account,
      suPwd: password,
      loginType: 1
    };
    // params.method = 'GET'
    net.req(params).then(
      data => {
        if (data) {
          let userInfo = data.data;
          if (userInfo) {
            if (userInfo.token) {
              utils.storage.save("userToken", userInfo.token);
            }
            userInfo = encodeURIComponent(JSON.stringify(userInfo));
            utils.storage.save("loginUserInfo", userInfo);
          }
        }
        success && success(data);
      },
      e => {
        fail && fail(e);
      }
    );
  },
  //解密方法
  Decrypt: word => {
    let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
    let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    let decrypt = CryptoJS.AES.decrypt(srcs, CryptoJSKey, {
      iv: CryptoJSiv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
  },
  //加密方法
  Encrypt: word => {
    let srcs = CryptoJS.enc.Utf8.parse(word);
    let encrypted = CryptoJS.AES.encrypt(srcs, CryptoJSKey, {
      iv: CryptoJSiv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.ciphertext.toString().toUpperCase();
  },
  wxShare: shareInfo => {
    let params = {};
    params.url = "http://api.hoolihome.com/index/get-wechat-config";
    params.data = {
      url: window.location.href
    };
    net.req(params).then(res => {
      Object.assign(shareInfo, res && res.data);
      net.doWxShare(shareInfo);
    });
  },
  doWxShare: function(shareInfo) {
    let goShare = () => {
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: shareInfo.appId, // 必填，公众号的唯一标识
        timestamp: shareInfo.timestamp, // 必填，生成签名的时间戳
        nonceStr: shareInfo.nonceStr, // 必填，生成签名的随机串
        signature: shareInfo.signature, // 必填，签名，见附录1
        jsApiList: [
          "checkJsApi",
          "onMenuShareTimeline",
          "onMenuShareAppMessage",
          "onMenuShareQQ",
          "onMenuShareWeibo",
          "onMenuShareQZone"
        ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
      });
      wx.ready(function() {
        let shareObj = {
          title: shareInfo.title,
          desc: shareInfo.desc,
          link: window.location.href,
          imgUrl: shareInfo.img_url,
          trigger: function() {},
          complete: function() {},
          success: function() {},
          cancel: function() {},
          fail: function() {}
        };
        wx.onMenuShareTimeline(shareObj);
        wx.onMenuShareAppMessage(shareObj);
        wx.onMenuShareQQ(shareObj);
        wx.onMenuShareWeibo(shareObj);
        wx.onMenuShareQZone(shareObj);
      });
    };
    goShare();
  },
  doHooliShare: function(params) {
    let shareObj = {
      type: 6, // 4内部调用分享方法 6app原生分享
      data: {
        share_obj: params,
        share_tag: "1234",
        is_share: true
      }
    };
    shareObj = encodeURIComponent(JSON.stringify(shareObj));
    if (utils.checkIsHooliAndroid()) {
      window.Android.javaScriptToNative(shareObj);
    } else {
      window.webkit.messageHandlers.javaScriptToNative.postMessage(shareObj);
    }
  }
};

export default net;
