/*
 * Author: 黎永顺
 * name: 编辑弹框
 * Description:
 * Date: 2023/9/25
 */
import React, { Component } from "react";
import { Button, message, Modal } from "antd";
import { WeaLocaleProvider, WeaSlideModal, WeaTab } from "ecCom";
import EditSalaryBaseInfo from "./baseInfo";
import PayrollItemsTable from "../../../../calculateDetail/payrollItemsTable";
import IssuedAndReissueTable from "../../../../calculateDetail/issuedAndReissueTable";
import { acctresultDetail, saveAcctResult } from "../../../../../apis/calculate";
import { toDecimal_n } from "../../../../../util";
import CalcAnchorList from "./calcAnchorList";
import "./index.less";

const getLabel = WeaLocaleProvider.getLabel;

class EditSalaryCalcSlide extends Component {
  constructor(props) {
    super(props);
    this.state = {
      baseInfo: [], selectedKey: "0", loading: false,
      issuedAndReissueItems: [], //已发补发薪资项目
      itemsByGroup: [] //正常发放薪资项目所得薪资项目
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) this.acctresultDetail(nextProps.id);
    if (nextProps.visible !== this.props.visible && !nextProps.visible) this.setState({ selectedKey: "0" }, () => document.getElementById("salary_anchor_area").scrollTop = 0);
  }

  acctresultDetail = (id) => {
    acctresultDetail({ id }).then(({ status, data }) => {
      if (status) {
        const { employeeInfos, issuedAndReissueItems, itemsByGroup } = data;
        this.setState({
          baseInfo: employeeInfos, issuedAndReissueItems, itemsByGroup
        });
      }
    });
  };
  renderTitle = () => {
    const { loading, itemsByGroup } = this.state, { viewAttr } = this.props;
    return <div className="titleDialog">
      <div className="titleCol titleLeftBox">
        <div className="titleIcon"><i className="icon-coms-fa"/></div>
        <div className="title">{viewAttr === 2 ? getLabel(543559, "编辑薪资") : getLabel(111, "查看薪资")}</div>
      </div>
      <div className="titleCol titleRightBox">
        {
          viewAttr === 2 &&
          <Button type="primary" disabled={_.isEmpty(itemsByGroup)} onClick={this.save} loading={loading}>{getLabel(537558, "保存")}</Button>
        }
      </div>
    </div>;
  };
  handleItemValueChange = (field, value, isInput, groupId) => {
    const { issuedAndReissueItems, itemsByGroup } = this.state;
    if (isInput === "itemsByGroup") {
      this.setState({
        itemsByGroup: itemsByGroup.map(item => {
          if (item.salarySobItemGroupId === groupId) {
            return {
              ...item,
              salaryItems: _.map(item.salaryItems, it => {
                if (it.salaryItemId === field) {
                  return { ...it, resultValue: value };
                }
                return { ...it };
              })
            };
          }
          return { ...item };
        })
      });
    } else if (isInput === "issuedAndReissueItems") {
      this.setState({
        issuedAndReissueItems: issuedAndReissueItems.map(item => {
          item = { ...item };
          if (item.salaryItemName === field) {
            item.resultValue = value;
          }
          return item;
        })
      });
    }
  };
  save = () => {
    const { id: salaryAcctEmpId } = this.props;
    const { issuedAndReissueItems, itemsByGroup, baseInfo } = this.state;
    if (!_.every(baseInfo, (item) => (!item.canEdit || !!item.fieldValue))) {
      Modal.warning({
        title: getLabel(131329, "信息确认"),
        content: getLabel(518702, "必要信息不完整，红色*为必填项！")
      });
      return;
    }
    const payload = {
      salaryAcctEmpId,
      employeeInfos: _.map(baseInfo, o => ({ ...o, fieldValue: o.fieldValue.id || o.fieldValue })),
      items: [
        ..._.reduce(itemsByGroup, (pre, cur) => {
          return [
            ...pre,
            ..._.map(cur.salaryItems, it => {
              return {
                salaryItemId: it.salaryItemId,
                resultValue: (it.dataType === "number" && !!it.resultValue) ? toDecimal_n(it.resultValue, !_.isNil(it.pattern) ? it.pattern : 2) : it.resultValue
              };
            })
          ];
        }, []),
        ...issuedAndReissueItems.map(item => ({
          salaryItemId: item.salaryItemId,
          resultValue: (item.dataType === "number" && !!item.resultValue) ? toDecimal_n(item.resultValue, !_.isNil(item.pattern) ? item.pattern : 2) : item.resultValue
        }))
      ]
    };
    this.setState({ loading: true });
    saveAcctResult(payload).then(({ status, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        message.success(getLabel(30700, "操作成功！"));
        this.props.onClose("true");
      } else {
        message.error(errormsg);
      }
    }).catch(() => this.setState({ loading: false }));
  };

  render() {
    const { baseInfo, selectedKey, itemsByGroup, issuedAndReissueItems } = this.state;
    const topTab = [
      { title: getLabel(542704, "正常工资薪金所得"), viewcondition: "0" },
      { title: getLabel(542651, "已发补发"), viewcondition: "1" }
    ];
    return (
      <React.Fragment>
        <WeaSlideModal
          className="salary-calculate-esf-layout" {...this.props}
          top={0} width={60} height={100} measure={"%"}
          direction={"right"} title={this.renderTitle()}
          content={<div className="salary-calculate-esf-area" id="salary_anchor_area">
            {/*锚点*/}
            <CalcAnchorList datas={itemsByGroup} visible={this.props.visible}/>
            <EditSalaryBaseInfo {...this.props} baseInfo={baseInfo}
                                onChange={baseInfo => this.setState({ baseInfo })}/>
            <WeaTab keyParam="viewcondition" className="calc-esf-tab"
                    selectedKey={selectedKey} onChange={v => this.setState({ selectedKey: v })}
                    datas={!_.isEmpty(issuedAndReissueItems) ? topTab : topTab.slice(0, 1)}
            />
            {
              selectedKey === "0" && _.map(itemsByGroup, item => {
                return <PayrollItemsTable {...this.props} {...item}
                                          onChangeIssueReissueValue={this.handleItemValueChange}/>;
              })
            }
            {
              selectedKey === "1" &&
              <IssuedAndReissueTable
                {...this.props}
                dataSource={issuedAndReissueItems}
                onChangeIssueReissueValue={this.handleItemValueChange}
              />
            }
          </div>}
        />
      </React.Fragment>
    );
  }
}

export default EditSalaryCalcSlide;
