/* eslint-disable no-undef */
// import { color } from 'html2canvas/dist/types/css/types/color';  //wyw 这个会影响
import { random, omit } from 'lodash';
import moment from 'moment';
const RFC4122_TEMPLATE = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';

export function uuid(placeholder) {
  return RFC4122_TEMPLATE.replace(/[xy]/g, function () {
    let value = random(15)
    value = placeholder === 'x' ? value : (value & 0x3 | 0x8)
    return value.toString(16)
  })
}

export function Base64_Encode(str) { // base64转换
  let c1, c2, c3;
  let base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  let i = 0;
  let len = str.length;
  let string = '';

  while (i < len) {
    c1 = str.charCodeAt(i++) & 0xff;
    if (i === len) {
      string += base64EncodeChars.charAt(c1 >> 2);
      string += base64EncodeChars.charAt((c1 & 0x3) << 4);
      string += "==";
      break;
    }
    c2 = str.charCodeAt(i++);
    if (i === len) {
      string += base64EncodeChars.charAt(c1 >> 2);
      string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
      string += base64EncodeChars.charAt((c2 & 0xF) << 2);
      string += "=";
      break;
    }
    c3 = str.charCodeAt(i++);
    string += base64EncodeChars.charAt(c1 >> 2);
    string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
    string += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
    string += base64EncodeChars.charAt(c3 & 0x3F);
  }
  return string;
}

export function guid() {
  function S4() {
    return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
  }
  return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4();
}

export function extend(obj1, obj2) {
  if (typeof (obj2) === 'object')
    for (let p in obj2) obj1[p] = obj2[p];
}

//wyw 添加 子表过滤条件
export function extendFilterGroupGroupRules(obj, filed, op, value, isSysParam) { //查询条件
  let data = {};
  if (value === null) {
    value = '';
  }
  data['Field'] = filed;
  data['Operate'] = op;
  data['Value'] = isSysParam ? value.toString() : value;
  if (isSysParam) {
    data["IsSysParamRule"] = true;
  }

  if (!obj.FilterGroup) {
    obj.FilterGroup = {};
  }
  if (!obj.FilterGroup.groups) {
    obj.FilterGroup.groups = [];
  }
  if (!obj.FilterGroup.groups[0].rules) {
    obj.FilterGroup.groups[0].rules = [];
  }
  obj.FilterGroup.groups[0].rules.push(data);
}


export function extendRule(obj, filed, op, value, isSysParam) { //查询条件
  let data = {};
  if (value === null) {
    value = '';
  }
  data['Field'] = filed;
  data['Operate'] = op;
  data['Value'] = isSysParam ? value.toString() : value;
  if (isSysParam) {
    data["IsSysParamRule"] = true;
  }

  if (!obj.FilterGroup) {
    obj.FilterGroup = {};
  }
  if (!obj.FilterGroup.Rules) {
    obj.FilterGroup.Rules = [];
  }
  obj.FilterGroup.Rules.push(data);
}

export function initFilterGroup(IsAnd = true) {
  return {
    IsAnd,
    Rules: [],
    Groups: [],
  }
}


export function extendFilterGroup(obj, obj2) {

  if (!obj.FilterGroup) {
    obj.FilterGroup = {};
  }
  if (!obj.FilterGroup.Groups) {
    obj.FilterGroup.Groups = [];
  }
  obj.FilterGroup.Groups.push(obj2);
}

export function extendChildGroup(obj, obj2) {
  if (!obj.Groups) {
    obj.Groups = [];
  }
  obj.Groups.push(obj2);
}

export function extendGroupRule(obj, filed, op, value, isSysParam) { //查询条件
  let data = {};
  if (value === null) {
    value = '';
  }
  data['Field'] = filed;
  data['Operate'] = op;
  data['Value'] = isSysParam ? value.toString() : value;
  if (isSysParam) {
    data["IsSysParamRule"] = true;
  }

  if (!obj.Rules) {
    obj.Rules = [];
  }
  obj.Rules.push(data);

}

export function initQueryFilter(OrgId, PageIndex, Limit, Sort, Order) {
  return {
    OrgId,
    PageIndex,
    Limit,
    Start: (PageIndex - 1) * Limit,
    Sort,
    Order: (Order === '' ? 0 : Order),
    RuleCount: 0,
    IncludeCount: 0,
    OrderCount: 0,
    FilterGroupCount: 0,
    Include: [],
    Orders: [],
    FilterGroup: { Rules: [], Groups: [] }
  };
}

export function initFilter(OrgId, Keyword = "", Sort, Order, PageIndex = 1, Parameter1, Parameter2, Parameter3, Parameter4, Parameter5, Parameter6) {
  return {
    Keyword,
    Parameter1,
    Parameter2,
    Parameter3,
    Parameter4,
    Parameter5,
    Parameter6,
    OrgId,
    PageIndex,
    Limit: 10,
    Start: (PageIndex - 1) * 10,
    Sort,
    Order: (Order === '' ? 0 : Order),
    RuleCount: 0,
    IncludeCount: 0,
    OrderCount: 0,
    FilterGroupCount: 0,
    Include: [],
    Orders: [],
    FilterGroup: { Rules: [], Groups: [] },
    SelectField: [],
    DataRule: [],
    IgnoreDataRule: false
  };
  // let params = $("#search-form").elFilterParam();
  // extend(json, params);
}

export function extendInclude(obj, clude) {

  if (!obj.Include) {
    obj.Include = [];
  }
  obj.Include.push(clude);
}

export function extendOrder(obj, filed, order) {
  var data = {};
  data["Field"] = filed;
  data["Order"] = order;
  if (!obj.Orders) {
    obj.Orders = [];
  }
  obj.Orders.push(data);
}
export function extendIgnoreDataRule(obj) {
  obj.IgnoreDataRule = true
}

function trim(str) { // ?
  for (var i = 0; i < str.length && str.charAt(i) == "  "; i++)
    ;
  for (var j = str.length; j > 0 && str.charAt(j - 1) == "  "; j--)
    ;
  if (i > j)
    return "";
  return str.substring(i, j);
}

export function empty(v, allowZero) {
  if (v === "null" || v === undefined || v === "") return true;
  switch (typeof v) {
    case 'undefined':
      return true;
    case 'string':
      if (trim(v).length == 0)
        return true;
      break;
    case 'boolean':
      if (!v)
        return true;
      break;
    case 'number':
      if (0 === v && !allowZero)
        return true;
      break;
    case 'object':
      if (null === v)
        return true;
      if (undefined !== v.length && v.length == 0)
        return true;
      for (var k in v) {
        return false;
      }
      return true;
    default:
      return false;
  }
}

