/*
 * Author: 黎永顺
 * Description: 预留编号设置
 * Date: 2022-06-08 09:53:51
 * LastEditTime: 2022-06-15 11:00:55
 */
import React, { Component } from "react";
import { Row, Col, Spin, Modal, Button, Alert, message } from "antd";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { i18n } from "../../../../public/i18n";
import {
  WeaTab,
  WeaButtonIcon,
  WeaFormItem,
  WeaDialog,
  WeaMoreButton,
  WeaSearchGroup,
} from "ecCom";
import { WeaSwitch, WeaTableNew } from "comsMobx";

const WeaTable = WeaTableNew.WeaTable;

@inject("numberSet")
@observer
class ReservedNumberSetting extends Component {
  constructor() {
    super();
    this.state = {
      addVisible: false,
      showSearchAd: false,
      reservedcode: "",
      previewStr: "",
      date: "",
    };
  }
  componentWillReceiveProps(nextProps) {
    const { numberSet, onChangeAddVisible } = this.props;
    const { reservedForm } = numberSet;
    if (nextProps.addVisible !== this.props.addVisible) {
      !nextProps.addVisible &&
        this.setState({ addVisible: false }, () => {
          reservedForm.reset();
          onChangeAddVisible && onChangeAddVisible();
        });
    }
  }
  /**
   * name:渲染搜索栏
   * return {*}
   */
  getPanelComponents = () => {
    const { numberSet } = this.props;
    const { searchCondition, form } = numberSet;
    let colList = [];
    const { isFormInit } = form;
    isFormInit &&
      searchCondition.map((c) => {
        c.items.map((field, index) => {
          colList.push(
            <Col
              ecId={`${(this && this.props && this.props.ecId) || ""
                }_Col@4cc308@${index}`}
              span={index % 2 == 0 ? 10 : 11}
              offset={1}>
              <div style={{ marginTop: 20 }}>
                <WeaFormItem
                  ecId={`${(this && this.props && this.props.ecId) || ""
                    }_WeaFormItem@u6ex85@${index}`}
                  label={`${field.label}`}
                  labelCol={{ span: `${field.labelcol}` }}
                  wrapperCol={{ span: `${field.fieldcol}` }}>
                  {
                    <WeaSwitch
                      ecId={`${(this && this.props && this.props.ecId) || ""
                        }_WeaSwitch@p7d3td@${index}`}
                      fieldConfig={field}
                      form={form}
                    />
                  }
                </WeaFormItem>
              </div>
            </Col>
          );
        });
      });
    return (
      <Row ecId={`${(this && this.props && this.props.ecId) || ""}_Row@ppeb6z`}>
        {colList}
      </Row>
    );
  };

