/*
 * Author: 黎永顺
 * Description: 部门编号设置
 * Date: 2022-06-06 09:37:39
 * LastEditTime: 2022-06-15 09:52:04
 */
import React, { Component, Fragment } from "react";
import { inject, observer } from "mobx-react";
import { Button, message } from "antd";
import {
  WeaTop,
  WeaFormItem,
  WeaCheckbox,
  WeaSearchGroup,
  WeaSelect,
  WeaHelpfulTip,
} from "ecCom";
import StartReservedNumberSet from "../branchNumSetting/components/startReservedNumberSet";
import NumberComposition from "../branchNumSetting/components/numberComposition";
import { serialFieldOptions } from "../constants";
import { i18n } from "../../../public/i18n";
import moment from "moment";
import "../branchNumSetting/index.less";

const deptSerialFieldOptions = [{ key: 'subcompany', showname: "分部编号" }]

@inject("numberSet")
@observer
export default class DeptNumberSet extends Component {
  constructor() {
    super();
    this.state = {
      options: [],
      loading: false,
      dataSource: [],
      startNumberInfo: {
        columns: [],
        dataSource: [],
      },
      subCompanyInfo: {
        details: [],
        serialenable: "0",
        deptSerial: {
          enable: "0",
          key: "",
        },
        dateSerial: {
          enable: "0",
          key: "",
        },
      },
    };
  }

  componentDidMount() {
    this.getCodeSetting();
  }

  getCodeSetting = () => {
    const { numberSet } = this.props;
    numberSet
      .getCodeSetting({ serialtype: "DEPARTMENT" })
      .then(({ api_status, details, serialenable, dateSerial = {}, deptSerial = {} }) => {
        if (api_status && !_.isEmpty(details)) {
          this.setState({
            subCompanyInfo: { details, serialenable, dateSerial, deptSerial },
          });
        }
      });
  };

  handleSubmit = () => {
    let promise = new Promise((resolve, reject) => {
      const { numberSet } = this.props;
      const { dataSource, subCompanyInfo } = this.state;
      const { serialenable, dateSerial, deptSerial } = subCompanyInfo;
      const details = _.map(dataSource, (it, showorder) => {
        const { numField, value: rulevalue } = it;
        return {
          ruletype: _.upperCase(numField),
          rulevalue,
          showorder,
        };
      });
      const payload = {
        datas: JSON.stringify({
          serialenable,
          details,
          dateSerial,
          deptSerial,
          serialtype: "DEPARTMENT",
        }),
      };
      this.setState({ loading: true });
      numberSet.saveOrUpdateCodeSetting(payload).then(({ api_status }) => {
        this.setState({ loading: false });
        if (api_status) {
          message.success("保存成功");
          resolve(api_status);
        } else {
          reject("接口调用失败");
        }
      });
    });
    return promise;
  };

  handleChangeCode = (data) => {
    const tmpV = _.filter(
      data,
      (it) =>
        it.numField === "year" ||
        it.numField === "month" ||
        it.numField === "day" ||
        it.numField === "subcompany" ||
        it.numField === "department" ||
        it.numField === "jobtitles"
    );
    this.setState({
      dataSource: _.cloneDeep(data),
      options: _.map(tmpV, (it) => {
        const { numFieldName: showname, numField: key } = it;
        return { key: _.upperCase(key), showname };
      }),
    });
  };

  handleSetNumber = (type, data = {}) => {
    this.handleSubmit().then((res) => {
      const { numberSet } = this.props;
      const { subCompanyInfo } = this.state;
      const { dateSerial, deptSerial } = subCompanyInfo;
      if (type === "start") {
        const formatVal = dateSerial.key === "YEAR" ? "YYYY" : dateSerial.key === "MONTH" ? "YYYY-MM" : "YYYY-MM-DD";
        let payload = {
          coderuleid: 2,
          type: dateSerial.enable == '1' ? dateSerial.key : '',
          dateStart: data.startDate ? data.startDate : moment().format(formatVal),
          dateEnd: data.endDate ? data.endDate : moment().format(formatVal),
          subCompanyId: data.subCompanyId ? data.subCompanyId : "",
          deptId: "",
          jobtitlesId: "",
        };
        if (deptSerial.enable === '1' && !data.subCompanyId) return
        if (deptSerial.enable === '1' && data.subCompanyId) {
          payload = { ...payload, type: payload.type + ',' + deptSerial.key }
        }
        numberSet.getStartNumForm(payload).then(({ api_status, columns, dataSource }) => {
          if (api_status) {
            this.setState({
              startNumberInfo: { columns, dataSource },
            });
          }
        });
      } else {
        numberSet.getAdvanceSearchCondition();
        numberSet.getSearchReservedCodeList({
          serialtype: "DEPARTMENT",
          checkboxType: "multi",
        });
      }
    });
  };
  handleChangeTable = (newColumns, datas) => {
    this.setState({
      startNumberInfo: {
        ...this.state.startNumberInfo,
        columns: newColumns,
        dataSource: datas,
      },
    });
  };

