import isEmpty from "lodash/isEmpty";
import { message } from "antd";
import { indexOf } from "lodash";

const dbKeys = [
  "PERCENT",
  "PLAN",
  "PRECISION",
  "PRIMARY",
  "PRINT",
  "PROC",
  "PROCEDURE",
  "PUBLIC",
  "RAISERROR",
  "READ",
  "READTEXT",
  "RECONFIGURE",
  "REFERENCES",
  "REPLICATION",
  "RESTORE",
  "RESTRICT",
  "RETURN",
  "REVOKE",
  "RIGHT",
  "ROLLBACK",
  "ROWCOUNT",
  "ROWGUIDCOL",
  "RULE",
  "SAVE",
  "SCHEMA",
  "SELECT",
  "SESSION_USER",
  "SET",
  "SETUSER",
  "SHUTDOWN",
  "SOME",
  "STATISTICS",
  "SYSTEM_USER",
  "TABLE",
  "TEXTSIZE",
  "THEN",
  "TO",
  "TOP",
  "TRAN",
  "TRANSACTION",
  "TRIGGER",
  "TRUNCATE",
  "TSEQUAL",
  "UNION",
  "UNIQUE",
  "UPDATE",
  "UPDATETEXT",
  "USE",
  "USER",
  "VALUES",
  "VARYING",
  "VIEW",
  "WAITFOR",
  "WHEN",
  "WHERE",
  "WHILE",
  "WITH",
  "WRITETEXT",
  "EXCEPT",
  "EXEC",
  "EXECUTE",
  "EXISTS",
  "EXIT",
  "FETCH",
  "FILE",
  "FILLFACTOR",
  "FOR",
  "FOREIGN",
  "FREETEXT",
  "FREETEXTTABLE",
  "FROM",
  "FULL",
  "FUNCTION",
  "GOTO",
  "GRANT",
  "GROUP",
  "HAVING",
  "HOLDLOCK",
  "IDENTITY",
  "IDENTITY_INSERT",
  "IDENTITYCOL",
  "IF",
  "IN",
  "INDEX",
  "INNER",
  "INSERT",
  "INTERSECT",
  "INTO",
  "IS",
  "JOIN",
  "KEY",
  "KILL",
  "LEFT",
  "LIKE",
  "LINENO",
  "LOAD",
  "NATIONAL",
  "NOCHECK",
  "NONCLUSTERED",
  "NOT",
  "NULL",
  "NULLIF",
  "OF",
  "OFF",
  "OFFSETS",
  "ON",
  "OPEN",
  "OPENDATASOURCE",
  "OPENQUERY",
  "OPENROWSET",
  "OPENXML",
  "OPTION",
  "OR",
  "ORDER",
  "OUTER",
  "OVER",
  "ADD",
  "ALL",
  "ALTER",
  "AND",
  "ANY",
  "AS",
  "ASC",
  "AUTHORIZATION",
  "BACKUP",
  "BEGIN",
  "BETWEEN",
  "BREAK",
  "BROWSE",
  "BULK",
  "BY",
  "CASCADE",
  "CASE",
  "CHECK",
  "CHECKPOINT",
  "CLOSE",
  "CLUSTERED",
  "COALESCE",
  "COLLATE",
  "COLUMN",
  "COMMIT",
  "COMPUTE",
  "CONSTRAINT",
  "CONTAINS",
  "CONTAINSTABLE",
  "CONTINUE",
  "CONVERT",
  "CREATE",
  "CROSS",
  "CURRENT",
  "CURRENT_DATE",
  "CURRENT_TIME",
  "CURRENT_TIMESTAMP",
  "CURRENT_USER",
  "CURSOR",
  "DATABASE",
  "DBCC",
  "DEALLOCATE",
  "DECLARE",
  "DEFAULT",
  "DELETE",
  "DENY",
  "DESC",
  "DISK",
  "DISTINCT",
  "DISTRIBUTED",
  "DOUBLE",
  "DROP",
  "DUMMY",
  "DUMP",
  "ELSE",
  "END",
  "ERRLVL",
  "ESCAPE",
  "ACCESS",
  "ADD",
  "ALL",
  "ALTER",
  "AND",
  "ANY",
  "AS",
  "ASC",
  "AUDIT",
  "BETWEEN",
  "BY",
  "CHAR",
  "CHECK",
  "CLUSTER",
  "COLUMN",
  "COMMENT",
  "COMPRESS",
  "CONNECT",
  "CREATE",
  "CURRENT",
  "DATE",
  "DECIMAL",
  "DEFAULT",
  "DELETE",
  "DESC",
  "DISTINCT",
  "DROP",
  "ELSE",
  "EXCLUSIVE",
  "EXISTS",
  "FILE",
  "FLOAT",
  "FOR",
  "FROM",
  "GRANT",
  "GROUP",
  "HAVING",
  "IDENTIFIED",
  "IMMEDIATE",
  "IN",
  "INCREMENT",
  "INDEX",
  "INITIAL",
  "INSERT",
  "INTEGER",
  "INTERSECT",
  "INTO",
  "IS",
  "LEVEL",
  "LIKE",
  "LOCK",
  "LONG",
  "MAXEXTENTS",
  "MINUS",
  "MLSLABEL",
  "MODE",
  "MODIFY",
  "NOAUDIT",
  "NOCOMPRESS",
  "NOT",
  "NOWAIT",
  "NULL",
  "NUMBER",
  "OF",
  "OFFLINE",
  "ON",
  "ONLINE",
  "OPTION",
  "OR",
  "ORDER",
  "PCTFREE",
  "PRIOR",
  "PRIVILEGES",
  "PUBLIC",
  "RAW",
  "RENAME",
  "RESOURCE",
  "REVOKE",
  "ROW",
  "ROWID",
  "ROWNUM",
  "ROWS",
  "SELECT",
  "SESSION",
  "SET",
  "SHARE",
  "SIZE",
  "SMALLINT",
  "START",
  "SUCCESSFUL",
  "SYNONYM",
  "SYSDATE",
  "TABLE",
  "THEN",
  "TO",
  "TRIGGER",
  "UID",
  "UNION",
  "UNIQUE",
  "UPDATE",
  "USER",
  "VALIDATE",
  "VALUES",
  "VARCHAR",
  "VARCHAR2",
  "VIEW",
  "WHENEVER",
  "WHERE",
  "WITH"
];

