/*
 * Author: 黎永顺
 * Description:
 * Date: 2022-05-17 16:02:56
 * LastEditTime: 2022-06-14 14:16:16
 */
import React, { Component, Fragment } from "react";
import { Button, Modal } from "antd";
import {
  WeaTableEdit,
  WeaDialog,
  WeaMoreButton,
  WeaFormItem,
  WeaSelect,
  WeaInput,
  WeaInputNumber,
} from "ecCom";
import Preview from "./preview";
import { i18n } from "../../../../public/i18n";
import _ from "lodash";
import "../index.less";

class NumberComposition extends Component {
  constructor() {
    super();
    this.state = {
      visible: false,
      objectData: {
        numField: "string",
        numFieldName: "字符串",
      },
      dataSource: [],
    };
  }

  componentDidMount() {
    const enums = {
      STRING: "字符串",
      NUMBER: "流水号位数",
      YEAR: "当前年份",
      MONTH: "当前月份",
      DAY: "当前日期",
      SUBCOMPANY: "分部编号",
      DEPARTMENT: "部门编号",
      JOBTITLES: "岗位编号",
    };
    let num = 0;
    const { dataSource: details, onChange } = this.props;
    for (let i in details) {
      if (details[i].ruletype === "STRING") {
        details[i].showorder = num;
        num++;
      }
    }
    const tmpV = _.map(details, (it, index) => {
      const { ruletype, rulevalue, showorder } = it;
      return {
        id: index,
        value: rulevalue,
        strLogo: Number(showorder) + 1,
        numFieldName:
          ruletype === "STRING"
            ? `${enums[ruletype]}${Number(showorder) + 1}`
            : enums[ruletype],
        numField: _.toLower(ruletype),
      };
    });
    this.setState(
      {
        dataSource: !_.isEmpty(tmpV)
          ? tmpV
          : [
            {
              id: 1,
              value: "",
              strLogo: 1,
              numFieldName: "字符串1",
              numField: "string",
            },
            {
              id: 2,
              value: 3,
              numFieldName: "流水号位数",
              numField: "number",
            },
          ],
      },
      () => {
        onChange && onChange(this.state.dataSource);
      }
    );
  }

