import {
  Modal,
  message,
  Button,
} from 'antd';
import {
  WeaSearchGroup,
  WeaFormItem,
  WeaLocaleProvider,
} from 'ecCom';
import {
  WeaSwitch,
} from 'comsMobx';
import {
  checkTableFieldValueUnique,
  checkNonstandardStatus,
  checkIsHasOrganization,
} from "../apis/CommonService";
import isFunction from 'lodash/isFunction';

const { getLabel } = WeaLocaleProvider;

/**
 * 检测是否有分权的权限
 * @param {回调函数} callBack 
 */
export const checkHasOrganization = (callBack = null) => {
  checkIsHasOrganization({ moudleType: "integration" }).then(result => {
    if (callBack && typeof (callBack) === "function") {
      callBack(result.manageDetachable);
    }
  })
}

/**
 * 
 * @param {非标编号} params 
 * @param {回调函数} saveCallBack 
 */
export const checkNonstandard = (params = {}, saveCallBack = null) => {
  checkNonstandardStatus(params).then(result => {
    if (saveCallBack && typeof (saveCallBack) === "function") {
      saveCallBack(result);
    }
  })
}

/**
 * form渲染
 * @param {*} form 
 * @param {*} datas 
 * @param {*} needTrigger 
 * @param {*} handleChange 
 * @param {*} otherDom 
 */