  handleSubmitStartNumber = () => {
    const { numberSet } = this.props;
    const payload = {
      datas: JSON.stringify({
        coderuleid: 2,
        ...this.state.startNumberInfo,
      }),
    };
    numberSet.saveStartNum(payload).then(({ api_status }) => {
      if (api_status) {
        message.success("保存成功");
        this.numberSetRef.handleClose();
      }
    });
  };

  /**
   * name: 删除预留编号
   * param {*} ids
   * return {*}
   */
  deleteReservedNumber = (ids) => {
    const { numberSet } = this.props;
    numberSet.deleteReservedCodeById({ ids }).then(({ api_status }) => {
      if (api_status) {
        message.success("删除成功");
        numberSet.getSearchReservedCodeList({
          serialtype: "DEPARTMENT",
          checkboxType: "multi",
        });
      }
    });
  };
  /**
   * name:新增预留编号
   * return {*}
   */
  handleAddReservedNumber = () => {
    const { numberSet } = this.props;
    const { reservedForm } = numberSet;
    const { options } = this.state;
    numberSet.getReservedCodeFrom({ serialtype: "DEPARTMENT" }).then(() => {
      const type = _.get(_.last(options), ['key']);
      const format = type === "YEAR" ? "YYYY" : type === "MONTH" ? "YYYY-MM" : "YYYY-MM-DD"
      const payload = {
        coderuleid: 2,
        type,
        dateStart: moment().format(format),
        dateEnd: moment().format(format),
        subCompanyId: "",
        deptId: "",
        jobtitlesId: "",
      };
      numberSet
        .getStartNumForm(payload)
        .then(({ api_status, dataSource }) => {
          if (api_status && !_.isEmpty(dataSource)) {
            const currentnumber = _.get(_.last(dataSource), ['startnum']);
            reservedForm.updateFields({
              currentnumber: {
                value: currentnumber,
              },
            });
          }
        });
    })
  };
  /**
   * name: 保存预留设置
   * param {*} params
   * return {*}
   */
  handleSubmitReservedNumber = (params) => {
    const { numberSet } = this.props;
    const payload = { ...params, serialtype: "DEPARTMENT" };
    numberSet.saveReservedCode(payload).then(({ api_status }) => {
      if (api_status) {
        message.success("保存成功");
        this.numberSetRef.handleCloseReservedModal();
        numberSet.getSearchReservedCodeList({
          serialtype: "DEPARTMENT",
          checkboxType: "multi",
        });
      }
    });
  };