export function strConvert(target, def) { // 点字符串转对象
  // str为需要转换的值, def为有固定的最后一个属性值
  let splitFiles = target.split('.');
  let str = '';
  let len = splitFiles.length;
  splitFiles.forEach(item => {
    str += '{\"' + item + '\":'
  });
  str += "" + def + ""
  for (let j = 0; j < len; j++) {
    str += '}'
  }
  let mat = JSON.parse(str);
  return mat
}

//仅仅获取对象的基础属性，不包含属性中的对象
export function getOnlyPropertyData(data, isGetSysParam) {
  let result = {};
  Object.keys(data).forEach((n) => {
    if (n.indexOf('.') !== -1) return;
    if (isGetSysParam && n === 'Nav_SysParams') {
      result[n] = data[n];
    }
    else if (Array.isArray(data[n])) {
      result[n] = data[n];
    }
    else if (typeof (data[n]) !== "object") {
      result[n] = data[n];
    }
  });
  return result;
}

//仅仅获取对象的基础属性及列表，不包含属性中的对象
export function getPropertyData(data, isSetDelete) {
  let result = {};
  Object.keys(data).forEach((n) => {
    if (n.indexOf('.') != -1) return;
    if (typeof (data[n]) !== "object") {
      result[n] = data[n];
    }
    else if (data[n] && data[n].length) {
      const array = [];
      data[n].forEach(nx => {
        const d = getPropertyData(nx, isSetDelete);
        array.push(d);
      });
      result[n] = array;
    }
    if (isSetDelete) {
      result['IS_DELETED'] = true;
    }
  });
  return result;
}

// 取导航属性的最后一个字段
export function dataIndexName(field) {
  const valueValid = field ? field.split('.') : [];
  return valueValid[valueValid.length - 1]
}

export function splitEnum(str) {
  let newArr = [];
  let oArr = str ? str.split(',') : [];
  oArr.forEach(item => {
    let n = item.split(':');
    newArr.push({
      label: n[0],
      value: n[1]
    })
  });
  return newArr
}

export function getDataFieldValueByCol(data, field, defaultValue) {
  if (!data || !field) return null;
  let opIndex = field.lastIndexOf('/');
  let op = 0;
  if (opIndex === -1) {
    opIndex = field.indexOf('*');
    if (opIndex === -1) {
      opIndex = field.indexOf('+');
      if (opIndex === -1) {
        opIndex = field.lastIndexOf('-');
        if (opIndex !== -1) {
          op = 2;
        }
      } else {
        op = 1;
      }
    } else {
      op = 3;
    }
  } else {
    op = 4;
  }

  let controlValue = null;
  if (opIndex !== -1) {
    const leftField = field.substring(0, opIndex);
    const rightField = field.substring(opIndex + 1);
    const leftText = getDataFieldValueByCol(data, leftField);
    const rigthText = getDataFieldValueByCol(data, rightField);
    if (leftText !== '' && rigthText !== '' && !isNaN(leftText) && !isNaN(rigthText)) {
      if (op === 1) {
        controlValue = (+leftText) + (+rigthText);
      } else if (op === 2) {
        controlValue = (+leftText) - (+rigthText);
      } else if (op === 3) {
        controlValue = (+leftText) * (+rigthText);
      } else if (op === 3 && (+rigthText) !== 0) {
        controlValue = (+leftText) / (+rigthText);
      }
    }
  }
  else {
    controlValue = getDataFieldValue(data, field, defaultValue);
  }
  return controlValue;
}

function innerGetDataFieldValue(data, field, defaultValue) {
  if (!data || !field) return null;
  const valueValid = field ? field.split('.') : [];
  let controlValue = null;
  let tmp = { ...data };
  if (tmp) {
    for (let j = 0; j < valueValid.length; j++) {
      if (j < valueValid.length - 1) {
        if (!Array.isArray(tmp)) {
          if (tmp && tmp.hasOwnProperty(valueValid[j])) {
            tmp = tmp[valueValid[j]];
          } else {
            tmp = null;
          }
        }
        else {
          let arrayTmp = [];
          tmp.forEach(item => {
            if (item && item.IS_DELETED) {
            } else {
              if (item.hasOwnProperty(valueValid[j])) {
                arrayTmp.push(item[valueValid[j]]);
              }
            }
          })
          tmp = arrayTmp;
        }
      } else {
        if (!Array.isArray(tmp)) {
          if (tmp && tmp.hasOwnProperty(valueValid[j])) {
            controlValue = tmp[valueValid[j]];
          }
        } else {
          controlValue = '';
          tmp.forEach(item => {
            if (item.IS_DELETED) {
            } else {
              controlValue += item[valueValid[j]] + ",";
            }
          })
          if (controlValue && controlValue.indexOf(',') > 0) {
            controlValue = controlValue.substring(0, controlValue.length - 1);
          }
        }
      }
    }
  }
  if (controlValue == null && defaultValue !== undefined) {
    return defaultValue;
  }
  return controlValue;
}

export function getDataFieldValue(data, field, defaultValue) {
  if (!data || !field) {
    if (defaultValue !== undefined) {
      return defaultValue;
    }
    return null;
  }
  const key = 'Nav_SysParams';
  const index = field.indexOf(key);
  if (index === -1) {
    return innerGetDataFieldValue(data, field, defaultValue);
  }
  else {
    const f1 = index > 0 ? field.substring(0, index - 1) : null;
    const f2 = field.substring(index + key.length + 1);
    let temp = null;
    if (f1) {
      temp = innerGetDataFieldValue(data, f1);
    }
    else {
      temp = data;
    }
    if (temp) {
      let sysParams = temp[key];
      if (sysParams) {
        let paramRecord = sysParams.filter(t => t.CODE === f2)[0];
        if (paramRecord) {
          return paramRecord.VALUE;
        }
      }
    }
  }
  if (defaultValue !== undefined) {
    return defaultValue;
  }
  return null;
}

function innerSetDataFieldValue(data, field, value) {
  let tmp = data;
  const valueValid = field ? field.split('.') : [];
  for (let j = 0; j < valueValid.length; j++) {
    if (j < valueValid.length - 1) {
      if (!tmp.hasOwnProperty(valueValid[j]) || !tmp[valueValid[j]]) {
        tmp[valueValid[j]] = {};
      }
      let tmpData = tmp[valueValid[j]];
      if (!tmpData) {
        tmpData = {};
      }
      tmp = tmpData;
    } else {
      tmp[valueValid[j]] = value;
    }
  }
  return data;
}
export function setDataFieldValue(data, field, value) {
  if (!data || !field) return data;
  const key = 'Nav_SysParams';
  const index = field.indexOf(key);
  if (index === -1) {
    innerSetDataFieldValue(data, field, value);
  }
  else {
    const f1 = index > 0 ? field.substring(0, index - 1) : null;
    const f2 = field.substring(index + key.length + 1);
    let temp = null;
    if (f1) {
      temp = innerGetDataFieldValue(data, f1);
      if (!temp) {
        temp = {};
        innerSetDataFieldValue(data, f1, temp);
      }
    }
    else {
      temp = data;
    }
    let sysParams = temp[key];
    if (!sysParams) {
      sysParams = [];
      temp[key] = sysParams;
    }
    let paramRecord = sysParams.filter(t => t.CODE === f2)[0];
    if (!paramRecord) {
      paramRecord = {
        ID: guid(),
        CODE: f2,
        ENTITY_ID: temp.ID,
      }
      sysParams.push(paramRecord);
    }
    paramRecord.VALUE = value;
  }
  return data;
}

