/*
 * Author: 黎永顺
 * name: 薪资档案页面重构-薪资档案编辑与查看
 * Description:
 * Date: 2024/1/11
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaLocaleProvider, WeaSearchGroup, WeaSlideModal, WeaTools } from "ecCom";
import { Button, message, Modal } from "antd";
import { renderSalaryFilesForm } from "./form";
import { salaryFilesConditions } from "../../config";
import { getConditionDomkeys, toDecimal_n } from "../../../../util";
import * as API from "../../../../apis/archive";
import { savePaySet } from "../../../../apis/payrollFiles";
import SalaryItemChangeList from "../../../salaryFile/salaryItemChangeList";
import SalaryArchiveEditAdjLogRecord from "../../../salaryFile/salaryArchiveEditAdjLogRecord";

const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;

@inject("payrollFilesStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, conditions: [], formData: {}, salaryAdjustmentInfo: {},
      salaryArchiveItems: [], //薪资档案项目
      adjLogRecordDialog: { //薪资档案-调薪
        visible: false, title: "", salaryArchiveId: ""
      }
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      document.querySelector(".salary-files-wrapper").classList.add("zIndex0-welfare-archive");
      this.getArchiveForm(nextProps);
    } else if (nextProps.visible !== this.props.visible && !nextProps.visible) {
      document.querySelector(".salary-files-wrapper").classList.remove("zIndex0-welfare-archive");
      nextProps.payrollFilesStore.initSalaryFileForm();
    }
  }

  getArchiveForm = async (props) => {
    const { payrollFilesStore: { salaryFileForm }, salaryArchiveId, runStatuses, showOperateBtn } = props;
    const { data: salaryAdjustmentInfo } = (runStatuses === "fixed") ? await API.salaryAdjustmentInfo() : { data: {} };
    const payload = { salaryArchiveId };
    API.getArchiveForm(payload).then(({ status, data }) => {
      if (status) {
        const { baseInfo: { employee }, paySet: { data: paySetData }, adjustSalaryItems = [] } = data;
        const adjustSalaryItemsFormData = _.reduce(adjustSalaryItems, (pre, cur) => ({
          ...pre, [cur["id"]]: cur["value"]
        }), {});
        const formData = { ...paySetData, ...employee, ...adjustSalaryItemsFormData };
        this.setState({
          salaryAdjustmentInfo,
          salaryArchiveItems: _.map(adjustSalaryItems, o => ({
            adjustValue: o.value, salaryItemId: o.id, pattern: o.pattern, dataType: o.dataType
          })),
          conditions: _.map(salaryFilesConditions, o => {
            if (o.salaryFile) {
              return {
                ...o, title: getLabel(o.lanId, o.title), titleHelpful: getLabel(o.titleHelpfulLanId, o.titleHelpful),
                items: _.map(adjustSalaryItems, g => {
                  const otherParams = g.dataType === "number" ? { precision: g.pattern } : {};
                  return {
                    colSpan: 3, fieldcol: 14, label: g.name, labelcol: 10, ...otherParams,
                    conditionType: g.dataType === "number" ? "INPUTNUMBER" : "INPUT",
                    domkey: [g.id + ""], viewAttr: (runStatuses === "pending" && showOperateBtn) ? 2 : 1
                  };
                })
              };
            }
            return {
              ...o, title: getLabel(o.lanId, o.title), items: _.map(o.items, g => {
                if (getKey(g) === "payStartDate") {
                  return {
                    ...g, label: getLabel(g.lanId, g.label),
                    viewAttr: ((runStatuses === "pending" || runStatuses === "ext") && showOperateBtn) ? g.viewAttr : 1
                  };
                } else if (getKey(g) === "payEndDate") {
                  return {
                    ...g, label: getLabel(g.lanId, g.label),
                    viewAttr: (runStatuses === "stop" || !showOperateBtn) ? 1 : (runStatuses === "suspend" && showOperateBtn) ? 3 : g.viewAttr,
                    rules: (runStatuses === "suspend" && showOperateBtn) ? "required|string" : ""
                  };
                }
                return {
                  ...g, label: getLabel(g.lanId, g.label)
                };
              })
            };
          })
        }, () => {
          salaryFileForm.initFormFields(this.state.conditions);
          _.map(getConditionDomkeys(this.state.conditions), k => {
            salaryFileForm.updateFields({ [k]: formData[k] || "" });
          });
        });
      }
    });
  };

  save = async () => {
    const { salaryArchiveItems } = this.state;
    const {
      payrollFilesStore: { salaryFileForm, setHasBeenModify },
      salaryArchiveId, runStatuses
    } = this.props;
    const [salaryForm] = await Promise.all([salaryFileForm.validateForm()]);
    if (salaryForm.isValid) {
      const { payStartDate, payEndDate, ...extraParams } = salaryForm.getFormParams();
      const payload = {
        //status-非系统人员保存与定薪人员一样
        salaryArchiveId, status: _.toUpper(runStatuses === "ext" ? "fixed" : runStatuses),
        payStartDate, payEndDate,
        salaryArchiveItems: _.map(salaryArchiveItems, o => ({
          salaryItemId: o.salaryItemId,
          adjustValue: (o.dataType === "number" && (extraParams[o.salaryItemId] || extraParams[o.salaryItemId] === 0)) ? toDecimal_n(extraParams[o.salaryItemId], o.pattern || 2) : extraParams[o.salaryItemId]
        }))
      };
      this.setState({ loading: true });
      savePaySet(payload).then(({ status, errormsg }) => {
        this.setState({ loading: false });
        if (status) {
          setHasBeenModify(false);
          message.success(getLabel(30700, "操作成功！"));
          this.props.onClose(true);
        } else {
          message.error(errormsg);
        }
      }).catch(() => this.setState({ loading: false }));
    } else {
      salaryForm.showErrors();
      this.forceUpdate();
    }
  };
  renderTitle = () => {
    const { loading, salaryAdjustmentInfo } = this.state, { runStatuses, showOperateBtn, salaryArchiveId } = this.props;
    const { isShow, url } = salaryAdjustmentInfo;
    return <div className="titleDialog">
      <div className="titleCol titleLeftBox">
        <div className="titleIcon"><i className="icon-coms-fa"/></div>
        <div className="title">{getLabel(543312, "员工薪资档案")}</div>
      </div>
      <div className="titleCol titleRightBox">
        {
          runStatuses === "fixed" && showOperateBtn && isShow === "true" &&
          <Button type="ghost" onClick={() => {
            const linkUrl = url.indexOf("http") !== -1 ? url : `${window.location.origin}${url}`;
            window.open(`${linkUrl}&salaryArchiveId=${salaryArchiveId}`, "_blank");
          }}>{getLabel(543310, "发起调薪")}</Button>
        }
        {
          (runStatuses === "fixed" || runStatuses === "ext") && showOperateBtn &&
          <Button type="ghost" onClick={() => {
            this.setState({
              adjLogRecordDialog: {
                ...this.state.adjLogRecordDialog,
                visible: true, title: getLabel(542686, "调薪"), salaryArchiveId
              }
            });
          }}>{getLabel(542686, "调薪")}</Button>
        }
        {
          runStatuses !== "stop" && showOperateBtn &&
          <Button type="primary" loading={loading} onClick={this.save}>{getLabel(537558, "保存")}</Button>
        }
      </div>
    </div>;
  };
  handleClose = (visible = false) => {
    const { payrollFilesStore: { hasBeenModify, setHasBeenModify }, onClose } = this.props;
    if (hasBeenModify) {
      Modal.confirm({
        title: getLabel(131329, "信息确认"),
        content: getLabel(545770, "确定放弃填写吗？放弃后数据将不会被保存！"),
        onOk: () => {
          onClose(visible);
          setHasBeenModify(false);
        }
      });
    } else {
      onClose(visible);
      setHasBeenModify(false);
    }
  };

  render() {
    const {
      payrollFilesStore: { salaryFileForm, setHasBeenModify }, runStatuses, salaryArchiveId,
      showOperateBtn, visible
    } = this.props;
    const { conditions, adjLogRecordDialog } = this.state;
    return (
      <WeaSlideModal
        className="salary-files-edit-layout" {...this.props}
        top={0} width={800} height={100} measureT="%" measureX="px" measureY="%"
        direction={"right"} title={this.renderTitle()} onClose={() => this.handleClose(false)}
        content={<div className="salary-files-edit-area">
          {
            renderSalaryFilesForm(salaryFileForm, conditions, setHasBeenModify)
          }
          {
            runStatuses !== "pending" && visible &&
            <WeaSearchGroup title={getLabel(543328, "薪资调整记录")} items={[]} needTigger showGroup>
              <SalaryItemChangeList id={salaryArchiveId} selectedKey={runStatuses} showOperateBtn={showOperateBtn}/>
            </WeaSearchGroup>
          }
          <SalaryArchiveEditAdjLogRecord
            {...adjLogRecordDialog}
            onCancel={() => this.setState({
              adjLogRecordDialog: {
                ...adjLogRecordDialog, visible: false, title: "", salaryArchiveId: ""
              }
            })}
          />
        </div>}
      />
    );
  }
}

export default Index;