export const getForm = (form, datas, needTrigger = true, handleChange = null, otherDom = null, hideFields = null, ecId = "", itemName = "") => {
  const { isFormInit } = form;
  let group = [];
  const formParams = form.getFormParams();
  isFormInit && datas && datas.forEach((c, index) => {
    let items = [];
    c && c.items && c.items.forEach(fields => {
      items.push({
        com: (
          <WeaFormItem ecId={`${ecId || ''}_WeaFormItem@wkqx6i@${itemName}${fields.domkey[0]}`}
            label={`${fields.label}`}
            labelCol={{ span: `${fields.labelcol}` }}
            wrapperCol={{ span: `${fields.fieldcol}` }}
            error={form.getError(fields)}
            tipPosition="bottom"
          >
            <nobr>
              <WeaSwitch ecId={`${ecId || ''}_WeaSwitch@frs1gu@${itemName}${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} onChange={(v) => {
                if (handleChange && typeof handleChange === "function") {
                  handleChange(form, formParams, fields);
                }
              }} />
              {otherDom && typeof (otherDom) === "function" && otherDom(form, fields)}
            </nobr>
          </WeaFormItem>),
        colSpan: 1,
        hide: form.isHide(fields, (keys, allParams) => {
          let bool = false;
          fields && fields.showWhere && fields.showWhere.length > 0 && fields.showWhere.map(w => {
            if (!bool) {
              let show = false;
              for (let val of w.value) {
                if (allParams[w.domkey] == val) {
                  show = true;
                  break;
                }
              }
              bool = !show;
            }
          })
          if (hideFields && typeof (hideFields) === "function") {
            bool = hideFields(allParams, fields);
          }
          return bool;
        })
      });
    })
    if (needTrigger) {
      group.push(<WeaSearchGroup ecId={`${ecId || ''}_WeaSearchGroup@sy84la@${itemName}${index}`} col={1} center={true} needTigger={needTrigger} title={c.title} showGroup={c.defaultshow}
        items={items} />)
    } else {
      group.push(<WeaSearchGroup ecId={`${ecId || ''}_WeaSearchGroup@u6kf6z@${itemName}${index}`} col={1} center={true} needTigger={needTrigger} showGroup={c.defaultshow} items={items} />)
    }
  });
  return group;
}

/**
 * 推荐使用 checkFieldValueUnique
 * @param {*} checkParams 
 * @param {*} form 
 * @param {*} key 
 * @param {1代表名称，2代表标识, 3路径已存在, 4地址已存在} name 
 * @param {满足唯一性执行的内容} saveCallBack
 */
export const checkUnique = (checkParams, form, key, name = "1", operateIndex = "", saveCallBack, params = {}, errorback) => {
  checkTableFieldValueUnique(checkParams).then(result => {
    if (result && result.isNotUnique && operateIndex == "") {
      let title = "";
      if (name == 1) {
        title = getLabel('129943', '名称已存在');
      } else if (name == 2) {
        title = getLabel('387654', '标识已存在');
      } else if (name == 3) {
        title = getLabel('513558', '路径已存在');
      } else if (name == 4) {
        title = getLabel('513568', '地址已存在');
      } else if (name == 5) {
        title = getLabel('504645', '简称已存在');
      } else if (name == 6) {
        title = getLabel('504643', '全称已存在');
      } else if (name == 7) {
        title = getLabel('514192', '流程类型已存在');
      } else if (name == 8) {
        title = getLabel('126042', '主键字段已存在');
      }
      form.showError(key, title);
      if (errorback && typeof (errorback) === "function") {
        errorback();
      }
    } else {
      if (saveCallBack && typeof (saveCallBack) === "function") {
        saveCallBack(params);
      }
    }
  })
}

/**
 * 检测名称或标识等的唯一性，推荐使用校验唯一性的方法
 * @param {object} checkParams 检测表单的一些信息
 * @param {*} name 提示信息类型
 * @returns 
 */
export const checkFieldValueUnique = (checkParams, name) => {
  return checkTableFieldValueUnique(checkParams).then(result => {
    let title = "";
    if (result && result.isNotUnique) {
      if (name == 1) {
        title = getLabel('129943', '名称已存在');
      } else if (name == 2) {
        title = getLabel('387654', '标识已存在');
      } else if (name == 3) {
        title = getLabel('513558', '路径已存在');
      } else if (name == 4) {
        title = getLabel('513568', '地址已存在');
      } else if (name == 5) {
        title = getLabel('504645', '简称已存在');
      } else if (name == 6) {
        title = getLabel('504643', '全称已存在');
      } else if (name == 7) {
        title = getLabel('514192', '流程类型已存在');
      } else if (name == 8) {
        title = getLabel('126042', '主键字段已存在');
      } 
    }
    return title;
  })
}



export const getDescription = (form, datas = [], ecId = "", itemName = "") => {
  const { isFormInit } = form;
  let group = [];
  const formParams = form.getFormParams();
  isFormInit && datas && datas.map((c, index) => {
    let items = [];
    c.items.map(fields => {
      items.push({
        com: (<div style={{ margin: "0 -20px" }}>
          <WeaFormItem ecId={`${ecId || ''}_WeaFormItem@asukbg@${itemName}${fields.domkey[0]}`}
            label={`${fields.label}`}
            labelCol={{ span: `${fields.labelcol}` }}
            wrapperCol={{ span: `${fields.fieldcol}` }}
            error={form.getError(fields)}
            tipPosition="bottom"
          >
            <WeaSwitch ecId={`${ecId || ''}_WeaSwitch@oxx3gc@${itemName}${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} onChange={(v) => {
              if (handleChange && typeof (handleChange) === "function") {
                handleChange(fields, v);
              }
            }} />
          </WeaFormItem>
        </div>),
        colSpan: 1
      })
    });
    group.push(<WeaSearchGroup ecId={`${ecId || ''}_WeaSearchGroup@9jikjt@${itemName}${index}`} col={1} needTigger={true} title={c.title} showGroup={c.defaultshow || true} items={items} />)
  });
  return group;
}


/**
 * 单行文本回车搜索
 * @param {*} form 
 * @param {*} datas 
 * @param {*} onSearch 
 */
export const getAdvancedItem = (form, datas = [], onSearch = null, needTrigger = false, ecId = "", itemName = "") => {
  const { isFormInit } = form;
  let group = [];
  isFormInit && datas && datas.map((c, index) => {
    const formParams = form.getFormParams();
    let items = [];
    c.items.map(fields => {
      items.push({
        com: (<WeaFormItem ecId={`${ecId || ''}_WeaFormItem@5ov6s5@${itemName}${fields.domkey[0]}`}
          label={`${fields.label}`}
          labelCol={{ span: `${fields.labelcol}` }}
          wrapperCol={{ span: `${fields.fieldcol}` }}>
          <WeaSwitch ecId={`${ecId || ''}_WeaSwitch@kac2bu@${itemName}${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} onEnterSearch={onSearch} />
        </WeaFormItem>),
        colSpan: 1
      })
    });
    group.push(<WeaSearchGroup ecId={`${ecId || ''}_WeaSearchGroup@ylnn3o@${itemName}${index}`} col={2} needTigger={needTrigger} title={needTrigger ? c.title : ""} showGroup={c.defaultshow} items={items} />)
  });
  return group;
}

// 用于高级搜索的按钮组
export const getSearchBtns = (searchFun = function () { }, resetFun = function () { }, cancelFun = function () { }, ecId = "", itemName = "") => {
  if (isFunction(searchFun) && isFunction(resetFun) && isFunction(cancelFun)) {
    return [
      <Button ecId={`${ecId || ''}_Button@zagjkj@${itemName}SearchBtn`} type="primary" onClick={searchFun} >{getLabel(197, "搜索")}</Button>,
      <Button ecId={`${ecId || ''}_Button@7p487d@${itemName}ResetBtn`} type="ghost" onClick={resetFun}>{getLabel(2022, "重置")}</Button>,
      <Button ecId={`${ecId || ''}_Button@2ul5bg@${itemName}CancelBtn`} type="ghost" onClick={cancelFun}>{getLabel(31129, "取消")}</Button>
    ];
  } else {
    return [];
  }
}

/**
 * 计算高级搜索的高度
 * @param {*} condition 
 */
export const getSearchFormHeight = (condition = []) => {
  let height = 0;
  condition && condition.forEach(data => {
    if (data.items) {
      height += (Math.ceil(data.items.length / 2) * 72);
    }
  })
  return height;
}

//带表单验证的form数据
export const getFormSearchs = (form, datas, needTigger = true, center = true, lableCol, fieldcol, otherCom = null, ecId = "", itemName = "") => {
  const { isFormInit } = form;
  let group = [];
  const formParams = form.getFormParams();
  isFormInit && datas && datas.map((c, index) => {
    let items = [];
    c.items.map(fields => {
      items.push({
        com: (
          <WeaFormItem ecId={`${ecId || ''}_WeaFormItem@5dfwbb@${itemName}${fields.domkey[0]}`}
            label={`${fields.label}`}
            labelCol={{ span: lableCol ? lableCol : `${fields.labelcol}` }}
            wrapperCol={{ span: fieldcol ? fieldcol : `${fields.fieldcol}` }}
            error={form.getError(fields)}
            tipPosition="bottom"
          >
            <WeaSwitch ecId={`${ecId || ''}_WeaSwitch@k78lxf@${itemName}${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} />
            {fields.showOtherCom && otherCom}
          </WeaFormItem>),
        colSpan: 1
      })
    });
    if (needTigger) {
      group.push(<WeaSearchGroup ecId={`${ecId || ''}_WeaSearchGroup@4aiqsw@${itemName}${index}`}
        center={center} col={1} needTigger={needTigger} title={c.title}
        showGroup={c.defaultshow || true} items={items} />)
    } else {
      group.push(<WeaSearchGroup ecId={`${ecId || ''}_WeaSearchGroup@ertega@${itemName}${index}`} center={center} col={1} needTigger={needTigger}
        showGroup={c.defaultshow || true} items={items} />)
    }
  });
  return group;
}

//表单验证
export const onCheck = (form, func = null, errorBack = null) => {
  form.validateForm().then(f => {
    if (f.isValid) {
      func && typeof func == 'function' && func();
    } else {
      message.warning(getLabel('532053', '请检查必填项是否已经正确填写'));
      f.showErrors();
      errorBack && typeof (errorBack) === "function" && errorBack();
    }
  });
}

/**
 * 重构表单验证方法，使用 promise ，防止 callback-hell 
 * @param {WeaForm} form 要验证的 form 表单 
 * @returns 
 */
export const checkFormValidator = (form) => {
  const promise = new Promise((resolve, reject) => {
    form.validateForm().then(f => {
      if(f.isValid) {
        resolve(true);
      } else {
        message.warning(getLabel('532053', '请检查必填项是否已经正确填写'));
        f.showErrors();
        reject(getLabel('532053', '请检查必填项是否已经正确填写'));
      }
    })
  });

  return promise;
}


//提示
export const setModal = (content) => {
  Modal.warning({
    title: `${getLabel(15172, '系统提示')}`,
    content: content,
  });
}

export const setModalInfo = (content) => {
  Modal.info({
    title: getLabel(15172, '系统提示'),
    content,
    okText: getLabel(826, '确定'),
    onOk: () => { },
  });
}

//form重置
export const doFormReset = (form, conditioninfo) => {
  if (form && conditioninfo) {
    form.resetForm();
    form.initFormFields(conditioninfo);
  }
}

//删除等信息确认，弃用选用 showConfirmDialog
export const doConfirm = (content, func = () => { }, val = {}) => {//确认信息， 方法， 方法参数
  Modal.confirm({
    title: `${getLabel(131329, '信息确认')}`,
    content: content,
    okText: `${getLabel(16631, '确定')}`,
    cancelText: `${getLabel(201, '取消')}`,
    onOk: () => func(val),
  })
}

/**
 * 推荐使用的信息确认弹窗，尽量弃用 doConfirm 方法
 * @param {string} content 提示信息内容 
 * @returns 
 */
export const showConfirmDialog = (content) => {
  const promise = new Promise((resolve) => {
    Modal.confirm({
      title: getLabel(131329, '信息确认'),
      content: <div dangerouslySetInnerHTML={{__html: content}} />,
      okText: getLabel(16631, '确定'),
      cancelText: getLabel(201, '取消'),
      onOk: () => {
        resolve();
      }
    })
  });

  return promise;
}

/**
 * 删除时默认使用的弹窗
 * @param {string} type 默认是批量删除
 * @returns 
 */
export const showDeleteDataConfirmDialog = (type='batch') => {
  const title = ('batch' === type ? getLabel(385625, '确定要删除选择的记录吗？') : getLabel(15097, '确定要删除吗？'));
  return showConfirmDialog(title);
}

//字段处理公共方法
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"
];

const validDBKeys = (value) => {
  let val = value;
  if (dbKeys.indexOf(value.toUpperCase()) >= 0) {
    message.error(`${getLabel(19946, "不能使用数据库保留字作为字段名!")}`);
    val = '';
  }
  return val;
}

export const getNewColumns = (datas) => {
  let columns = [...datas];
  columns[0].com[0] = {
    ...columns[0].com[0],
    otherParams: {
      length: 25,
      regExp: /^[a-zA-Z][a-zA-Z0-9]*$/,
      filter: (val) => {
        return validDBKeys(val);
      }
    }
  }

  columns[2].com[0] = {
    ...columns[2].com[0],
    options: ['peculiar'],
    viewAttr: 3,
    otherParams: {
      customProps: {
        'input.text': {
          defaultValue: '100',
          viewAttr: 3,
        },
        'textarea': {
          parent: {
            type: "div",
            style: {
              display: "none"
            }
          },
          style: {
            display: "none"
          }
        },
        'textarea.*': {
          parent: {
            type: "div",
            style: {
              display: "none"
            }
          },
          style: {
            display: "none"
          }
        },
        'textarea.*.*': {
          style: {
            display: "none"
          }
        },
        "select": {
          options: [{
            key: 'select',
            selected: true,
            showname: getLabel(383051, '下拉框')
          }]
        },
        "upload": {
          options: [{
            key: 'file',
            selected: true,
            showname: getLabel(20798, '上传文件')
          }]
        },
        "peculiar": {
          style: {
            display: "none"
          }
        }
      }
    }
  }
  return columns;
}

//字段保存同名校验
export const doNameRepeat = (datas) => {
  let newArr1 = [], newArr2 = [], isRepeat = false;
  if (datas && datas.length > 0) {
    datas.map(item => {
      if (newArr1.indexOf(item.fieldname) <= -1) { //判断字段名称是否重复
        newArr1.push(item.fieldname);
      } else {
        isRepeat = true;
      }
      if (newArr2.indexOf(item.fieldlabel) <= -1) { //判断字段显示名是否重复
        newArr2.push(item.fieldlabel);
      } else {
        isRepeat = true;
      }
    });
  }
  return isRepeat;
}

//处理checkbox默认选中, 级联默认值100
export const getNewData = (datas) => {
  const newDatas = JSON.parse(JSON.stringify(datas));
  newDatas.map(v => {
    if (!v.fieldid) {
      if (v.isUse == '') {
        v.isUse = '1'
      }
      if (v.type && v.type.join('') == 'inputtext') {
        v.type = ["input", "text", "100"];
      }
    }
  });
  return newDatas;
}

export const GeneralTitleColor = {
  icon: "icon-coms-integration",
  iconDom: <i className="icon-coms-integration" />,
  iconBgcolor: "#1A57A0",
  moduleName: "integration"
}

export const defaultBtns = {
  defaultSaveBtns: [{
    type: "primary",
    key: "BTN_SAVE",
    icon: <i className="icon-coms-Preservation" />,
    content: getLabel(30986, '保存')
  }],
  defaultCloseBtns: [{
    type: "primary",
    key: 'BTN_EXIT',
    icon: <i className="icon-coms02-Exit" />,
    content: getLabel('309', '关闭'),
  }]
};

//是否包含特殊字段
export const isSpecialChar = (str) => {
  var reg = /[-\+=\`~!@#$%^&\*\(\)\[\]{};:'",.<>\/\?\\|]/;
  return reg.test(str);
}

/**
 * 生成随机密码
 * @param {密码长度随机} randomFlag 
 * @param {密码最小长度} minLength 
 * @param {密码最大长度} maxLength 
 */
export const getAppSecret = (randomFlag, minLength, maxLength) => {
  let $chars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
  let str = '';

  if (randomFlag) {
    if (maxLength >= minLength) {
      let len = Math.round(Math.random() * (maxLength - minLength)) + minLength;
      for (let i = 0; i < len; i++) {
        let pos = Math.floor(Math.random() * $chars.length);
        str += $chars[pos];
      }
    }
  } else {
    for (let i = 0; i < minLength; i++) {
      let pos = Math.floor(Math.random() * $chars.length);
      str += $chars[pos];
    }
  }
  return str;
}

/**
 * 右键菜单的图标
 */
export const menuIcon = {
  save: <i className="icon-coms-Preservation" />,
  column: <i className="icon-coms-Custom" />,
  exit: <i className="icon-coms02-Exit" />
}

export const isCallBackFunction = (callBack) => {
  let flag = false;

  if (callBack && typeof callBack === "function") {
    flag = true;
  }
  return flag;
}

/**
 * 查找当前页面来源是否是产品集成
 * @returns typename 从哪个产品功能跳转过来的
 */
export const findOriginFromRoute = () => {
  const href = location.href.trim() || '',
    paramsIndex = href.indexOf('?');

  if((paramsIndex != -1) && (href.indexOf('typename') > paramsIndex) && (href.indexOf('from=productEntrance') > paramsIndex)) {
    // 当前是从产品集成中访问到页面的
    const url = href.split('?')[1];
    if(url) {
      const params = url.split('&');
      const query = {};
      for(let i = 0; i < params.length; i++) {
        query[params[i].split('=')[0]] = params[i].split('=')[1];
      }
      return query.typename || '';
    }else {
      return '';
    }
  }else {
    return '';
  }
}