export function getParseValue(value, user, getHeadFieldValueFunc, getRecordFieldValueFunc, thisRef) {
  if (value && typeof (value) == 'string') {
    let index = value.indexOf("@user.");
    let departmentIndex = value.indexOf("@department.");
    let teamIndex = value.indexOf("@team.");
    if (index == 0) {
      let field = value.substring(6);
      if (field) {
        if (user) {
          value = getDataFieldValue(user, field, null);
        }
      };
    } else if (departmentIndex == 0) {
      let field1 = value.substring(12);
      if (field1) {
        if (user && user.Nav_Department) {
          value = getDataFieldValue(user.Nav_Department, field1, null);
        } else {
          value = "";
        }
      };
    } else if (teamIndex == 0) {
      let field2 = value.substring(6);
      if (field2) {
        if (user && user.Team) {
          value = getDataFieldValue(user.Team, field2, null);
        } else {
          value = '00000000-0000-0000-0000-000000000000';
        }
      };
    }
    else {
      index = value.indexOf("@nowDate");
      if (index == 0) {
        value = moment().format('YYYY-MM-DD');
      } else {
        index = value.indexOf("@nowTime");
        if (index == 0) {
          value = moment().format('HH:mm:ss');
        } else {
          index = value.indexOf("@now");
          if (index == 0) {
            value = moment().format('YYYY-MM-DD HH:mm:ss');
          } else {
            index = value.indexOf("@head.");
            if (index == 0) {
              const field = value.substring(6);
              if (field && typeof getHeadFieldValueFunc === 'function') {
                value = getHeadFieldValueFunc(field, thisRef);
              };
            } else {
              index = value.indexOf("@record.");
              if (index === 0) {
                const field = value.substring(8);
                if (field && typeof getRecordFieldValueFunc === 'function') {
                  value = getRecordFieldValueFunc(field, thisRef);
                };
              }
            }
          }
        }
      }


    }
  }
  return value;
}

export function permissionUtils(login) {
  const checkPermission = (formId, keyId, type) => {
    if (login.userType == 99 || !formId) return true; //管理员
    let hasPermission = false;
    const currActivatedMenu = login.currActivatedMenu || {}
    if (login.rolePerm && login.rolePerm.Nav_RolePermForms && login.rolePerm.Nav_RolePermForms.length) { //只要一个角色有权限就有权限
      /**
       * hasPermssion 判断为 true 之后，必须直接赋值为 true，
       * 不能用条件判断（比如：hasPermission = matchForm;）去赋值
       * 因为一直在循环，满足 if 条件后，可能 hasPermission 又被置为 false 了
       */
      login.rolePerm.Nav_RolePermForms.forEach((n1, i1) => {
        if (!currActivatedMenu.ID) {
          hasPermission = true
        } else {
          if (n1.PermFormId === formId) {
            const matchForm = (n1.MenuId === currActivatedMenu.ID || !currActivatedMenu.ID)
            if (type == 0 && matchForm) { //表单权限
              hasPermission = true;
            } else if (type == 1) { //按钮权限
              if (n1.Nav_Btns && n1.Nav_Btns.length) {
                n1.Nav_Btns.forEach((n2, i2) => {
                  const matchBtn = (n2.MenuId === currActivatedMenu.ID || !currActivatedMenu.ID)
                  if (n2.BtnId === keyId && matchBtn) {
                    hasPermission = true;
                  }
                });
              }
            } else if (type == 2) { //行权限
              if (n1.Nav_Columns && n1.Nav_Columns.length) {
                n1.Nav_Columns.forEach((n2, i2) => {
                  const matchRow = (n2.MenuId === currActivatedMenu.ID || !currActivatedMenu.ID)
                  if (n2.ColumnId === keyId && matchRow) {
                    hasPermission = true;
                  }
                });
              }
            }
          }
        }


      });
    }
    return hasPermission;
  };
  return {
    checkBtn: (formId, btnId) => {
      return checkPermission(formId, btnId, 1);
    },
    checkColumn: (formId, columnId) => {
      return checkPermission(formId, columnId, 2);
    },
    checkForm: (formId) => {
      return checkPermission(formId, '', 0);
    },
  };
}

//根据枚举字符串获取枚举列表
export function getEnums(str) {
  let newArr = {};
  let oArr = str ? str.split(',') : [];
  oArr.forEach(item => {
    let n = item.split(':');
    newArr[[n[1]]] = n[0];
  });
  return newArr
}

export function getCustomParams(customParamsStr) {
  const customParams = {};
  if (customParamsStr && typeof customParamsStr === 'string') {
    let arrays = customParamsStr.split('|');
    arrays.forEach(function (n, i) {
      let paris = n.split("=");
      if (paris.length >= 2) {
        customParams[paris[0]] = paris[1];
      } else {
        customParams[paris[0]] = null;
      }
    });
  }
  return customParams;
}

export function getParseValueByDate(date) {
  if (date) {
    let r = null;
    if (date === "{now}") {
      r = [moment(), moment()];
    } else if (date.indexOf('{now,') > -1) {
      const tt1 = date.indexOf('}');
      const et = tt1 > -1 ? date.substring(tt1 + 1) : null;
      if (et && et.indexOf('{now,') > -1) {
        const bs = date.substring(0, tt1 + 1);
        let b1 = bs.substring(5);
        let e1 = et.substring(5);
        b1 = b1.substring(0, b1.length - 1);
        e1 = e1.substring(0, e1.length - 1);
        const bts = b1.split(',');
        const ets = e1.split(',');
        if (bts && bts.length >= 2 && ets && ets.length >= 2) {
          const n1 = bts[1];
          const n2 = ets[1];
          const b = n1 > 0 ? moment().add(n1, bts[0]) : (n1 < 0 ? moment().subtract(Math.abs(n1), bts[0]) : moment());
          const e = n2 > 0 ? moment().add(n2, ets[0]) : (n2 < 0 ? moment().subtract(Math.abs(n2), ets[0]) : moment());
          if (b.isBefore(e)) {
            r = [b, e];
          }
        }

      }
      else {
        let t = date.substring(5);
        t = t.substring(0, t.length - 1);
        const ts = t.split(',');
        if (ts && ts.length >= 2) {
          if (ts.length === 2) {
            const n1 = ts[1];
            if (n1 > 0) {
              r = [moment(), moment().add(n1, ts[0])];
            } else if (n1 < 0) {
              r = [moment().subtract(Math.abs(n1), ts[0]), moment()];
            } else {
              r = [moment(), moment()];
            }
          }
          else {
            const n1 = ts[1];
            const n2 = ts[2];
            const b = n1 > 0 ? moment().add(n1, ts[0]) : (n1 < 0 ? moment().subtract(Math.abs(n1), ts[0]) : moment());
            const e = n2 > 0 ? moment().add(n2, ts[0]) : (n2 < 0 ? moment().subtract(Math.abs(n2), ts[0]) : moment());
            if (b.isBefore(e)) {
              r = [b, e];
            }
          }
        }
      }
    } else {
      const temps = value ? value.split(',') : null;
      if (temps && temps.length === 2) {
        r = [moment(temps[0]), moment(temps[1])];
      }
    }
    return r;
  }
  return null;
}