  onSearchChange = (reservedcode) => {
    const { numberSet } = this.props;
    const { form } = numberSet;
    this.setState({ reservedcode });
    !_.isEmpty(form.getFormParams()) &&
      form.updateFields({
        reservedcode: {
          value: reservedcode,
        },
      });
  };
  /**
   * name: 查询
   * return {*}
   */
  handelSearch = () => {
    const { onSearchReservedNumberset } = this.props;
    onSearchReservedNumberset && onSearchReservedNumberset();
  };
  /**
   * name: 删除 预留编号
   * return {*}
   */
  handleDelete = () => {
    const { numberSet, onDeleteReservedNumber } = this.props;
    const { tableStore } = numberSet;
    const selectedKeys = toJS(tableStore.selectedRowKeys);
    Modal.confirm({
      title: "信息确认",
      content: `确定要删除选择的记录吗？`,
      onOk: () => {
        onDeleteReservedNumber &&
          onDeleteReservedNumber(selectedKeys.join(","));
      },
      onCancel: () => { },
    });
  };
  handleAddReservedNumber = () => {
    const { onAddReservedNumber } = this.props;
    this.setState({ addVisible: true }, () => {
      onAddReservedNumber && onAddReservedNumber();
    });
  };
  /**
   * name: 提交预留编号设置
   * return {*}
   */
  handleSubmitReservedNumber = () => {
    const { numberSet, onSubmitReservedNumber } = this.props;
    const { reservedForm, condition } = numberSet;
    reservedForm.validateForm().then((f) => {
      if (f.isValid) {
        const { desc: reserveddesc, flowcode: reservedcodes } =
          reservedForm.getFormParams() || {};
        if (!/(^[1-9]\d*$)/.test(reservedcodes)) {
          message.warning(`"流水号"格式不正确，请重新输入！`);
          return;
        }
        onSubmitReservedNumber &&
          onSubmitReservedNumber({
            reserveddesc,
            reservedcodes: this.state.previewStr,
          });
      } else {
        message.warning("请完善表单信息");
        f.showErrors();
        this.setState({ date: new Date() }); // 改变一个state的变量,强制页面刷新
      }
    });
  };
  /**
   * name: 新增预留编号表单渲染
   * return {*}
   */
  getReservedForm = () => {
    const { condition, reservedForm } = this.props.numberSet;
    let reservedFormItem = [];
    const { isFormInit } = reservedForm;
    isFormInit &&
      condition.map((c, i) => {
        let switchItem = [];
        c.items.map((field, index) => {
          switchItem.push({
            com: (
              <div>
                {i === condition.length - 1 && index === 0 && (
                  <div style={{ width: 280 }}>
                    <Alert
                      message="填写完上方编号组成后才会显示当前流水号"
                      type="warning"
                      showIcon
                    />
                  </div>
                )}
                <WeaFormItem
                  ecId={`${(this && this.props && this.props.ecId) || ""
                    }_WeaFormItem@merei2@${index}`}
                  label={`${field.label}`}
                  labelCol={{ span: `${field.labelcol}` }}
                  tipPosition="bottom"
                  wrapperCol={{ span: `${field.fieldcol}` }}>
                  <WeaSwitch
                    ecId={`${(this && this.props && this.props.ecId) || ""
                      }_WeaSwitch@5r6c5a@${index}`}
                    fieldConfig={field}
                    form={reservedForm}
                    formParams={reservedForm.getFormParams()}
                    onChange={this.handleFormItemChange}
                  />
                  {field.domkey[0] === "flowcode" && (
                    <p>格式为：5,6-10,21,66,99</p>
                  )}
                </WeaFormItem>
              </div>
            ),
            colSpan: 1,
          });
        });
        reservedFormItem.push(
          <WeaSearchGroup
            ecId={`${(this && this.props && this.props.ecId) || ""
              }_WeaSearchGroup@qaih5l@${i}`}
            needTigger={true}
            title={c.title}
            showGroup={c.defaultshow}
            items={switchItem}
            col={1}
          />
        );
      });

    return reservedFormItem;
  };

  /**
   * name: 输出指定个数0
   * param {*} num
   * param {*} length
   * return {*}
   */
  prefixInteger = (num, length) => {
    return (Array(length).join("0") + num).slice(-length);
  };
  /**
   * name: 字符串替换
   * param {*} str
   * param {*} index
   * param {*} char
   * return {*}
   */
  replaceStr2 = (str, index, char) => {
    return str.substring(0, index) + char;
  };

