import CryptoJS from "crypto-js";

/**
 * @brief 提示框
 * @param  zconfirm('是否清除数据', (result: boolean) => {if (result) { 确认 } else { 取消 } })
 * @return
 */
export const zconfirm = (msg: string, callBackFun?: any, title?: string) => {
  uni.showModal({
    title,
    content: msg,
    success(res) {
      if (res.confirm) {
        callBackFun(true);
      } else if (res.cancel) {
        callBackFun(false);
      }
    },
  });
};

export const zalert = (msg: string, callBackFun?: any) => {
  uni.showModal({
    title: "提示",
    content: msg,
    showCancel: false,
    success() {
      if (callBackFun) {
        callBackFun();
      }
    },
  });
};

export const toast = (msg: string) => {
  uni.showToast({
    title: msg,
    duration: 2000,
    mask: false,
    icon: "none",
  });
};

export const sLoading = (msg: string = "加载中...") => {
  uni.showLoading({
    title: msg,
    mask: true,
  });
};

export const hLoading = () => {
  uni.hideLoading();
};

// 防抖
interface DebounceFunc<T extends (...args: any[]) => any> {
  (this: ThisParameterType<T>, ...args: Parameters<T>): ReturnType<T>;
}

export function debounce<T extends (...args: any[]) => any>(
  fn: T,
  delay = 300
): DebounceFunc<T> {
  let timer: number | null;
  return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.call(this, ...args);
    }, delay);
  } as DebounceFunc<T>;
}

export const jsonp = function (url: any, data: any) {
  return new Promise((resolve, reject) => {
    // 1.初始化url
    let dataString = url.indexOf("?") === -1 ? "?" : "&";
    let callbackName: any = `jsonpCB_${Date.now()}`;
    url += `${dataString}callback=${callbackName}`;
    if (data) {
      // 2.有请求参数，依次添加到url
      for (let k in data) {
        url += `&${k}=${data[k]}`;
      }
    }

    let scriptNode = document.createElement("script");
    scriptNode.src = url;
    const windows: any = window;
    // 3. callback
    windows[callbackName] = (result: any) => {
      result ? resolve(result) : reject("没有返回数据");
      delete window[callbackName];
      document.body.removeChild(scriptNode);
    };

    // 4. 异常情况
    scriptNode.addEventListener(
      "error",
      () => {
        reject("接口返回数据失败");
        delete window[callbackName];
        document.body.removeChild(scriptNode);
      },
      false
    );

    // 5. 开始请求
    document.body.appendChild(scriptNode);
  });
};

// 截取url中的code方法
export const getUrlCode = () => {
  const url = location.search;
  const theRequest: any = new Object();
  if (url.indexOf("?") != -1) {
    const str = url.substr(1);
    const strs = str.split("&");
    for (let i: any = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
    }
  }
  return theRequest;
};

export const evaluateStr = (num: number) => {
  let str = "";
  switch (num) {
    // case 0:
    case 1:
      str = "很不满意";
      break;
    case 2:
      str = "不满意";
      break;
    case 3:
      str = "一般";
      break;
    case 4:
      str = "满意";
      break;
    case 5:
      str = "很满意";
      break;
  }
  return str;
};

export const hidePhoneNumber = (phoneNumber: string) => {
  if (phoneNumber.length === 11) {
    const prefix = phoneNumber.substring(0, 3);
    const suffix = phoneNumber.substring(7);
    return prefix + "****" + suffix;
  } else {
    // 手机号码不合法，不进行隐藏处理
    return phoneNumber;
  }
};

const key = "lqkj456789A10086"; // 32位
const iv = "lqkj567890A10086"; // 16位

// 加密
export const encrypt = (text: string) => {
  return CryptoJS.AES.encrypt(text, CryptoJS.enc.Utf8.parse(key), {
    iv: CryptoJS.enc.Utf8.parse(iv),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  }).toString();
};

// 解密
export const decrypt = (text: string) => {
  let decrypted = CryptoJS.AES.decrypt(text, CryptoJS.enc.Utf8.parse(key), {
    iv: CryptoJS.enc.Utf8.parse(iv),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  return decrypted.toString(CryptoJS.enc.Utf8);
};

export const callPhone = (e: any, phone: string) => {
  if (!phone) return toast("电话号码为空");
  location.href = "tel:" + phone;
};
