/*
 * Author: 黎永顺
 * name: 薪资档案-调薪
 * Description:
 * Date: 2023/9/4
 */
import React, { Component } from "react";
import { WeaDialog, WeaInput, WeaInputNumber, WeaLocaleProvider, WeaSearchGroup, WeaTableEdit, WeaTools } from "ecCom";
import { Button, message, Spin } from "antd";
import {
  editSingleSalaryItem,
  getSalaryItemAdjustBeforeValue,
  getSalaryItemForm,
  getSingleSalaryItemInfo,
  saveSalaryItem
} from "../../apis/archive";
import { inject, observer } from "mobx-react";
import { adjCondition } from "./columns";
import { getDomkes, getSearchs, toDecimal_n } from "../../util";
import moment from "moment";

const { getLabel } = WeaLocaleProvider;
const getKey = WeaTools.getKey;
const APIFox = {
  save: saveSalaryItem,
  edit: editSingleSalaryItem,
  saveForm: getSalaryItemForm,
  editForm: getSingleSalaryItemInfo
};

@inject("salaryFileStore")
@observer
class SalaryArchiveEditAdjLogRecordDialog extends Component {
  constructor(props) {
    super(props);
    this.state = {
      conditions: [], loading: false, saveLoading: false,
      salaryArchiveItemDetail: {}, canOperator: false
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    const { id, visible, salaryFileStore: { adjForm, initAdjForm } } = nextProps;
    if (nextProps.visible !== this.props.visible && visible) {
      this.getSingleSalaryItemInfo(nextProps);
    } else {
      adjForm.resetForm();
      initAdjForm();
    }
  }

  getSingleSalaryItemInfo = (props) => {
    const { salaryFileStore: { adjForm }, id, salaryArchiveId: salaryArchiveItemId } = props;
    this.setState({ loading: true });
    APIFox[id ? "editForm" : "saveForm"](id ? { id } : { salaryArchiveItemId })
      .then(({ status, data }) => {
        this.setState({ loading: false });
        if (status) {
          const { salaryArchiveItemForm, salaryArchiveItemDetail, canOperator } = data;
          const { adjustReasonList } = salaryArchiveItemForm;
          this.setState({
            canOperator,
            salaryArchiveItemDetail: {
              ...salaryArchiveItemDetail,
              list: _.map(salaryArchiveItemDetail.list, o => ({
                ...o, dataType: _.find(salaryArchiveItemDetail.salaryItemList, g => g.id === o.salaryItem).dataType,
                pattern: _.find(salaryArchiveItemDetail.salaryItemList, g => g.id === o.salaryItem).pattern
              }))
            },
            conditions: _.map(adjCondition, item => {
              return {
                ...item,
                title: getLabel(111, "调薪信息"),
                items: _.map(item.items, o => {
                  if (getKey(o) === "adjustReason") {
                    return {
                      ...o,
                      options: _.map(adjustReasonList, it => ({ key: it.id, showname: it.content }))
                    };
                  }
                  return { ...o };
                })
              };
            })
          }, () => {
            adjForm.initFormFields(this.state.conditions);
            _.map(getDomkes(this.state.conditions), domkey => {
              adjForm.updateFields({
                [domkey]: salaryArchiveItemForm[domkey] || ""
              });
            });
          });
        }
      }).catch(() => this.setState({ loading: false }));
  };
  getSalaryItemAdjustBeforeValue = (salaryItemId) => {
    const payload = {
      salaryArchiveId: this.props.salaryArchiveId,
      salaryItemId
    };
    getSalaryItemAdjustBeforeValue(payload).then(({ status, data }) => {
      if (status) {
        const { salaryArchiveItemDetail } = this.state;
        const { list } = salaryArchiveItemDetail;
        this.setState({
          salaryArchiveItemDetail: {
            ...salaryArchiveItemDetail,
            list: _.map(list, o => {
              if (o.salaryItem === salaryItemId) {
                return {
                  ...o, salaryBefore: data,
                  dataType: _.find(salaryArchiveItemDetail.salaryItemList, g => g.id === salaryItemId).dataType,
                  pattern: _.find(salaryArchiveItemDetail.salaryItemList, g => g.id === salaryItemId).pattern
                };
              }
              return { ...o };
            })
          }
        });
      }
    });
  };
  handleChangeAdjustAfter = (record, v) => {
    const { salaryArchiveItemDetail } = this.state;
    const { list } = salaryArchiveItemDetail;
    this.setState({
      salaryArchiveItemDetail: {
        ...salaryArchiveItemDetail,
        list: _.map(list, o => {
          if (o.salaryItem === record.salaryItem) {
            return {
              ...o, adjustAfter: v
            };
          }
          return { ...o };
        })
      }
    });
  };
  save = () => {
    const { salaryFileStore: { adjForm, fetchSingleSalaryItemList, getArchiveForm } } = this.props;
    const { pass } = this.tableEdit.refs.edit.doRequiredCheck();
    adjForm.validateForm().then(f => {
      if (f.isValid) {
        if (!pass) return;
        const { salaryArchiveId, id: salaryArchiveItemId } = this.props;
        const { salaryArchiveItemDetail, canOperator } = this.state;
        const { list } = salaryArchiveItemDetail;
        let payload = {
          ...adjForm.getFormParams(), salaryArchiveId,
          effectiveTime: moment(new Date(adjForm.getFormParams().effectiveTime)).format("YYYY-MM-DD"),
          salaryArchiveItems: _.map(list, o => ({
            salaryItemId: o.salaryItem,
            adjustValue: o.dataType === "number" ? toDecimal_n(o.adjustAfter, o.pattern) : o.adjustAfter
          }))
        };
        if (salaryArchiveItemId) {
          payload = { ...payload, canOperator, salaryArchiveItemId };
        }
        this.setState({ saveLoading: true });
        APIFox[salaryArchiveItemId ? "edit" : "save"](payload).then(({ status, errormsg }) => {
          this.setState({ saveLoading: false });
          if (status) {
            message.success(getLabel(22619, "保存成功！"));
            this.props.onCancel();
            fetchSingleSalaryItemList({ salaryArchiveId });
            getArchiveForm(salaryArchiveId);
          } else {
            message.error(errormsg);
          }
        }).catch(() => this.setState({ saveLoading: false }));
      } else {
        f.showErrors();
      }
    });
  };

  render() {
    const { salaryFileStore: { adjForm }, id } = this.props;
    const { loading, saveLoading, salaryArchiveItemDetail, conditions } = this.state;
    const { salaryItemList, list } = salaryArchiveItemDetail;
    const adjColumns = [
      {
        title: "薪资项目",
        dataIndex: "salaryItem",
        key: "salaryItem",
        com: [{
          options: _.map(salaryItemList, o => ({ key: o.id, showname: o.content })),
          type: "SELECT", viewAttr: id ? 1 : 3, key: "salaryItem",
          onChange: (v) => this.getSalaryItemAdjustBeforeValue(v)
        }],
        colSpan: 1,
        width: "40%"
      },
      {
        title: getLabel(111, "调整前"),
        dataIndex: "salaryBefore",
        key: "salaryBefore",
        com: [{ label: "", type: "INPUT", viewAttr: 1, key: "salaryBefore" }],
        colSpan: 1,
        width: "30%"
      },
      {
        title: getLabel(111, "调整后"),
        dataIndex: "adjustAfter",
        key: "adjustAfter",
        com: [{ label: "", type: "INPUTNUMBER", otherParams: { precision: 3 }, viewAttr: 3, key: "adjustAfter" }],
        colSpan: 1,
        width: "30%"
      }
    ];
    return (
      <WeaDialog
        {...this.props}
        scalable hasScroll className="declareResultDialog" initLoadCss
        style={{
          width: 800,
          height: 406.6,
          minHeight: 200,
          minWidth: 380,
          maxHeight: "80%",
          maxWidth: "80%",
          overflow: "hidden",
          transform: "translate(0px, 0px)"
        }}
        buttons={[<Button type="primary" onClick={this.save} loading={saveLoading}>{getLabel(537558, "保存")}</Button>]}
      >
        <div className="adjLogRecordDialogContent">
          {
            !loading ? <React.Fragment>
              {getSearchs(adjForm, conditions, 1)}
              <WeaSearchGroup title={getLabel(543333, "调薪明细")} showGroup needTigger={false}>
                <WeaTableEdit
                  ref={dom => this.tableEdit = dom} deleteConfirm
                  datas={list} showCopy={false} showAdd={!id} showDelete={!id}
                  onChange={o => this.setState({
                    salaryArchiveItemDetail: {
                      ...salaryArchiveItemDetail, list: _.map(o, it => ({ ...it, dataType: "" }))
                    }
                  })} columns={_.map(adjColumns, o => {
                  if (o.dataIndex === "adjustAfter") {
                    return {
                      ...o, render: (__, record) => {
                        if (record.dataType === "number") {
                          return <WeaInputNumber
                            precision={record.pattern} viewAttr={3} value={record["adjustAfter"]}
                            onChange={v => this.handleChangeAdjustAfter(record, v)}
                          />;
                        } else {
                          return <WeaInput
                            value={record["adjustAfter"]} viewAttr={3}
                            onChange={v => this.handleChangeAdjustAfter(record, v)}
                          />;
                        }
                      }
                    };
                  }
                  return { ...o };
                })}
                />
              </WeaSearchGroup>
            </React.Fragment> : <div className="empty"><Spin/></div>
          }
        </div>
      </WeaDialog>
    );
  }
}

export default SalaryArchiveEditAdjLogRecordDialog;