export function getGroupByQueryFields(fields, groups, parentId, parent, list) {
  if (groups && groups.length) {
    const tempGroups = groups.filter(t => t.PARENT_ID === parentId);
    if (tempGroups && tempGroups.length) {
      tempGroups.forEach(t => {
        const group = {
          rules: [],
          childGroups: [],
          isAnd: t.RELATION_TYPE !== 1,
        };
        if (fields && fields.length) {
          const tempFields = fields.filter(t1 => t1.USER_C_C_QUERY_GROUP_ID === t.ID);
          if (tempFields && tempFields.length) {
            group.rules = getRulesByQueryFields(tempFields, group.childGroups);
          }
        }
        if (parent) {
          parent.childGroups.push(group)
        } else {
          list.push(group);
        }
        getGroupByQueryFields(fields, groups, t.ID, group, list);
      });
    }
  }
}

export function getRuleAndGroupsByQueryFields(queryFields, queryGroups) {
  const result = {};
  if (queryFields != null && queryFields.length) {
    const sysFields = queryFields.filter(t => !t.USER_C_C_QUERY_GROUP_ID);
    result.groups = [];
    result.rules = getRulesByQueryFields(sysFields, result.groups);
    getGroupByQueryFields(queryFields, queryGroups, null, null, result.groups);
  }
  return result;
}

export function getRulesByQueryFields(queryFields, groupList) {
  if (queryFields && queryFields.length) {
    const result = [];
    queryFields.forEach(t => {
      if (t.DATA_VALUE === null || t.DATA_VALUE === undefined || t.DATA_VALUE === '') return;
      // dataType-controlType
      // 5-10: 时分秒区间组件 9-18：月份 10-19：月份区间 12-20：年份 13-20：年份区间 15-22：年月日时分秒区间 16-23：年月日时分区间 17-2：日期选择
      if (
        t.DATA_TYPE === 5 ||
        t.DATA_TYPE === 9 ||
        t.DATA_TYPE === 10 ||
        t.DATA_TYPE === 12 ||
        t.DATA_TYPE === 13 ||
        t.DATA_TYPE === 15 ||
        t.DATA_TYPE === 16 ||
        t.DATA_TYPE === 17
      ) {
        const tmps = getParseValueByDate(t.DATA_VALUE);
        if (tmps != null && tmps.length) {
          if (t.IS_CUSTOM) {
            const vas = tmps.map((time, timeIndex) => {
              return timeIndex === 0 ? moment(time).format('YYYY-MM-DD') : moment(moment(time).format('YYYY-MM-DD')).add(1, 'd').subtract(1, 's').format('YYYY-MM-DD HH:mm:ss')
            })
            // 将 2020-07-18 格式化成 2020-07-01 月份开始的时间
            const monthFormat = moment(moment(vas[0]).format('YYYY-MM')).format('YYYY-MM-DD')
            const monthEndFormat = moment(moment(vas[1]).format('YYYY-MM')).format('YYYY-MM-DD')
            // 将 2020-07-18 格式化成 2020-01-01 月份开始的时间
            const yearFormat = moment(moment(vas[0]).format('YYYY')).format('YYYY-MM-DD')
            const yearEndFormat = moment(moment(vas[1]).format('YYYY')).format('YYYY-MM-DD')
            // 年月日时分或者秒控件
            const dateHMOrS = tmps.map(item => {
              if (t.DATA_TYPE === 15) {
                // 年月日时分秒控件
                return moment(item).format('YYYY-MM-DD HH:mm:ss')
              }
              // 将 2020-07-18 18:24:15 格式化成 2020-07-18 18:24:00 开始的时间
              return moment(moment(item).format('YYYY-MM-DD HH:mm')).format('YYYY-MM-DD HH:mm:ss')
            })
            let dateVal = vas.join(',')
            switch (t.DATA_TYPE) {
              case 9:
                dateVal = monthFormat
                break
              case 10:
                dateVal = [monthFormat, monthEndFormat].join(',')
                break
              case 12:
                dateVal = yearFormat
                break
              case 13:
                dateVal = [yearFormat, yearEndFormat].join(',')
                break
              case 15:
              case 16:
                dateVal = dateHMOrS.join(',')
                break
              case 17:
                dateVal = vas[0]
                break
              default:
                break
            }
            result.push({
              field: t.QUERY_NAME,
              operator: 0,
              value: dateVal,
              isCustom: t.IS_CUSTOM,
              isSysParam: t.IS_SYS_PARAM,
            });
          } else {
            let tempList = result;
            const group = {
              isAnd: true,
              rules: [],
            };
            if (groupList) {
              groupList.push(group);
              tempList = group.rules;
            }
            tmps.forEach((j, k) => {
              const tmpVal = k === 0 ? moment(j).format('YYYY-MM-DD') : moment(moment(j).format('YYYY-MM-DD')).add(1, 'd').subtract(1, 's').format('YYYY-MM-DD HH:mm:ss')
              const monthVal = moment(moment(j).format('YYYY-MM')).format('YYYY-MM-DD')
              const yearVal = moment(moment(j).format('YYYY')).format('YYYY-MM-DD')
              const dateHMS = moment(j).format('YYYY-MM-DD HH:mm:ss') // 15 精确到年月日时分秒
              const dateHM = moment(j).format('YYYY-MM-DD HH:mm') // 16 精确到年月日时分
              tempList.push({
                field: t.QUERY_NAME,
                operator: k === 0 ? '6' : '4',
                value: t.DATA_TYPE === 5 || t.DATA_TYPE === 17 ? (t.DATA_TYPE === 16 ? dateHM : t.DATA_TYPE === 15 ? dateHMS : tmpVal) : (t.DATA_TYPE === 9 || t.DATA_TYPE === 10 ? monthVal : yearVal),
                isCustom: t.IS_CUSTOM,
                isSysParam: t.IS_SYS_PARAM
              })
            });
          }
        }
      }
      else if (t.DATA_TYPE === 3 || t.DATA_TYPE === 2) { // 枚举 数值
        result.push({
          field: t.QUERY_NAME,
          operator: t.OP_DEFAULT ? t.OP_DEFAULT : '1',
          value: (+t.DATA_VALUE),
          isCustom: t.IS_CUSTOM,
          isSysParam: t.IS_SYS_PARAM,
        })
      }
      else if (t.DATA_TYPE === 4) { // 布尔
        result.push({
          field: t.QUERY_NAME,
          operator: t.OP_DEFAULT ? t.OP_DEFAULT : '1',
          value: (t.DATA_VALUE && t.DATA_VALUE == 'true' ? true : false),
          isCustom: t.IS_CUSTOM,
          isSysParam: t.IS_SYS_PARAM,
        })
      }
      else if (t.DATA_TYPE === 6) { // 下拉多选
        let temps = [];
        if (t.DATA_VALUE.toString().indexOf(',') > -1) {
          temps = t.DATA_VALUE.toString().split(',');
        } else if (t.DATA_VALUE.toString().indexOf('_') > -1) {
          const tmp = t.DATA_VALUE.toString().split('_');
          tmp.forEach((n, i) => {
            if (n !== '')
              temps.push(n);
          });
        }

        let tempList = result;
        const group = {
          isAnd: false,
          rules: [],
        };
        if (groupList) {
          groupList.push(group);
          tempList = group.rules;
        }
        temps.forEach((j, k) => {
          tempList.push({
            field: t.QUERY_NAME,
            operator: "1",
            value: j,
            isCustom: t.IS_CUSTOM,
            isSysParam: t.IS_SYS_PARAM,
          })
        });
      }
      else {
        result.push({
          field: t.QUERY_NAME,
          operator: t.OP_DEFAULT ? t.OP_DEFAULT : '9',
          value: t.DATA_VALUE,
          isCustom: t.IS_CUSTOM,
          isSysParam: t.IS_SYS_PARAM,
        })
      }
    });
    return result;
  }
}

