// 东八区时间差
let _timezone = 8; //目标时区时间，东八区   东时区正数 西时区负数
let _offset_GMT = new Date().getTimezoneOffset(); // 本地时间和格林威治的时间差，单位为分钟
let diffTime = _offset_GMT * 60 * 1000 + _timezone * 60 * 60 * 1000; //0
export const weekDay = [
  {
    label: "周一",
    alias: "星期一",
    value: 1
  },
  {
    label: "周二",
    alias: "星期二",
    value: 2
  },
  {
    label: "周三",
    alias: "星期三",
    value: 3
  },
  {
    label: "周四",
    alias: "星期四",
    value: 4
  },
  {
    label: "周五",
    alias: "星期五",
    value: 5
  },
  {
    label: "周六",
    alias: "星期六",
    value: 6
  },
  {
    label: "周日",
    alias: "星期日",
    value: 0
  }
];
export const getWeekNameFromVal = (index) => {
  const week = weekDay.map((v) => v.label);
  return week[index - 1 < 0 ? 6 : index - 1];
};
export const getWeekDateName = (date, useAlias = false) => {
  const week = weekDay.map((v) => {
    return useAlias ? v.alias : v.label;
  });
  const index = new Date(date).getDay();
  return week[index - 1 < 0 ? 6 : index - 1];
};
export const toChinesNum = (num) => {
  let changeNum = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
  let unit = ["", "十", "百", "千", "万"];
  num = parseInt(num);
  let getWan = (temp) => {
    let strArr = temp.toString().split("").reverse();
    let newNum = "";
    for (var i = 0; i < strArr.length; i++) {
      newNum =
        (i == 0 && strArr[i] == 0
          ? ""
          : i > 0 && strArr[i] == 0 && strArr[i - 1] == 0
          ? ""
          : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i])) +
        newNum;
    }
    return newNum;
  };
  let overWan = Math.floor(num / 10000);
  let noWan = num % 10000;
  if (noWan.toString().length < 4) {
    noWan = "0" + noWan;
  }
  return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
};
// 保留小数(四舍五入)
export const fomatFloat = (src, pos) => {
  return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos);
};
export const setStringToDate = (timeStr) => {
  // IE不能识别字符串日期
  let splitArray = timeStr.split(" ");
  let dateArray = splitArray[0].split("-");
  let d = new Date();
  d.setFullYear(dateArray[0], dateArray[1] - 1, dateArray[2]);
  d.setHours(0);
  d.setMinutes(0);
  d.setSeconds(0);
  return d;
};
//  获取当前时间
export const getNow = () => {
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  if (month < 10) {
    month = "0" + month;
  }
  if (day < 10) {
    day = "0" + day;
  }
  return year + month + day;
};
/**
 * 格式化秒
 * @param int  value 总秒数
 * @return string result 格式化后的字符串
 */
export const formatSeconds = (value) => {
  var theTime = parseInt(value); // 需要转换的时间秒
  var theTime1 = 0; // 分
  var theTime2 = 0; // 小时
  if (theTime > 60) {
    theTime1 = parseInt(theTime / 60);
    theTime = parseInt(theTime % 60);
    if (theTime1 > 60) {
      theTime2 = parseInt(theTime1 / 60);
      theTime1 = parseInt(theTime1 % 60);
    }
  }
  var result = "";
  if (theTime === 0 && theTime1 === 0 && theTime2 === 0) {
    result = "0秒";
  }
  if (theTime > 0) {
    result = "" + parseInt(theTime) + "秒";
  }
  if (theTime1 > 0) {
    result = "" + parseInt(theTime1) + "分" + result;
  }
  if (theTime2 > 0) {
    result = "" + parseInt(theTime2) + "小时" + result;
  }
  return result;
};
/**
 * 格式化秒
 * @param int  value 总秒数
 * @return string result 格式化后的字符串 HH:mm:ss
 */