  /**
   * name:复选框禁用
   * param undefined
   * return {*}
   */
  getRowSelection = (rowSelection) => {
    const { dataSource } = this.state;
    const hasMonthNum = dataSource.some((item) => item.numField === "month");
    const hasDayNum = dataSource.some((item) => item.numField === "day");
    const sel = { ...rowSelection };
    sel.getCheckboxProps = (record) => {
      return {
        disabled:
          record.numField === "number" ||
          (hasMonthNum && record.numField === "year") ||
          (hasDayNum && record.numField === "month"),
      };
    };
    return sel;
  };
  /**
   * name: 字段保存
   * return {*}
   */
  handleSave = () => {
    let newDataSource = [];
    const { objectData, dataSource } = this.state;
    const { onChange } = this.props;
    const { numField, numFieldName } = objectData;
    const stringRow = _.filter(dataSource, (it) => it.numField === "string"); //字符串列表
    const maxStrLen = !_.isEmpty(stringRow)
      ? _.sortBy(stringRow, function (o) {
        return -o.strLogo;
      })[0].strLogo
      : 0; //字符串列表
    const maxIdLen = _.sortBy(dataSource, function (o) {
      return -o.id;
    })[0].id; //字符串列表

    const index = _.findIndex(dataSource, (item) => item.numField !== "string");
    const lastStrindex = _.findLastIndex(
      dataSource,
      (item) => item.numField === "string"
    );
    if (numField === "subcompany" || numField === "department" || numField === "jobtitles") {
      if (_.findIndex(dataSource, it => it.numField === numField) !== -1) {
        Modal.warning({
          title: "信息确认",
          content: `已经添加过一个${numFieldName}，请选择其他编号字段！`,
          onOk() { },
          okText: "确认",
        });
        return;
      }
    }
    if (numField === "year" || numField === "month" || numField === "day") {
      const hasYearOrMonthOrDay = _.some(
        dataSource,
        (it) => it.numField === numField
      );
      const hasYearNum = dataSource.some((item) => item.numField === "year");
      const hasMonthNum = dataSource.some((item) => item.numField === "month");
      if (!hasYearOrMonthOrDay) {
        if (numField === "month" && !hasYearNum) {
          Modal.warning({
            title: "信息确认",
            content: `添加【${numFieldName}】时，请先添加【当前年份】！`,
            onOk() { },
            okText: "确认",
          });
          return;
        }
        if (numField === "day" && (!hasYearNum || !hasMonthNum)) {
          Modal.warning({
            title: "信息确认",
            content: `添加【${numFieldName}】时，请先添加【当前年份】和【当前月份】！`,
            onOk() { },
            okText: "确认",
          });
          return;
        }
      } else {
        this.showConfirm();
        return;
      }
    }

    // 如果前n项为空或者当中包含非字符串项，则
    if (index > lastStrindex) {
      if (numField === "month") {
        const tmpVLastYearindex = _.findLastIndex(
          dataSource,
          (item) => item.numField === "year"
        );
        dataSource.splice(tmpVLastYearindex + 1, 0, {
          id: maxIdLen + 1,
          value: "",
          numFieldName:
            numField === "string"
              ? `${numFieldName}${stringRow.length + 1}`
              : numFieldName,
          numField,
        });
      } else if (numField === "day") {
        const tmpVLastMonthindex = _.findLastIndex(
          dataSource,
          (item) => item.numField === "month"
        );
        dataSource.splice(tmpVLastMonthindex + 1, 0, {
          id: maxIdLen + 1,
          value: "",
          numFieldName:
            numField === "string"
              ? `${numFieldName}${stringRow.length + 1}`
              : numFieldName,
          numField,
        });
      } else {
        const tmpVLastStrindex = _.findLastIndex(
          dataSource,
          (item) => item.numField === "string"
        );
        dataSource.splice(tmpVLastStrindex + 1, 0, {
          id: maxIdLen + 1,
          value: "",
          strLogo: maxStrLen + 1,
          numFieldName:
            numField === "string"
              ? `${numFieldName}${maxStrLen + 1}`
              : numFieldName,
          numField,
        });
      }
      newDataSource = [...dataSource];
    } else {
      if (numField === "month") {
        const tmpVLastYearindex = _.findLastIndex(
          dataSource,
          (item) => item.numField === "year"
        );
        dataSource.splice(tmpVLastYearindex + 1, 0, {
          id: maxIdLen + 1,
          value: "",
          numFieldName:
            numField === "string"
              ? `${numFieldName}${stringRow.length + 1}`
              : numFieldName,
          numField,
        });
      } else if (numField === "day") {
        const tmpVLastMonthindex = _.findLastIndex(
          dataSource,
          (item) => item.numField === "month"
        );
        dataSource.splice(tmpVLastMonthindex + 1, 0, {
          id: maxIdLen + 1,
          value: "",
          numFieldName:
            numField === "string"
              ? `${numFieldName}${stringRow.length + 1}`
              : numFieldName,
          numField,
        });
      } else {
        const tmpVLastStrindex = _.findLastIndex(
          dataSource,
          (item) => item.numField === "string"
        );
        dataSource.splice(tmpVLastStrindex, 0, {
          id: maxIdLen + 1,
          value: "",
          strLogo: maxStrLen + 1,
          numFieldName:
            numField === "string"
              ? `${numFieldName}${maxStrLen + 1}`
              : numFieldName,
          numField,
        });
      }
      newDataSource = [...dataSource];
    }
    this.setState({
      visible: false,
      objectData: { numField: "string", numFieldName: "字符串" },
      dataSource: newDataSource,
    });
    onChange && onChange(newDataSource);
  };
  /**
   * name:年月日字段重复提示
   * return {*}
   */
  showConfirm = () => {
    const { objectData } = this.state;
    Modal.warning({
      title: "信息确认",
      content: `已经添加过一个${objectData.numFieldName}，请选择其他编号字段！`,
      footer: [],
      onOk() { },
      okText: "确认",
    });
  };