export function locationQuery(query) {
  if (!query) return {};
  let querys = query.split('?')[1];
  let pair = querys.split('&');
  let obj = {};
  for (let i = 0; i < pair.length; i++) {
    let propertys = pair[i].split('=');
    obj[propertys[0]] = propertys[1]
  }
  return obj;
}

export function getRuleAndGroupByParseValue({
  ruleJson,
  field,
  operator,
  value,
  user,
  isCustom,
  getHeadFieldValueFunc,
  getRecordFieldValueFunc
}) {
  if (isCustom) { //自定义字段
    if (value.indexOf('{now') > -1) {
      const temps = getParseValueByDate(value);
      let vas = '';
      temps.forEach((j, k) => {
        const v = k === 0 ? moment(j).format('YYYY-MM-DD') : moment(moment(j).format('YYYY-MM-DD')).add(1, 'd').subtract(1, 's').format('YYYY-MM-DD HH:mm:ss');
        vas += v + ",";
      });
      if (ruleJson && ruleJson.rules) {
        ruleJson.rules.push({
          field,
          operator,
          value: vas,
          isCustom: isCustom,
        });
      }
    } else {
      if (ruleJson && ruleJson.rules) {
        ruleJson.rules.push({
          field,
          operator,
          value: getParseValue(value, user, getHeadFieldValueFunc, getRecordFieldValueFunc),
          isCustom: isCustom,
        });
      }
    }
  } else {
    if (value.indexOf('{now') > -1) {
      if (ruleJson) {
        const groups = ruleJson.groups ? ruleJson.groups : ruleJson.childGroups;
        if (groups) {
          const group = {
            isAnd: true,
            rules: [],
          };
          groups.push(group);
          const temps = getParseValueByDate(value);
          temps.forEach((j, k) => {
            group.rules.push({
              field,
              operator: (k === 0 ? '6' : '4'),
              value: (k === 0 ? moment(j).format('YYYY-MM-DD') : moment(moment(j).format('YYYY-MM-DD')).add(1, 'd').subtract(1, 's').format('YYYY-MM-DD HH:mm:ss')),
              isCustom: isCustom,
            });
          });
        }
      }
    } else {
      if (ruleJson && ruleJson.rules) {
        ruleJson.rules.push({
          field,
          operator,
          value: getParseValue(value, user, getHeadFieldValueFunc, getRecordFieldValueFunc),
          isCustom: isCustom,
        });
      }
    }
  }
}

export function addChildGroups(list, group) {
  if (list && list.length) {
    list.forEach(t => {
      const tempGroup = initFilterGroup(t.isAnd);
      if (t.rules && t.rules.length) {
        t.rules.forEach(t1 => {
          extendGroupRule(tempGroup, t1.field, t1.operator, t1.value, t1.isSysParam);
        });
      }
      if (t.childGroups && t.childGroups.length) {
        addChildGroups(t.childGroups, tempGroup);
      }
      extendChildGroup(group, tempGroup);
    });
  }
}