export const format_seconds = (value) => {
  let theTime = parseInt(value); // 需要转换的时间秒
  let theTime1 = 0; // 分
  let theTime2 = 0; // 小时
  if (theTime > 60) {
    theTime1 = parseInt(theTime / 60);
    theTime = parseInt(theTime % 60);
    if (theTime1 > 60) {
      theTime2 = parseInt(theTime1 / 60);
      theTime1 = parseInt(theTime1 % 60);
    }
  }
  let t_hour = 0;
  let t_min = 0;
  let t_sec = 0;
  if (theTime > 0) {
    t_sec = parseInt(theTime);
  }
  if (theTime1 > 0) {
    t_min = parseInt(theTime1);
  }
  if (theTime2 > 0) {
    t_hour = parseInt(theTime2);
  }
  return t_hour > 0
    ? `${t_hour > 9 ? "" : 0}${t_hour}:${t_min > 9 ? "" : 0}${t_min}:${
        t_sec > 9 ? "" : 0
      }${t_sec}`
    : `${t_min > 9 ? "" : 0}${t_min}:${t_sec > 9 ? "" : 0}${t_sec}`;
};
/**
 * 获取对象类型
 */
export const getObjType = (obj) => {
  var toString = Object.prototype.toString;
  var map = {
    "[object Boolean]": "boolean",
    "[object Number]": "number",
    "[object String]": "string",
    "[object Function]": "function",
    "[object Array]": "array",
    "[object Date]": "date",
    "[object RegExp]": "regExp",
    "[object Undefined]": "undefined",
    "[object Null]": "null",
    "[object Object]": "object"
  };
  if (obj instanceof Element) {
    return "element";
  }
  return map[toString.call(obj)];
};
//时间戳转时间
export const date_format = (unixtimestamp, type) => {
  if (!unixtimestamp) {
    return "";
  }
  unixtimestamp = new Date(unixtimestamp * 1000 + diffTime);
  var year = 1900 + unixtimestamp.getYear();
  var month = "0" + (unixtimestamp.getMonth() + 1);
  var date = "0" + unixtimestamp.getDate();
  var hour = "0" + unixtimestamp.getHours();
  var minute = "0" + unixtimestamp.getMinutes();
  var second = "0" + unixtimestamp.getSeconds();
  return (
    year +
    "-" +
    month.substring(month.length - 2, month.length) +
    "-" +
    date.substring(date.length - 2, date.length) +
    " " +
    hour.substring(hour.length - 2, hour.length) +
    ":" +
    minute.substring(minute.length - 2, minute.length) +
    (type ? "" : ":" + second.substring(second.length - 2, second.length))
  );
};
//时间转化为时间戳
export const date_time = (datestring) => {
  let time = new Date(datestring).getTime() / 1000;
  if (!time && datestring) {
    //兼容火狐浏览器
    datestring = datestring.replace(new RegExp(/-/gm), "/");
    time = new Date(datestring).getTime() / 1000;
  }
  return parseInt(time);
};
/**
 * 对象深拷贝
 */
export const deepClone = (data) => {
  var type = getObjType(data);
  var obj;
  if (type === "array") {
    obj = [];
  } else if (type === "object") {
    obj = {};
  } else {
    // 不再具有下一层次
    return data;
  }
  if (type === "array") {
    for (var i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]));
    }
  } else if (type === "object") {
    for (var key in data) {
      obj[key] = deepClone(data[key]);
    }
  }
  return obj;
};

/**
 * 日期格式化,时间戳
 */
export function format_date(time, format = "yyyy-MM-dd hh:mm:ss") {
  let date = new Date(time * 1000 + diffTime);
  if (date !== "Invalid Date") {
    let o = {
      "M+": date.getMonth() + 1, // month
      "d+": date.getDate(), // day
      "h+": date.getHours(), // hour
      "m+": date.getMinutes(), // minute
      "s+": date.getSeconds(), // second
      "q+": Math.floor((date.getMonth() + 3) / 3), // quarter
      S: date.getMilliseconds() // millisecond
    };
    if (/(y+)/.test(format)) {
      format = format.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    }
    for (let k in o) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
      }
    }
    return format;
  }
  return "";
}
/**
 * 日期格式化
 */