  /**
   * name:提示文本
   * return {*}
   */
  helpContent = () => {
    return (
      <div>
        <p>开启后，可根据设置的部门编号规则自动生成部门编号，涉及场景如下：</p>
        <p>1.手动新建和手动编辑部门时可选择重新生成编号和选择预留部门编号；</p>
        <p>2.导入人员-添加时，新创建的部门可自动生成部门编号；</p>
        <p>3.组织结构导入-添加新部门且部门编号列为空时可自动生成部门编号；</p>
        <p>【注意】开启前请先确认部门编号字段已启用！</p>
      </div>
    );
  };
  render() {
    const { options, subCompanyInfo, loading, startNumberInfo } = this.state;
    const { numberSet } = this.props;
    const { details, serialenable, dateSerial = {}, deptSerial = {} } = subCompanyInfo;
    const btns = [
      <Button type="primary" onClick={this.handleSubmit} loading={loading}>
        保存
      </Button>,
    ];
    const dropMenuDatas = [
      {
        key: "save",
        disabled: false,
        icon: <i className="icon-coms-Preservation" />,
        content: "保存",
        onClick: (key) => this.handleSubmit(),
      },
    ];
    return (
      <div className="dept-number-set">
        <WeaTop
          title={i18n.label.deptNumSetting()}
          icon={<i className="icon-coms-hrm" />}
          iconBgcolor="#217346"
          buttons={btns}
          showDropIcon={true}
          dropMenuDatas={dropMenuDatas}
        />
        <div className="dept-content">
          <div className="switch-wrapper">
            <WeaFormItem
              label="部门编号自动生成"
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}>
              <WeaCheckbox
                value={serialenable}
                helpfulTip={this.helpContent}
                helpfulTipProps={{ placement: "top" }}
                display="switch"
                id="num-set-switch"
                onChange={(checkVal) =>
                  this.setState({
                    subCompanyInfo: {
                      ...subCompanyInfo,
                      serialenable: checkVal,
                    },
                  })
                }
              />
            </WeaFormItem>
          </div>
          {/* 内容区 */}
          {serialenable === "1" && (
            <Fragment>
              <div className="numberComposition">
                <WeaSearchGroup title={"编号组成"} showGroup>
                  <NumberComposition
                    onChange={this.handleChangeCode}
                    dataSource={details}
                    options={[...serialFieldOptions, ...deptSerialFieldOptions]}
                  />
                </WeaSearchGroup>
              </div>
              {!_.isEmpty(options) && (
                <div className="codeNumbering">
                  <WeaSearchGroup title={"编号流水规则"} showGroup>
                    {
                      !_.isEmpty(_.filter(options, item => ["YEAR", "MONTH", "DAY"].includes(item.key))) &&
                      <div className="switch-wrapper" style={{ paddingBottom: !_.isEmpty(_.filter(options, item => !["YEAR", "MONTH", "DAY"].includes(item.key))) && 0 }}>
                        <WeaFormItem
                          label="日期单独流水"
                          labelCol={{ span: 8 }}
                          wrapperCol={{ span: 16 }}>
                          <div className="codeNumbering-operateWapper">
                            <WeaCheckbox
                              value={dateSerial.enable ? dateSerial.enable : "0"}
                              display="switch"
                              id="dept-date-set-switch"
                              onChange={(isSingle) =>
                                this.setState({
                                  subCompanyInfo: {
                                    ...subCompanyInfo,
                                    dateSerial: {
                                      ...dateSerial,
                                      enable: isSingle,
                                      key: isSingle == '0' ? 'YEAR' : dateSerial.key
                                    },
                                  },
                                })
                              }
                            />
                            {dateSerial.enable == "1" && (
                              <WeaSelect
                                options={_.map(_.filter(options, item => ["YEAR", "MONTH", "DAY"].includes(item.key)), it => ({ ...it, showname: it.showname.substr(2, 1) }))}
                                value={dateSerial.key}
                                detailtype={3}
                                supportCancel
                                onChange={(key) =>
                                  this.setState({
                                    subCompanyInfo: {
                                      ...subCompanyInfo,
                                      dateSerial: {
                                        ...dateSerial,
                                        key,
                                      },
                                    },
                                  })
                                }
                              />
                            )}
                            <WeaHelpfulTip
                              width={200}
                              title="开启后可设置按年、按月或按天单独流水，如设置按年单独流水，那每年的1月1日开始流水号从001开始重新流水。"
                              placement="topLeft"
                            />
                          </div>
                        </WeaFormItem>
                      </div>
                    }
                    {
                      !_.isEmpty(_.filter(options, item => !["YEAR", "MONTH", "DAY"].includes(item.key))) &&
                      <div className="switch-wrapper">
                        <WeaFormItem
                          label="机构单独流水"
                          labelCol={{ span: 8 }}
                          wrapperCol={{ span: 16 }}>
                          <div className="codeNumbering-operateWapper">
                            <WeaCheckbox
                              value={deptSerial.enable ? deptSerial.enable : "0"}
                              display="switch"
                              id="dept-set-switch"
                              onChange={(isSingle) =>
                                this.setState({
                                  subCompanyInfo: {
                                    ...subCompanyInfo,
                                    deptSerial: {
                                      ...deptSerial,
                                      enable: isSingle,
                                    },
                                  },
                                })
                              }
                            />
                            {deptSerial.enable == "1" && (
                              <WeaSelect
                                options={_.map(_.filter(options, item => ["SUBCOMPANY", "DEPARTMENT"].includes(item.key)), it => ({ ...it, showname: it.showname.substr(0, 2) }))}
                                value={deptSerial.key}
                                detailtype={3}
                                supportCancel
                                onChange={(key) =>
                                  this.setState({
                                    subCompanyInfo: {
                                      ...subCompanyInfo,
                                      deptSerial: {
                                        ...deptSerial,
                                        key,
                                      },
                                    },
                                  })
                                }
                              />
                            )}
                            <WeaHelpfulTip
                              width={200}
                              title="开启后，可选择按分部进行单独流水"
                              placement="topLeft"
                            />
                          </div>
                        </WeaFormItem>
                      </div>
                    }
                  </WeaSearchGroup>
                </div>
              )}
              <div className="startReservedNumberSet">
                <WeaSearchGroup
                  title={"起始编号及预留编号设置"}
                  showGroup
                  center>
                  <StartReservedNumberSet
                    ref={(dom) => (this.numberSetRef = dom)}
                    onSet={this.handleSetNumber}
                    companyInfo={subCompanyInfo}
                    loading={loading}
                    startNumberInfo={startNumberInfo}
                    onChange={this.handleChangeTable}
                    onSaveStartNumber={this.handleSubmitStartNumber}
                    onDeleteReservedNumber={this.deleteReservedNumber}
                    onAddReservedNumber={this.handleAddReservedNumber}
                    onSubmitReservedNumber={this.handleSubmitReservedNumber}
                    onSearchReservedNumberset={() =>
                      numberSet.getSearchReservedCodeList({
                        serialtype: "DEPARTMENT",
                        checkboxType: "multi",
                      })
                    }
                  />
                </WeaSearchGroup>
              </div>
            </Fragment>
          )}
        </div>
      </div>
    );
  }
}