export function getRandomCode(len) {
  len = len || 32;
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678=-*&@#$%!~+,./?\;:|'    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length;
  var pwd = '';
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

export function addRuleAndGroups(json, ruleAndGroupJson) {
  if (json && ruleAndGroupJson) {
    if (ruleAndGroupJson.rules && ruleAndGroupJson.rules.length) {
      ruleAndGroupJson.rules.forEach(t => {
        if (t.isCustom) { //自定义字段

          if (t.field.indexOf(',') > -1) //modify by陈昌雨 2020/6/4
          {
            var splitFileds = t.field.split(',');
            let values = null;
            if (typeof (t.value) === 'number' && t.value !== undefined && t.value != null) {
              values = t.value.toString().split(',');
            } else {
              values = t.value.split(',');
            }

            if (splitFileds && values) {
              splitFileds.forEach((n, i) => {
                json[n] = values[i];
              });
            }
          }
          else {
            json[t.field] = t.value;
          }


        }
        else {
          extendRule(json, t.field, t.operator, t.value, t.isSysParam);
        }
      });
    }

    if (ruleAndGroupJson.groups && ruleAndGroupJson.groups.length) {
      ruleAndGroupJson.groups.forEach(t => {
        const tempGroup = initFilterGroup(t.isAnd);
        if (t.rules && t.rules.length) {
          t.rules.forEach(t1 => {
            extendGroupRule(tempGroup, t1.field, t1.operator, t1.value, t1.isSysParam);
          });
        }
        if (t.childGroups && t.childGroups.length) {
          addChildGroups(t.childGroups, tempGroup);
        }
        extendFilterGroup(json, tempGroup);
      });
    }
    if (ruleAndGroupJson.orgType) {
      json.OrgType = ruleAndGroupJson.orgType;
    }
    if (ruleAndGroupJson.menuParameter) {
      json.MenuParameter = ruleAndGroupJson.menuParameter
    }
  }
}

export function constructStandardTreeData(data, cascader) {
  data.forEach(item => {
    const { Node, Children } = item
    const { NAME, ID } = Node
    if (cascader) {
      item.label = NAME
      item.value = ID
      Array.isArray(Children) && Children.length && (item.children = Children)
      for (let key in Node) {
        item[key] = Node[key]
      }
    } else {
      item.title = NAME
      item.key = ID
      item.value = ID
      item.children = Children
    }
    if (Array.isArray(Children) && Children.length) {
      constructStandardTreeData(Children, cascader)
    }
  })
}

export function renderExportCell(text, record = [], config, enums) {
  if (config) {
    const { enumName } = config
    if (enumName) {
      return enums[enumName] && enums[enumName].enums ? (enums[enumName].enums[text] || text) : text
    }
    if (config.isBool || config.controlType === 101) {
      text = text ? '是' : '否'
    }
    else if (config.isDate || config.controlType === 102) {//日期
      text = text.toString().substring(0, 10)
    }
    // 显示日期根据控件类型格式化
    else if (config.controlType === 2) {
      moment(text).isValid() && (text = moment(text).format('YYYY-MM-DD'))
    }
    else if (config.controlType === 8) {
      moment(text).isValid() && (text = moment(text).format('HH:mm:ss'))
    }
    else if (config.controlType === 10) {
      const dates = (text || '').split(',')
      if (moment(dates[0]).isValid() && moment(dates[1]).isValid()) {
        text = [moment(dates[0]).format('YYYY-MM-DD'), moment(dates[1]).format('YYYY-MM-DD')].join(',')
      }
    }
    else if (config.controlType === 18) {
      moment(text).isValid() && (text = moment(text).format('YYYY-MM'))
    }
    else if (config.controlType === 19) {
      const months = (text || '').split(',')
      if (moment(months[0]).isValid() && moment(months[1]).isValid()) {
        text = [moment(months[0]).format('YYYY-MM'), moment(months[1]).format('YYYY-MM')].join(',')
      }
    }
    // 分页下拉
    else if (config.controlType === 9) {
      if (Array.isArray(record) && record.length) {
        const values = (text || '').split(',')
        const texts = []
        values.forEach(item => {
          const findNode = record.find(rec => rec.ID === item)
          findNode && texts.push(`${findNode.CODE}-${findNode.NAME}`)
        })
        if (texts.length) return texts.join(',')
      }
    }
    // 下拉树选择、级联选择
    else if (config.controlType === 11 || config.controlType === 17) {
      if (Array.isArray(record) && record.length) {
        const valueArr = (text || '').split(',')
        // 级联选择，取最叶子节点
        const values = config.controlType === 17 ? [valueArr[valueArr.length - 1]] : valueArr
        const texts = []
        function matchVal(target, source, result) {
          for (let i = 0, j = source.length; i < j; i++) {
            const { title, label, value, children } = source[i]
            if (value === target) {
              result.push(title || label)
            }
            if (Array.isArray(children) && children.length) matchVal(target, children, result)
          }
        }
        values.forEach(item => matchVal(item, record, texts))
        if (texts.length) return texts.join(',')
      }
    }
  }
  return text
}

// 树搜索
export function flatTreeData(tree = [], data = []) {
  if (Array.isArray(tree) && tree.length) {
    tree.forEach(item => {
      data.push(omit(item, ['children']))
      flatTreeData(item.children, data)
    })
  }
}

export function digTreeData(arr, target) {
  for (let i = 0, j = arr.length; i < j; i++) {
    if (arr[i].Node && arr[i].Node.ID === target) return arr[i]
    if (Array.isArray(arr[i].Children) && arr[i].Children.length) {
      const result = digTreeData(arr[i].Children, target)
      if (result) return result
    }
  }
}

export function toFixed(num, base = 2, notCeil = true) {
  if (typeof num !== 'number') return num
  let str = num.toFixed(notCeil ? base + 1 : base)
  base === 0 && notCeil && (str = str.substring(0, str.length - 1)) // 防止出现 120. 这类多一个点的字符串
  return str.substring(0, notCeil ? str.length - 1 : str.length)
}
//排序
export function compare(obj1, obj2) {
  var val1 = obj1.num;
  var val2 = obj2.num;
  if (val1 < val2) {
    return -1;
  } else if (val1 > val2) {
    return 1;
  } else {
    return 0;
  }
}

export function validUUID(value) {
  if (!value) return false
  if (value.toString().split('-').length === 4 && value.toString().length === 32) return true
  if (value.toString().split('-').length === 5 && value.toString().length === 36) return true
  return false
}

//结束任务
export function endTask(orgId, taskID, dispatch) {
  let jsonEndTask = initFilter(orgId, taskID);
  dispatch({
    type: 'app/getDataByPost',
    payload: jsonEndTask,
    async: true,
    url: 'FM/FMNotificationTask/ChangeStatus',
    onComplete: (ret) => {
      if (ret) {
      }
    }
  });
}

//显示审批人签名信息
export function showApprove(listApproveDetail, enums, imgHost, width, height) {
  // 调用方法钱得自己排序
  var result = []
  if (width == undefined) { width = 200 }
  if (height == undefined) { height = 65 }

  //排序 debugger
  if (listApproveDetail != null && listApproveDetail.length > 1) {
    for (let j = 1; j < listApproveDetail.length; j++) {
      for (let i = 1; i < listApproveDetail.length; i++) {
        if (listApproveDetail[i - 1].NUM > listApproveDetail[i].NUM) {
          let temp = listApproveDetail[i - 1]
          listApproveDetail[i - 1] = listApproveDetail[i]
          listApproveDetail[i] = temp
        }
      }
    }
  }

  // height={height}
  listApproveDetail?.map((item, i) => {
    if (item.NODE_APPROVE_STATUS == 0) {
      // result.push((i > 0 ? ";" : "") + item.NAME + ":" + (item.Nav_ApproveUser != null ? item.Nav_ApproveUser.NAME : "") + "(" + enums[item.NODE_APPROVE_STATUS] + ")")
    } else {
      // result.push(<a>{item.NAME + ":" + "(" + enums[item.NODE_APPROVE_STATUS] + ")" + (item.CONTEXT == null ? "" : item.CONTEXT)}<img width={200} height={100} style={{ margin: "0 0 0 5px" }} src={imgHost + item.Nav_ApproveUser.Nav_UserSignFiles[0].Nav_ImgFile.Nav_File.FILE_PATH} alt={item.Nav_ApproveUser != null ? item.Nav_ApproveUser.NAME : ""} /></a>)
      var url = '#'
      if (item.Nav_ApproveUser?.Nav_UserSignFiles != null && item.Nav_ApproveUser?.Nav_UserSignFiles.length > 0) {
        if (item.Nav_ApproveUser?.Nav_UserSignFiles[0].Nav_ImgFile?.Nav_File?.FILE_PATH) {
          url = imgHost + item.Nav_ApproveUser?.Nav_UserSignFiles[0].Nav_ImgFile.Nav_File.FILE_PATH;
        }
      }
      if (i == 0) {
        result.push(
          <div style={{ height: height }}>
            <div style={{ float: 'left' }}>
              <div style={{ marginTop: '5px', marginLeft: '5px' }}>
                {item.NAME}
                <br />
                审批结论：{item.CONTEXT == undefined ? "" : item.CONTEXT}
                <br />
                审核时间：{item.NODE_APPROVE_TIME}
              </div>
            </div>
            <div style={{ float: 'left', marginLeft: '5%' }}>
              <img width={width} style={{
                margin: "0 0 0 5px", maxHeight: "80px", borderWidth: '0px', borderborderColor: 'wheat'
              }} src={url} alt={item.Nav_ApproveUser != null ? item.Nav_ApproveUser.NAME : ""}
                title={item.Nav_ApproveUser != null ? item.Nav_ApproveUser.NAME : ""}
              // onError={(e) => {
              //   e.target.src = require('../assets/home/backlog.png');
              // }}
              />
            </div>
          </div>
        )
      } else {
        result.push(
          <div style={{ height: height }}>
            <hr style={{ border: '1px dashed rgb(204, 204, 204)' }} />
            <div style={{ float: 'left' }}>
              <div style={{ marginTop: '5px', marginLeft: '5px' }}>
                {item.NAME}
                <br />
                审批结论：{item.CONTEXT == undefined ? "" : item.CONTEXT}
                <br />
                审核时间：{item.NODE_APPROVE_TIME}
              </div>
            </div>
            <div style={{ float: 'left', marginLeft: '5%' }}>
              <img width={width} style={{ margin: "0 0 0 5px", maxHeight: height, borderWidth: '0px', borderborderColor: 'wheat' }} title={item.Nav_ApproveUser != null ? item.Nav_ApproveUser.NAME : ""} src={url} alt={item.Nav_ApproveUser != null ? item.Nav_ApproveUser.NAME : ""}
              // onError={(e) => {
              //   e.target.src = require('../assets/home/backlog.png');
              // }}
              />
            </div>
          </div>
        )
      }
      // result.push(<a>{(item.CONTEXT == null ? "" : item.CONTEXT)}<img width={width} style={{ margin: "0 0 0 5px", maxHeight: "100px" }} src={url} alt={item.Nav_ApproveUser != null ? item.Nav_ApproveUser.NAME : ""} /></a>)
    }
  })
  return result
}

//显示用户签名
export function showUsersSign(listUsers, imgHost, width, height) {
  var result = []
  if (width == undefined) { width = 200 }
  if (height == undefined) { height = 50 }
  if (listUsers != null && listUsers.length > 0) {
    listUsers = listUsers.sort(function (a, b) {
      // if (a.CREATE_TIME > b.CREATE_TIME) {//很经常创建时间一样 签名会随机动态变位置
      if (a.MODIFY_TIME > b.MODIFY_TIME) {
        return 1
      } else {
        return -1
      }
    })
  }
  listUsers?.map((item, i) => {
    if (item.Nav_User != null && item.Nav_User.Nav_UserSignFiles != null && item.Nav_User.Nav_UserSignFiles.length > 0) {
      result.push(<img width={width} style={{ margin: "0 0 0 5px", maxHeight: height }} src={imgHost + item.Nav_User?.Nav_UserSignFiles[0]?.Nav_ImgFile.Nav_File.FILE_PATH}
        title={item.Nav_User?.NAME} alt={item.Nav_User?.NAME} />)
    } else if (item.Nav_UserSignFiles != null && item.Nav_UserSignFiles.length > 0) {
      result.push(<img width={width} style={{ margin: "0 0 0 5px", maxHeight: height }} src={imgHost + item.Nav_UserSignFiles[0]?.Nav_ImgFile.Nav_File.FILE_PATH}
        title={item?.NAME} alt={item?.NAME} />)
    }
    else {
      result.push(<img width={width} style={{ margin: "0 0 0 5px", maxHeight: height }} src=''
        title={item.Nav_User?.NAME} alt={item.Nav_User?.NAME} />)
    }
  })
  return result
}
//显示用户签名
export function showUserSign(user, imgHost, width, height, extShowTimeText) {
  var result = []
  if (width == undefined) { width = 200 }
  if (height == undefined) { height = 50 }
  // height={height}
  if (user != null && user.Nav_UserSignFiles != null && user.Nav_UserSignFiles.length > 0) {
    result.push(<img width={width} style={{ margin: "0 0 0 5px", maxHeight: height }} src={imgHost + user?.Nav_UserSignFiles[0]?.Nav_ImgFile.Nav_File.FILE_PATH} title={user.NAME} alt={user.NAME} />)
  } else {
    result.push(<img width={width} style={{ margin: "0 0 0 5px", maxHeight: height }} src='' title={user.NAME} alt={user.NAME} />)
  }

  if (extShowTimeText) {
    result.push(<span style={{ marginLeft: '20px' }}>{extShowTimeText}</span>)
  }

  return result
}

//显示参会人（前端map不好去除，）
export function showJoinsHtml(arry, isTaskCheck, STATUS) {
  if (arry != null && arry != undefined && arry.length > 0) {
    let arryResult = []
    let j = 0
    arry.map((item, i) => {
      if ((item.PERSONNATURE == null || item.PERSONNATURE == 10) && (item.PERSONTYPE == 10 || item.PERSONTYPE == 40)) {//评审人 可能也加入到 参会人员中  || item.PERSONTYPE == 40
        if (!isTaskCheck && (STATUS == 0 || STATUS == 20)) {
          arryResult.push((j > 0 ? "，" : "") + item.Nav_User.NAME)
        } else {
          // 人员 参会反馈情况 有 黑色 无 红色
          arryResult.push((<a style={{ color: ((item.JOINRESULT == undefined || item.JOINRESULT == null) ? "red" : "black") }}> {(j > 0 ? "，" : "") + item.Nav_User.NAME}</a>))
        }
        j++
      }
    })

    // if(arryResult[0].substring(0,1)=='，'){
    //   arryResult[0]=arryResult[0].substring(1)
    // }
    return arryResult
  } else {
    return ''
  }
}

//判断是PC还是移动端
export function getIsPC() {
  if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/WebOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/Windows Phone/i)) {
    return false
  } else {
    return true
  }
}