  handleChangeInput = (value, index, record) => {
    const { dataSource } = this.state;
    const { onChange } = this.props;
    this.setState(
      {
        dataSource: _.map(dataSource, (it) => {
          if (it.id === record.id) {
            return {
              ...it,
              value,
            };
          }
          return { ...it };
        }),
      },
      () => {
        onChange && onChange(this.state.dataSource);
      }
    );
  };

  handleDragChange = (dataSource) => {
    const { onChange } = this.props;
    this.setState({ dataSource });
    onChange && onChange(dataSource);
  };

  render() {
    const { visible, objectData, dataSource } = this.state;
    const { options } = this.props;
    const { numField, numFieldName } = objectData;
    const columns = [
      {
        title: "",
        dataIndex: "numFieldName",
        key: "numFieldName",
        colSpan: 1,
        com: [{ label: "", type: "TEXT" }],
        width: "20%",
      },
      {
        title: "",
        useRecord: true,
        dataIndex: "custom",
        key: "custom",
        com: [
          {
            type: "custom",
            key: "custom",
            render: (text, record, index) => {
              const { numField } = record;
              if (
                numField === "year" ||
                numField === "month" ||
                numField === "day" ||
                numField === "subcompany" ||
                numField === "department" ||
                numField === "jobtitles"
              ) {
                return <span></span>;
              }
              if (numField === "number") {
                return (
                  <WeaInputNumber
                    id="customNumberInput"
                    value={record.value}
                    onChange={(value) =>
                      this.handleChangeInput(value, index, record)
                    }
                  />
                );
              }
              return (
                <WeaInput
                  id="custom"
                  value={record.value}
                  onChange={(value) =>
                    this.handleChangeInput(value, index, record)
                  }
                />
              );
            },
          },
        ],
        colSpan: 1,
        width: "70%",
      },
    ];
    const buttons = [
      <Button
        ecId={`${(this && this.props && this.props.ecId) || ""}_Button@jd6baw`}
        onClick={this.handleSave}
        type="primary">
        {i18n.button.save()}
      </Button>,
      <WeaMoreButton
        ecId={`${(this && this.props && this.props.ecId) || ""
          }_WeaMoreButton@e4f4n1`}
      />,
    ];

    return (
      <Fragment>
        <WeaTableEdit
          draggable={true}
          columns={columns}
          datas={dataSource}
          getRowSelection={this.getRowSelection}
          pushTitleIntoHeader
          showCopy={false}
          btnsType="inline"
          deleteConfirm
          addType="func"
          addFunc={() =>
            this.setState({
              visible: true,
            })
          }
          onChange={this.handleDragChange}
        />
        {/* 预览 */}
        <Preview dataSource={dataSource} />
        {/* 新增弹框 */}
        <WeaDialog
          onCancel={() =>
            this.setState({
              visible: false,
            })
          }
          icon="icon-coms-hrm"
          iconBgcolor="#217346"
          title={i18n.label.addNumberField()}
          visible={visible}
          hasScroll
          initLoadCss
          maxHeight={150}
          buttons={buttons}>
          <div style={{ padding: "20px 20%" }}>
            <WeaFormItem
              label="编号字段"
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}>
              <WeaSelect
                options={options}
                value={numField}
                viewAttr={2}
                onChange={(numField, numFieldName) => {
                  this.setState({ objectData: { numField, numFieldName } });
                }}
              />
            </WeaFormItem>
          </div>
        </WeaDialog>
      </Fragment>
    );
  }
}

export default NumberComposition;
