import { Spin } from "antd";
import { WeaSwitch } from "comsMobx";
import { WeaAlertPage, WeaFormItem, WeaHelpfulTip, WeaLocaleProvider, WeaSearchGroup } from "ecCom";

const getLabel = WeaLocaleProvider.getLabel;

// 获取condition的domKey值
export const getConditionDomkeys = (condition) => {
  let domkeyList = [];
  _.forEach(condition, item => {
    const tmpV = _.reduce(item.items, (pre, cur) => {
      return [...pre, cur["domkey"][0]];
    }, []);
    domkeyList = domkeyList.concat(tmpV);
  });
  return domkeyList;
};
// 获取condition的field集合
export const getConditionFields = (condition) => {
  return _.reduce(condition, (pre, cur) => {
    return {
      ...pre,
      ..._.reduce(cur.items, (pre1, cur1) => ({ ...pre1, [cur1["domkey"][0]]: cur1 }), {})
    };
  }, {});
};

// 渲染form表单: 一般对form的渲染都统一使用该方法
export const getSearchs = (form, condition, col, isCenter, onChange = () => void (0), title, classnames = "") => {
  const { isFormInit } = form;
  const formParams = form.getFormParams();
  let group = [];
  isFormInit && condition && condition.map(c => {
    let items = [];
    c.items.map(fields => {
      items.push({
        com: (
          <WeaFormItem
            label={<span>
              <span>{`${fields.label}`}</span>
              {
                fields.labelExtra && <span className="wea-form-item-label-extra"
                                           onClick={() => onChange(fields.labelType)}>{fields.labelExtra}</span>
              }
            </span>} // label 标签的文本
            labelCol={{ span: `${fields.labelcol}` }} // label标签占一行比例
            wrapperCol={{ span: `${fields.fieldcol}` }} // 右侧控件占一行比例
            error={form.getError(fields)} // 错误提示: 处理表单中有必填项,保存的校验
            tipPosition="bottom" // 错误提示的显示位置: top/bottom
            className={(fields.domkey[0] === "subcompanyName" || fields.domkey[0] === "departmentName") ? "hideFormItem" : classnames}
          >
            <WeaSwitch fieldConfig={fields} form={form} formParams={formParams} onChange={onChange}/>
            {
              fields.helpfulTitle &&
              <WeaHelpfulTip title={fields.helpfulTitle} style={{ position: "absolute", right: "-20px", top: "25%" }}/>
            }
          </WeaFormItem>),
        colSpan: 1,
        hide: fields.hide
      });
    });
    group.push(
      <WeaSearchGroup
        col={col || c.col || 1} // 高级搜索列布局列数
        needTigger={true} // 是否开启收缩
        title={c.title || title} // 高级搜索标题
        showGroup={c.defaultshow} // 是否开启面板
        items={items} // 条目数组数据
        center={isCenter || false} // 内容是否居中：一般弹框需要
      />);
  });
  return group;
};

// 页面加载中效果处理
export const renderLoading = (loading) => (
  <div className="wea-demo-loading">
    <Spin spinning={loading}/>
  </div>
);

// 无权限处理
export const renderNoright = () => (
  <WeaAlertPage>
    <div>
      {getLabel(2012, "对不起，您暂时没有权限！")}
    </div>
  </WeaAlertPage>
);

// 暂无数据处理
export const renderNoData = () => (
  <WeaAlertPage>
    <div>
      暂无数据
    </div>
  </WeaAlertPage>
);

//分页计算
export function calcPageNo(total, pageNo = 1, pageSize = 10, selectDelDataLen = 1) {
  const totalPage = Math.ceil((total - selectDelDataLen) / pageSize); // 总页数
  pageNo = pageNo > totalPage ? totalPage : pageNo;
  pageNo = pageNo < 1 ? 1 : pageNo;
  return pageNo;
}

//金额格式化
export const format_with_regex = (number) => {
  return !(number + "").includes(".")
    ? // 就是说1-3位后面一定要匹配3位
    (number + "").replace(/\d{1,3}(?=(\d{3})+$)/g, (match) => {
      return match + ",";
    })
    : (number + "").replace(/\d{1,3}(?=(\d{3})+(\.))/g, (match) => {
      return match + ",";
    });
};

export const getDomkes = (conditions) => {
  return _.reduce(conditions, (pre, cur) => ([...pre, ..._.map(cur.items, o => o.domkey[0])]), []);
};

export const padding0 = (num, length) => {
  for (let len = ("" + num).length; len < length; len++) {
    num = "0" + num;
  }
  return "0." + num;
};
export const toDecimal_n = (num, decimalPlaces) => {
  if (num === null || !isFinite(num)) return null;
  if (decimalPlaces < 0) return null;
  const multiplier = Math.pow(10, decimalPlaces);
  const roundedNum = Math.round(num * multiplier) / multiplier;
  return roundedNum.toFixed(decimalPlaces);
};
//设置ifrme高度
export const getIframeParentHeight = (selector, total, extraHeight) => {
  const dom = document.querySelector(selector);
  let height = 280;
  if (dom && total > 0) {
    height = (parseFloat(dom.style.height) > 620 && total === 10) ? total * 48 + 108 : total < 10 ? (total + 1) * 48 + 108 : parseFloat(dom.style.height) - extraHeight;
  }
  return height;
};
export const removeElementById = (id) => {
  const element = document.getElementById(id);
  if (element) element.remove();
};
