/*
 * Author: 黎永顺
 * name: 工资单发放-重构页面编辑模板
 * Description:
 * Date: 2023/10/13
 */
import React, { Component } from "react";
import { toJS } from "mobx";
import { inject, observer } from "mobx-react";
import { WeaLocaleProvider, WeaSlideModal, WeaSteps } from "ecCom";
import { Button, message, Modal } from "antd";
import PayrollTempBaseSet from "../payrollTempBaseSet";
import PayrollTempNormalSet from "../payrollTempNormalSet";
import PayrollTempReissueSet from "../payrollTempReissueSet";
import { savePayroll, updatePayroll } from "../../../../apis/payroll";

const Step = WeaSteps.Step;
const getLabel = WeaLocaleProvider.getLabel;
const APIFox = { save: savePayroll, update: updatePayroll };

@inject("payrollStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      current: 0, loading: false
    };
    this.tmpBaseSetRef = null;
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      document.querySelector(".salary-payroll-main-page").classList.add("zIndex0-payroll-release");
    } else if (nextProps.visible !== this.props.visible && !nextProps.visible) {
      document.querySelector(".salary-payroll-main-page").classList.remove("zIndex0-payroll-release");
      nextProps.payrollStore.setHasBeenModify(false);
    }
  }

  save = async () => {
    const {
      payrollStore: {
        payrollTempForm, payrollTempFeedbackForm, initPayrollTempForm,
        initPayrollTempFeedbackForm, setTmplDataSource, tmplDataSource,
        setHasBeenModify
      }
    } = this.props;
    const [tempFormm, fbForm] = await Promise.all([payrollTempForm.validateForm(), payrollTempFeedbackForm.validateForm()]);
    if (tempFormm.isValid && fbForm.isValid) {
      const {
          replenishRule, autoSendStatus, emailStatus, msgStatus, smsStatus, ...extraBs
        } = payrollTempForm.getFormParams(),
        { ackFeedbackStatus, feedbackStatus, autoAckDays, ...extraFb } = payrollTempFeedbackForm.getFormParams(),
        { formData, smsSettingDialog } = this.tmpBaseSetRef.state;
      if (autoSendStatus !== "1" && emailStatus !== "1" && msgStatus !== "1" && smsStatus !== "1") {
        message.warning(getLabel(111, "工资单模板至少开启一个发送通道"));
        return;
      }
      const payload = {
        ...toJS(tmplDataSource), ...extraFb, ...formData, ...extraBs,
        ackFeedbackStatus: ackFeedbackStatus === "1",
        feedbackStatus: feedbackStatus === "1",
        autoSendStatus: autoSendStatus === "1",
        emailStatus: emailStatus === "1",
        msgStatus: msgStatus === "1",
        smsStatus: smsStatus === "1",
        smsSetting: {
          content: smsSettingDialog.content
        },
        autoAckDays: Number(autoAckDays),
        replenishRule: (replenishRule === "0" || !replenishRule) ? "ALL" : replenishRule
      };
      setTmplDataSource(payload);
      this.setState({ current: this.state.current + 1 }, () => {
        initPayrollTempForm();
        initPayrollTempFeedbackForm();
        setHasBeenModify(true);
      });
    } else {
      tempFormm.showErrors();
      fbForm.showErrors();
      this.forceUpdate();
    }
  };
  normalSave = () => {
    const { payrollStore: { payrollTempNormalForm, setTmplDataSource, tmplDataSource } } = this.props;
    payrollTempNormalForm.validateForm().then(f => {
      if (f.isValid) {
        const {
          salaryItemNullStatus,
          salaryItemZeroStatus,
          background,
          ...extra
        } = payrollTempNormalForm.getFormParams();
        const payload = {
          ...toJS(tmplDataSource), ...extra,
          salaryItemZeroStatus: salaryItemZeroStatus === "1",
          salaryItemNullStatus: salaryItemNullStatus === "1"
        };
        setTmplDataSource(payload);
        this.setState({ current: this.state.current + 1 });
      } else {
        f.showErrors();
        this.forceUpdate();
      }
    });
  };
  savePayroll = () => {
    const { payrollStore: { tmplDataSource, salaryBillItemNameSetting, setHasBeenModify }, tmplId: id } = this.props;
    const payload = {
      ...toJS(tmplDataSource), id,
      salarySobId: toJS(tmplDataSource).salarySob,
      salaryBillItemNameSetting: toJS(salaryBillItemNameSetting)
    };
    this.setState({ loading: true });
    const API = APIFox[id ? "update" : "save"];
    API(payload).then(({ status, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        message.success(getLabel(30700, "操作成功！"));
        setHasBeenModify(false);
        this.handleClose("refresh");
      } else {
        message.error(errormsg);
      }
    }).catch(() => this.setState({ loading: false }));
  };
  renderTitle = () => {
    const { tmplId, detail } = this.props, { current, loading } = this.state;
    const { payrollStore: { payrollTempNormalForm, setTmplDataSource, tmplDataSource } } = this.props;
    return <div className="payroll-title-flex titleDialog">
      <div className="titleCol titleLeftBox">
        <div className="titleIcon"><i className="icon-coms-fa"/></div>
        <div className="title">{tmplId ? getLabel(543583, "编辑工资单模板") : getLabel(543582, "新建工资单模板")}</div>
      </div>
      <div className="titleCol titleRightBox">
        {
          current === 0 ?
            <Button type="primary" onClick={this.save}>{getLabel(1402, "下一步")}</Button> :
            current === 1 ?
              <React.Fragment>
                <Button type="ghost"
                        onClick={() => {
                          const {
                            salaryItemNullStatus, salaryItemZeroStatus,
                            background, ...extra
                          } = payrollTempNormalForm.getFormParams();
                          const payload = {
                            ...toJS(tmplDataSource), ...extra,
                            salaryItemZeroStatus: salaryItemZeroStatus === "1",
                            salaryItemNullStatus: salaryItemNullStatus === "1"
                          };
                          setTmplDataSource(payload);
                          this.setState({ current: current - 1 });
                        }}>{getLabel(1876, "上一步")}</Button>
                <Button type="primary" onClick={this.normalSave}>{getLabel(1402, "下一步")}</Button>
                <Button type="ghost" onClick={this.handlePreview}>{getLabel(221, "预览")}</Button>
              </React.Fragment> :
              <React.Fragment>
                <Button type="ghost"
                        onClick={() => this.setState({ current: current - 1 })}>{getLabel(1876, "上一步")}</Button>
                {
                  !detail &&
                  <Button type="primary" loading={loading}
                          onClick={this.savePayroll}>{getLabel(537558, "保存")}</Button>
                }
              </React.Fragment>
        }
      </div>
    </div>;
  };
  renderSlideContent = () => {
    const { current } = this.state;
    let dom = null;
    switch (current) {
      case 0:
        dom = <PayrollTempBaseSet {...this.props} ref={dom => this.tmpBaseSetRef = dom}/>;
        break;
      case 1:
        dom = <PayrollTempNormalSet {...this.props} />;
        break;
      case 2:
        dom = <PayrollTempReissueSet {...this.props} />;
        break;
      default:
        break;
    }
    return dom;
  };
  handleClose = (type) => {
    const {
      payrollStore: {
        initPayrollTempForm, initPayrollTempFeedbackForm, setSalaryBillItemNameSetting,
        initPayrollTempNormalForm, setTmplDataSource, hasBeenModify
      }, onClose, detail
    } = this.props;
    if (detail) {
      initPayrollTempForm();
      initPayrollTempFeedbackForm();
      initPayrollTempNormalForm();
      setTmplDataSource({});
      setSalaryBillItemNameSetting([
        {
          salaryTemplateId: "",
          salaryBillType: 0,
          itemShowNameSetting: []
        },
        {
          salaryTemplateId: "",
          salaryBillType: 1,
          itemShowNameSetting: []
        }
      ]);
      this.setState({ current: 0 });
      onClose(type);
      return;
    }
    if (hasBeenModify) {
      Modal.confirm({
        title: getLabel(131329, "信息确认"),
        content: getLabel(111, "确定放弃填写吗？放弃后数据将不会被保存！"),
        onOk: () => {
          initPayrollTempForm();
          initPayrollTempFeedbackForm();
          initPayrollTempNormalForm();
          setTmplDataSource({});
          setSalaryBillItemNameSetting([
            {
              salaryTemplateId: "",
              salaryBillType: 0,
              itemShowNameSetting: []
            },
            {
              salaryTemplateId: "",
              salaryBillType: 1,
              itemShowNameSetting: []
            }
          ]);
          this.setState({ current: 0 });
          onClose(type);
        }
      });
    } else {
      initPayrollTempForm();
      initPayrollTempFeedbackForm();
      initPayrollTempNormalForm();
      setTmplDataSource({});
      setSalaryBillItemNameSetting([
        {
          salaryTemplateId: "",
          salaryBillType: 0,
          itemShowNameSetting: []
        },
        {
          salaryTemplateId: "",
          salaryBillType: 1,
          itemShowNameSetting: []
        }
      ]);
      this.setState({ current: 0 });
      onClose(type);
    }
  };
  handlePreview = () => {
    const { payrollStore: { payrollTempNormalForm, tmplDataSource } } = this.props;
    window.localStorage.removeItem("weapp-salary-payroll-preview-data");
    payrollTempNormalForm.validateForm().then(f => {
      if (f.isValid) {
        const {
          salaryItemNullStatus, salaryItemZeroStatus, background, ...extra
        } = payrollTempNormalForm.getFormParams();
        const { textContentPosition, textContent } = extra;
        const bkView = toJS(tmplDataSource).background;
        const payload = {
          ...toJS(tmplDataSource), ...extra, background: bkView,
          salaryItemZeroStatus: salaryItemZeroStatus === "1",
          salaryItemNullStatus: salaryItemNullStatus === "1"
        };
        if (textContentPosition !== "0" && ((textContentPosition && !textContent) || (!textContentPosition && textContent))) {
          message.warning(getLabel(111, "请完善文本内容与文本内容位置设置！"));
          return;
        }
        window.localStorage.setItem("weapp-salary-payroll-preview-data", JSON.stringify(payload));
        setTimeout(() => {
          window.open("/spa/hrmSalary/static/index.html#/main/hrmSalary/payrollinfo");
        }, 300);
      } else {
        f.showErrors();
        this.forceUpdate();
      }
    });
  };

  render() {
    const { current } = this.state;
    const tabs = [
      { key: 0, title: getLabel(82751, "基础设置") },
      { key: 1, title: getLabel(543579, "正常核算工资单模板") },
      { key: 2, title: getLabel(543580, "补发工资单模版") }
    ];
    return (
      <WeaSlideModal {...this.props} title={this.renderTitle()} className="payroll-tmpl-layout"
                     onClose={() => this.handleClose(null)}
                     content={(<div className="payroll-tmpl-content">
                       <WeaSteps current={current} style={{ margin: "0 0 20px 0" }}>
                         {
                           _.map(tabs, item => {
                             const { key, title } = item;
                             return <Step description={title} key={key}/>;
                           })
                         }
                       </WeaSteps>
                       {this.renderSlideContent()}
                     </div>)}
      />
    );
  }
}

export default Index;