export const validate = (conditions, params = {}) => {
  if (!isEmpty(conditions)) {
    for (let i = 0, leg = conditions.length; i < leg; i++) {
      let cd = conditions[i];
      for (let j = 0, length = cd.items.length; j < length; j++) {
        let c = cd.items[j];
        if (c) {
          let domkey = c.domkey[0];
          let viewAttr = c.viewAttr;
          if (c.conditionType == "BROWSER")
            viewAttr = c.browserConditionParam.viewAttr;
          if (viewAttr == "3" && !params[domkey]) {
            if (domkey == "managerid" || domkey == "belongto") {
              //直接上级 主账号不用校验
            } else {
              //message.warning(domkey+'必要信息不完整！');
              message.warning("必要信息不完整！");
              return false;
            }
          }
        }
      }
    }
  }
  return true;
};

export const getFormParamValue = (conditions = {}, fieldname) => {
  let fieldvalue = "";
  if (!isEmpty(conditions)) {
    for (let i = 0, leg = conditions.length; i < leg; i++) {
      let cd = conditions[i];
      for (let j = 0, length = cd.items.length; j < length; j++) {
        let c = cd.items[j];
        if (c) {
          let domkey = c.domkey[0];
          if (domkey == fieldname) {
            fieldvalue = c.value;
          }
        }
      }
    }
  }
  return fieldvalue;
};

export const transParams = formParams => {
  let params = {};
  for (let key in formParams) {
    if (formParams[key] === !!formParams[key])
      params[key] = !!formParams[key] ? "1" : "0";
    else params[key] = formParams[key];
  }
  return params;
};

export const findTabCount = str => {
  const bIndex = str.lastIndexOf("(");
  const eIndex = str.lastIndexOf(")");
  let title = "",
    count = "";
  try {
    title = str.substring(0, bIndex);
    count = str.substring(bIndex + 1, eIndex);
  } catch (err) {}
  return {
    title,
    count
  };
};

export const calFormHeight = (groupLength, children) => {
  let childrenLength = 0;
  children.map(c => {
    if (c.colSpan != null) {
      childrenLength += c.colSpan == 2 ? 1 : 2;
    } else childrenLength += 1;
  });
  let height = (childrenLength / 2 + (childrenLength % 2)) * 52 + 10;
  if (groupLength > 1) height += groupLength * 45;
  if (height > 300) return 300;
  return height;
};

export const validDBKeys = value => {
  if (indexOf(dbKeys, value.toUpperCase()) >= 0) {
    message.error("不能使用数据库保留字作为字段名!");
    return {
      isValid: false,
      value: ""
    };
  }
  return {
    isValid: true,
    value
  };
};

export const validNumber = value => {
  if (isNaN(parseInt(value))) return 0;
  return parseInt(value);
};

export const getColumIndex = num => {
  const n = 64;
  const loopIndex = num / 26;
  if (loopIndex <= 1)
    return String.fromCharCode(n + (num % 26 === 0 ? 26 : num));
  else
    return `${String.fromCharCode(
      n + parseInt(loopIndex)
    )}${String.fromCharCode(n + (num % 26))}`;
};

export const calColumnIndex = val => {
  const arr = Array.from(val);
  let num = 0;
  if (arr.length === 1) num = arr[0].charCodeAt() - 64;
  else {
    arr.map((c, i) => {
      if (i === 0) num += (c.charCodeAt() - 64) * 26;
      else num += c.charCodeAt() - 64;
    });
  }

  return num;
};

export const convertCalendarDate = date => {
  const y = date.getYear();
  let d = date.getDayOfMonth();
  if (d < 10) d = "0" + d;
  let m = date.getMonth() + 1;
  if (m < 10) m = "0" + m;
  return `${y}-${m}-${d}`;
};

export const dateFormat = (date, format) => {
  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|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;
};

/**
 * 添加多级路径
 *
 * @param {*} url
 */
export const addContentPath = (url) => {
  const ecologyContentPath = window.ecologyContentPath || '';
  if (url && ecologyContentPath) {
    //避免重复添加ecologyContentPath
    //避免传入的参数不是链接
    if (url.startsWith('/') && !url.startsWith(ecologyContentPath)) {
      url = ecologyContentPath + url;
    }
  }
  return url;
};