//task未空的onBeforeSaveHandleRecord事件日志
export function onBeforeSaveHandleRecordLog(params, formCode, title) {
  if (params.data.TaskID == '00000000-0000-0000-0000-000000000000' || params.data.id == '00000000-0000-0000-0000-000000000000') {
    var orgId = params.login.OrgId;   //登录后有存储登录信息
    let json = initFilter(orgId, null, null, null, null, formCode, title, params.data.TaskID, " params.pageCode:[" + params.pageCode + "] params.data.id:[" + params.data.id + "] UserId:[" + params.login.loginInfo.User.ID + "] params.data.taskCode: [" + params.data.taskCode + "] homeReload: [" + params.data.homeReload + "]");
    params.dispatch({
      type: 'app/getDataByPost',
      url: 'PF/PFSysLog/addLog',
      payload: json,
      onlyData: false,
      onComplete: (ret) => { }
    })
  }
}

//显示附件
export function showFiles(Nav_Files, imgHost, isShowNO, maxShow = 50) {
  var result = []
  var fileName = ''
  Nav_Files && Nav_Files?.map((item, i) => {
    fileName = item.Nav_ImgFile.FILE_NAME
    if (maxShow && maxShow > 3 && fileName.length > maxShow) {
      fileName = fileName.substring(0, maxShow - 3) + '......'
    }
    if (isShowNO) {
      result.push(<a width={'20%'} title={item.Nav_ImgFile.FILE_NAME} target='_blank' href={imgHost + item.Nav_ImgFile.Nav_File.FILE_PATH} >{(++i) + "、" + fileName + '  '} </a>)
    } else {
      result.push(<a width={'20%'} title={item.Nav_ImgFile.FILE_NAME} target='_blank' href={imgHost + item.Nav_ImgFile.Nav_File.FILE_PATH} >{fileName} </a>)
    }
  })
  return result
}