export function dateFormat(dateDemo, format = "yyyy-MM-dd hh:mm:ss") {
  let date = new Date(dateDemo);
  if (date !== "Invalid Date") {
    var o = {
      "M+": date.getMonth() + 1, // month
      "d+": date.getDate(), // day
      "h+": date.getHours(), // hour
      "m+": date.getMinutes(), // minute
      "s+": date.getSeconds(), // second
      "q+": Math.floor((date.getMonth() + 3) / 3), // quarter
      S: date.getMilliseconds() // millisecond
    };
    if (/(y+)/.test(format)) {
      format = format.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    }
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
      }
    }
    return format;
  }
  return "";
}

// 颜色渐变函数
export function hexToRgba(hex, opacity) {
  let rgbaColor = "";
  let reg = /^#[\da-f]{6}$/i;
  if (reg.test(hex)) {
    rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
      "0x" + hex.slice(3, 5)
    )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
  }
  return rgbaColor;
}
// 包含大小写字母和数字的随机组合
export const generateRandomString = (n = 8) => {
  let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";
  let hasUpperCase = false;
  let hasLowerCase = false;
  let hasDigit = false;
  // 当n<3时，只需随机选择字符即可
  if (n < 3) {
    for (let i = 0; i < n; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }
  // 当n>=3时，需要确保包含大写字母、小写字母和数字
  while (result.length < n) {
    let randomIndex = Math.floor(Math.random() * chars.length);
    let randomChar = chars.charAt(randomIndex);

    // 确保每种类型的字符至少被选中一次
    if (hasUpperCase && hasLowerCase && hasDigit) {
      result += randomChar;
    } else {
      // 如果还没包含大写字母，并且当前字符是大写字母，则添加
      if (!hasUpperCase && /[A-Z]/.test(randomChar)) {
        result += randomChar;
        hasUpperCase = true;
      }
      // 如果还没包含小写字母，并且当前字符是小写字母，则添加
      else if (!hasLowerCase && /[a-z]/.test(randomChar)) {
        result += randomChar;
        hasLowerCase = true;
      }
      // 如果还没包含数字，并且当前字符是数字，则添加
      else if (!hasDigit && /\d/.test(randomChar)) {
        result += randomChar;
        hasDigit = true;
      }
      // 否则跳过这个字符，重新选择
    }
  }
  // 如果字符串长度仍然小于n，则随机添加字符直到满足长度
  while (result.length < n) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  // 打乱结果字符串的顺序以确保随机性
  result = result
    .split("")
    .sort(function () {
      return 0.5 - Math.random();
    })
    .join("");
  return result;
};
/**
 * 提取html字符串中的文字
 */
export const getHtmlPlainText = (html_str = "") => {
  let text = html_str.replace(/<[^<>]+>/g, "").trim();
  return text;
};
//判断html中是否有文字或图片
export const htmlHasContent = (html_str = "") => {
  let text = html_str.replace(/<[^<>]+>/g, "").trim();
  let imgReg = /<img [^>]*src=['"]([^'"]+)[^>]*>/gi;
  let imgUrls = html_str.match(imgReg) || [];
  imgUrls.filter((url) => {
    return url && url.match(/src=['"]?([^'"]*)['"]?/i);
  });
  return Boolean(text) || imgUrls.length > 0;
};
/**
 * 压缩图片方法
 * @param {file} file 文件或文件数组
 * @param {Number} quality 图片质量(取值0-1之间默认0.92)
 */
export const compressImg = (file, quality) => {
  if (Array.isArray(file)) {
    return Promise.all(Array.from(file).map((e) => compressImg(e, quality))); // 如果是 file 数组返回 Promise 数组
  } else {
    let qualitys = 1;
    //单位：MB
    let fileSize = parseInt((file.size / 1024 / 1024).toFixed(2));
    if (1 < fileSize && fileSize < 5) {
      qualitys = 0.92;
    }
    if (5 < fileSize && fileSize < 10) {
      qualitys = 0.85;
    }
    if (10 < fileSize) {
      qualitys = 0.52;
    }
    if (quality) {
      qualitys = quality;
    }
    return new Promise((resolve) => {
      if (qualitys >= 1) {
        resolve(file);
      } else {
        let fileType = file.type;
        if (!fileType || !fileType.includes("image/")) {
          resolve(file);
          return;
        }
        const fileReader = new FileReader(); // 创建 FileReader
        fileReader.onload = ({ target: { result: src } }) => {
          const image = new Image(); // 创建 img 元素
          image.onload = () => {
            const mCanvas = document.createElement("canvas"); // 创建 canvas 元素
            const mCtx = mCanvas.getContext("2d");
            let targetWidth = image.width;
            let targetHeight = image.height;
            let originWidth = image.width;
            let originHeight = image.height;
            if (1 <= fileSize) {
              let maxWidth = 1400;
              let maxHeight = 1400;
              if (5 < fileSize) {
                maxWidth = 1920;
                maxHeight = 1920;
              }
              targetWidth = originWidth;
              targetHeight = originHeight;
              // 图片尺寸超过的限制
              if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 更宽，按照宽度限定尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(
                    maxWidth * (originHeight / originWidth)
                  );
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(
                    maxHeight * (originWidth / originHeight)
                  );
                }
              }
            }
            mCanvas.width = targetWidth;
            mCanvas.height = targetHeight;
            mCtx.clearRect(0, 0, targetWidth, targetHeight);
            mCtx.drawImage(image, 0, 0, targetWidth, targetHeight); // 绘制 canvas
            const canvasURL = mCanvas.toDataURL(fileType, qualitys);
            const buffer = atob(canvasURL.split(",")[1]);
            let length = buffer.length;
            const bufferArray = new Uint8Array(new ArrayBuffer(length));
            while (length--) {
              bufferArray[length] = buffer.charCodeAt(length);
            }
            const miniFile = new File([bufferArray], file.name, {
              type: fileType
            });
            resolve(miniFile);
          };
          image.src = src;
        };
        fileReader.readAsDataURL(file);
      }
    });
  }
};
/**
 * 连接类型列表
 */