  /**
   * name: 预留编号的设置
   * param {*} formVal
   * return {*}
   */
  handleFormItemChange = (formVal) => {
    const { numberSet, onSubmitReservedNumber } = this.props;
    const { reservedForm, condition } = numberSet;
    const NumberOfData = reservedForm.getFormParams() || {};
    let previewStr = "",
      originStr = "";
    for (let i in NumberOfData) {
      if (
        i.indexOf("STRING") > -1 ||
        i.indexOf("YEAR") > -1 ||
        i.indexOf("MONTH") > -1 ||
        i.indexOf("DAY") > -1
      ) {
        originStr = originStr + NumberOfData[i];
      }
    }
    let integer_0 = this.prefixInteger(0, Number(NumberOfData["NUMBER"]));
    //预留流水号值输入
    if (_.hasIn(formVal, "flowcode")) {
      const inputValue = formVal["flowcode"].value;
      if (inputValue.length <= Number(NumberOfData["NUMBER"])) {
        previewStr =
          originStr +
          this.replaceStr2(
            integer_0,
            integer_0.length - inputValue.length,
            inputValue
          );
      } else {
        previewStr = originStr + previewStr + inputValue;
      }
      this.setState({ previewStr: inputValue ? previewStr : "" });
    } else if (
      _.hasIn(formVal, "YEAR") ||
      _.hasIn(formVal, "MONTH") ||
      _.hasIn(formVal, "DAY")
    ) {
      const { flowcode } = NumberOfData;
      if (flowcode.length <= Number(NumberOfData["NUMBER"])) {
        previewStr =
          originStr +
          this.replaceStr2(
            integer_0,
            integer_0.length - flowcode.length,
            flowcode
          );
      } else {
        previewStr = originStr + previewStr + flowcode;
      }
      this.setState({ previewStr });
    }
  };
  render() {
    const {
      showSearchAd,
      reservedcodem,
      addVisible,
      reservedcode,
      date,
      previewStr,
    } = this.state;
    const { numberSet, loading } = this.props;
    const { form, tableStore, reservedForm } = numberSet;
    return (
      <div>
        <WeaTab
          searchType={["base", "advanced"]}
          showSearchAd={showSearchAd}
          advanceHeight={200}
          setShowSearchAd={(bool) => {
            this.setState({
              showSearchAd: bool,
            });
          }}
          searchsAd={this.getPanelComponents()}
          searchsBaseValue={
            _.isEmpty(form.getFormParams())
              ? reservedcode
              : form.getFormParams().reservedcode
          }
          onSearchChange={this.onSearchChange}
          onSearch={this.handelSearch}
          onAdReset={() => form.reset()}
          onAdSearch={this.handelSearch}
          hasMask={false}
          buttons={[
            <WeaButtonIcon
              buttonType="add"
              type="primary"
              onClick={this.handleAddReservedNumber}
            />,
            <WeaButtonIcon
              buttonType="del"
              type="primary"
              onClick={this.handleDelete}
              disabled={_.isEmpty(toJS(tableStore.selectedRowKeys))}
            />,
          ]}
        />
        <WeaTable
          ecId={`${(this && this.props && this.props.ecId) || ""
            }_WeaTable@b43d3f`}
          comsWeaTableStore={tableStore}
          hasOrder={true}
          needScroll={true}
        />
        {/* 起始/预留编号设置 */}
        <WeaDialog
          title={`新建预留编号`}
          visible={addVisible}
          onCancel={() => {
            reservedForm.resetForm();
            this.setState({ addVisible: false, previewStr: "" });
          }}
          icon="icon-coms-hrm"
          iconBgcolor="#217346"
          hasScroll
          style={{ width: 640, height: 480 }}
          buttons={[
            <Button
              ecId={`${(this && this.props && this.props.ecId) || ""
                }_Button@jd6baw`}
              type="primary"
              loading={loading}
              onClick={this.handleSubmitReservedNumber}>
              {i18n.button.save()}
            </Button>,
            <WeaMoreButton
              ecId={`${(this && this.props && this.props.ecId) || ""
                }_WeaMoreButton@e4f4n1`}
            />,
          ]}>
          {this.getReservedForm()}
          <WeaSearchGroup title="预留编号预览" showGroup>
            <p style={{ textAlign: "center", color: "#30b7f5" }}>
              {previewStr}
            </p>
          </WeaSearchGroup>
        </WeaDialog>
      </div>
    );
  }
}

export default ReservedNumberSetting;