export function ShowDateTime(datetime, fmt) {
  if (datetime == undefined || datetime == null || datetime.length < 1) {
    return ''
  } else {
    if (fmt == undefined || fmt == null || fmt.length < 1)
      fmt = 'yyyy-MM-dd'
    return new Date(datetime).Format(fmt)
  }
}

export function downLoad(imgHost, fileName) {
  if (fileName) {
    let link = document.createElement('a')
    link.href = imgHost + '/' + fileName
    document.body.appendChild(link)
    window.open(link)
  } else {
    alert('获取参数配置失败！')
  }
}

Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份 
    "d+": this.getDate(), //日 
    "D+": this.getDate(), //日 //wyw 时间格式
    "H+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}


export function ShowPrintClose(props) {
  if (typeof props.data.onCancel != "undefined" && typeof props.data.onCancel == 'function')
    props.data.onCancel();
}


//饼图展示 wyw  (安全检查情况占比)
//legendData, seriesData 数据类型参考方法体
export function ChartPieShow(echarts, divId, title, legendData, seriesData, tooltipFormatter) {

  //添加缺省参数案例
  if (tooltipFormatter == undefined || tooltipFormatter == null)
    tooltipFormatter = '{b} : {c} ({d}%)'

  var element = document.getElementById(divId)
  if (element != undefined) {
    var myChart = echarts.init(element);
    var option = {
      title: {
        text: title,
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: tooltipFormatter
      },
      legend: {
        // orient: 'vertical',  // left: 'left',
        type: 'scroll',
        top: 50,
        data: legendData //['综合检查', '例行检查', '巡回检查', '专业检查', '日常巡检']
      },
      series: [
        {
          type: 'pie',
          radius: '55%',
          center: ['50%', '50%'],
          data: seriesData,
          // [
          //   { value: 335, name: '直接访问' },
          //   { value: 310, name: '邮件营销' },
          //   { value: 234, name: '联盟广告' },
          //   { value: 135, name: '视频广告' },
          //   { value: 1548, name: '搜索引擎' }
          // ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
  }
}


//柱状图  （班组安全检查完成率分析）
export function ChartColumnShow(echarts, divId, title, xAxisData, seriesDataFinish, seriesDataNotFinish, tooltipFormatter) {
  var element = document.getElementById(divId)
  if (element != undefined) {
    var myChart = echarts.init(element);

    //添加缺省参数案例
    if (tooltipFormatter == undefined || tooltipFormatter == null)
      tooltipFormatter = '{b} : {c} '
    var option = {
      title: {
        text: title,
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: tooltipFormatter
      },

      /***横向排列***/
      yAxis: {
        data: xAxisData
      },
      xAxis: {},
      series: [
        {
          type: 'bar',
          stack: 'total',
          data: seriesDataFinish,// [320, 302, 301, 334, 390, 330, 320]
          label: {
            show: true,
            //  formatter:'{c0/(c0+c1)}%'
          }
        },
        {
          type: 'bar',
          stack: 'total',
          data: seriesDataNotFinish,// [120, 132, 101, 134, 90, 230, 210]  
          label: {
            show: true,
          }
        },
      ],
    }
  };

  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);
}


export function openNotificationMobile(placement, notification) {
  notification.info({
    duration: 20,
    message: `友情提示：`,
    description:
      '您当前用的是手机在访问，为有更好体验，建议使用电脑访问！',
    placement,
  });
}


export function auditOptionShow(stateData, dataState, stateReject, propName, dataId, dispatch, setFieldVisible) {
  if (propName == undefined || propName == null) {
    propName = "AUDIT_OPINION"
  }
  if (dataState == stateReject) {
    dispatch({
      type: 'app/getDataByPost',
      url: 'HM/HMHazardRecord/GetRejectContent',
      payload: {
        ID: dataId,
      },
      onComplete: (ret) => {
        // setFieldValue(propName, ret)
        stateData[propName] = ret // dataState.AUDIT_OPINION = ret
        return ret
      }
    });
  } else {
    setFieldVisible(propName, false);
  }
}

export function auditOptionShow2(stateData, dataState, stateReject, propName, dataId, dispatch, setFieldVisible) {
  if (propName == undefined || propName == null) {
    propName = "AUDIT_OPINION"
  }
  if (dataState == stateReject) {
    dispatch({
      type: 'app/getDataByGet',
      url: 'PF/PFApprove/GetRejectContentByAPPID',
      //url: 'PF/PFApprove/GetRejectContent?ApproveID=' + dataId,
      payload: {
        ApproveID: dataId,
      },
      onComplete: (ret) => {
        stateData[propName] = ret
        return ret
      }
    });
  } else {
    setFieldVisible(propName, false);
  }
}