export const relationTypeList = [
  {
    label: "左连接",
    value: "left join"
  },
  {
    label: "右连接",
    value: "right join"
  },
  {
    label: "内连接",
    value: "inner join"
  }
];
/**
 * 根据value获取连接的label
 */
export const getRelationTypeName = (relationType) => {
  let relationTypeItem = relationTypeList.filter(
    (v) => v.value === relationType
  )[0];
  return relationTypeItem ? relationTypeItem.label : null;
};
/**
 * 支持字段
 */
export const behaviorList = [
  { id: "long", name: "整型" },
  { id: "double", name: "浮点型" },
  { id: "string", name: "文本" },
  { id: "text", name: "长文本" },
  { id: "date", name: "日期" },
  { id: "datetime", name: "日期时间" },
  { id: "time", name: "时间" }
];
export function uuid() {
  const s = [];
  const hexDigits = "0123456789abcdef";
  for (let i = 0; i < 36; i++) {
    let start = Math.floor(Math.random() * 0x10);
    s[i] = hexDigits.substring(start, start + 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  let start = (s[19] & 0x3) | 0x8;
  s[19] = hexDigits.substring(start, start + 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";

  return s.join("");
}

export function getPosInDom(outerDom, innerDom) {
  // 元素的坐标和大小
  const rect = outerDom.getBoundingClientRect();
  const rect2 = innerDom.getBoundingClientRect();
  const x = rect2.left - rect.left;
  const y = rect2.top - rect.top;

  return {
    x: x,
    y: y,
    width: rect2.width,
    height: rect2.height
  };
}

export function getPosInDomByEvent(outerDom, event) {
  // 元素的坐标和大小
  const rect = outerDom.getBoundingClientRect();

  // 鼠标坐标
  const x = event.clientX;
  const y = event.clientY;

  // 计算鼠标在元素中的坐标
  const elementX = x - rect.left;
  const elementY = y - rect.top;

  return {
    x: elementX,
    y: elementY
  };
}
//表单正则验证
export function testVerify(eleProps) {
  //添加编辑状态不执行
  if (!eleProps.infoFilling) {
    return;
  }
  if (eleProps.isrequired) {
    eleProps.iserr = false;
    //必填校验
    if (
      eleProps.compType === "tpl_comp_select_muti" ||
      eleProps.compType === "tpl_comp_cascade" ||
      eleProps.compType === "tpl_comp_pic" ||
      eleProps.compType === "tpl_comp_annex" ||
      eleProps.compType === "tpl_comp_sign"
    ) {
      //多选 级联
      if (eleProps.fieldvalue.length === 0) {
        this.$Message.error(`${eleProps.requiredmsg}`);
        eleProps.iserr = true;
        return;
      }
    } else if (eleProps.compType === "tpl_comp_stepper") {
      //步进器
      if (eleProps.fieldvalue === 0) {
        this.$Message.error(`${eleProps.requiredmsg}`);
        eleProps.iserr = true;
        return;
      }
    } else if (eleProps.compType === "tpl_comp_table") {
      eleProps.tbodyObj.forEach((arr) => {
        arr.forEach((item) => {
          if (item.state && !item.title) {
            this.$Message.error(`${eleProps.requiredmsg}`);
            eleProps.iserr = true;
            return;
          }
        });
      });
    } else {
      if (eleProps.fieldvalue === "") {
        this.$Message.error(`${eleProps.requiredmsg}`);
        eleProps.iserr = true;
        return;
      }
    }
    if (eleProps.isverification) {
      //正则校验
      if (eleProps.showrule) {
        //自定义正则 customrules
        let reg = new RegExp(eleProps.customrules);
        if (!reg.test(eleProps.fieldvalue)) {
          this.$Message.error(`${eleProps.errmsg}`);
          eleProps.iserr = true;
        }
      } else {
        //选定正则 selectrule
        if (eleProps.selectrule === "^1\\d{10}$") {
          eleProps.fieldvalue = parseInt(eleProps.fieldvalue); //手机号 需要转数字
        }
        let reg = new RegExp(eleProps.selectrule);
        if (!reg.test(eleProps.fieldvalue)) {
          this.$Message.error(`${eleProps.errmsg}`);
          eleProps.iserr = true;
        }
      }
    }
  }
  this.$forceUpdate();
}
/**
 * 返回开始日期（以0点开始）和结束日期（以24点结束）的秒数
 * @param beginDate 开始日期
 * @param endDate 结束日期
 */
export const dateRangeToSecond = ([beginDate, endDate]) => {
  let _begintime = null;
  let _endtime = null;
  if (beginDate) {
    let _beginDate = new Date(beginDate);
    _begintime = new Date(
      _beginDate.getFullYear(),
      _beginDate.getMonth(),
      _beginDate.getDate(),
      0,
      0,
      0
    ).getTime();
    _begintime = parseInt(_begintime / 1000);
  }
  if (endDate) {
    let _endDate = new Date(endDate);
    _endtime = new Date(
      _endDate.getFullYear(),
      _endDate.getMonth(),
      _endDate.getDate(),
      23,
      59,
      59
    ).getTime();
    _endtime = parseInt(_endtime / 1000);
  }
  return {
    begintime: _begintime,
    endtime: _endtime
  };
};
export const doEventInfo = {
  1: "更换SIM卡",
  2: "违规开启蓝牙",
  3: "USB连接电脑",
  4: "USB拔出电脑",
  5: "插入SD卡",
  6: "拔出SD卡",
  7: "账号登录",
  8: "账号退出",
  9: "安装应用",
  10: "卸载应用",
  11: "启动应用",
  12: "首次使用"
};
export const pushTypeInfo = {
  1: "发送消息",
  2: "解除限制",
  3: "限制使用",
  4: "更新策略",
  5: "重启设备",
  6: "恢复出厂"
};
