/*
 * Author: 黎永顺
 * name: 薪资核算规则配置
 * Description:
 * Date: 2024/4/24
 */
import React, { Component } from "react";
import { WeaSwitch } from "comsMobx";
import { inject, observer } from "mobx-react";
import { WeaFormItem, WeaLocaleProvider, WeaSearchGroup, WeaTools } from "ecCom";
import LedgerAccountSalaryItemsSet from "./ledgerAccountSalaryItemsSet";
import * as API from "../../../apis/ledger";
import { acctApprRulesConditions } from "../config";

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

@inject("ledgerStore")
@observer
class LedgerAccountApprRule extends Component {
  constructor(props) {
    super(props);
    this.state = {
      conditions: [], approvalId: "", approvalItemGroup: []
    };
  }

  componentDidMount() {
    this.init();
  }

  init = () => {
    const { saveSalarySobId, editId } = this.props;
    API.getSalaryApprovalForm({ salarySobId: editId || saveSalarySobId }).then(({ status, data }) => {
      if (status) {
        this.setState({
          approvalId: data.id,
          approvalItemGroup: _.map(data.approvalItemGroup, item => ({
            ...item, id: String(item.sorted),
            approvalItems: _.map(item.approvalItems, o => ({ ...o, id: `${String(item.sorted)}-${String(o.sorted)}` }))
          })),
          conditions: _.map(acctApprRulesConditions, item => ({
            ...item, items: _.map(item.items, o => ({
              ...o, value: getKey(o) === "isOpenApproval" ? (data[getKey(o)] ? "1" : "0") : data[getKey(o)],
              viewAttr: getKey(o) === "approvalWorkflowUrl" ? (data["isOpenApproval"] ? 3 : 2) : o.viewAttr,
              hide: getKey(o) !== "isOpenApproval" ? !data["isOpenApproval"] : false,
              label: getLabel(o.lanId, o.label)
            }))
          }))
        }, () => {
          const { ledgerStore: { AARForm } } = this.props;
          AARForm.initFormFields(this.state.conditions);
        });
      }
    });
  };

  componentWillUnmount() {
    const { ledgerStore: { initAARForm } } = this.props;
    initAARForm();
  }

  renderForm = (form, conditions) => {
    const { saveSalarySobId, editId } = this.props;
    const { approvalItemGroup } = this.state;
    const { isFormInit } = form;
    const formParams = form.getFormParams();
    let group = [];
    isFormInit && conditions && conditions.map(c => {
      let items = [];
      c.items.map(fields => {
        if (getKey(fields) !== "approvalItemGroup") {
          items.push({
            com: (
              <WeaFormItem label={`${fields.label}`} labelCol={{ span: `${fields.labelcol}` }}
                           wrapperCol={{ span: `${fields.fieldcol}` }} error={form.getError(fields)}
                           tipPosition="bottom"
              >
                <WeaSwitch fieldConfig={fields} form={form} formParams={formParams}
                           onChange={this.handleFormItemChange}/>
              </WeaFormItem>),
            hide: fields.hide
          });
        } else {
          items.push({
            com: (
              <WeaFormItem label={`${fields.label}`} labelCol={{ span: `${fields.labelcol}` }}
                           wrapperCol={{ span: `${fields.fieldcol}` }} error={form.getError(fields)}
                           tipPosition="bottom"
              >
                <LedgerAccountSalaryItemsSet datas={approvalItemGroup} salarySobId={editId || saveSalarySobId}
                                             onAddItems={(groupId, items) => this.setState({
                                               approvalItemGroup: _.map(approvalItemGroup, o => ({
                                                 ...o,
                                                 approvalItems: (groupId === o.id && !_.isEmpty(items)) ? [...o.approvalItems, ..._.map(items, (k, ki) => ({
                                                   salaryItemId: k.id, salaryItemName: k.name,
                                                   id: `${String(o.sorted)}-${String(o.approvalItems.length + ki)}`
                                                 }))] : o.approvalItems
                                               }))
                                             }, () => form.updateFields({ approvalItemGroup: { value: this.state.approvalItemGroup } }))}
                                             onEdit={(groupName, groupId) => this.setState({
                                               approvalItemGroup: groupId ? _.map(approvalItemGroup, o => ({
                                                 ...o, groupName: groupId === o.id ? groupName : o.groupName
                                               })) : [{
                                                 approvalItems: [], groupName, id: String(approvalItemGroup.length)
                                               }, ...approvalItemGroup]
                                             }, () => form.updateFields({ approvalItemGroup: { value: this.state.approvalItemGroup } }))}
                                             onDelete={(group, item) => this.setState({
                                               approvalItemGroup: _.isEmpty(item) ? _.filter(approvalItemGroup, o => o.id !== group.id) :
                                                 _.map(approvalItemGroup, o => ({
                                                   ...o,
                                                   approvalItems: _.filter(o.approvalItems, oo => oo.id !== item.id)
                                                 }))
                                             }, () => form.updateFields({ approvalItemGroup: { value: this.state.approvalItemGroup } }))}
                                             onChange={datas => this.setState({
                                               approvalItemGroup: datas
                                             }, () => form.updateFields({ approvalItemGroup: { value: datas } }))}/>
              </WeaFormItem>),
            hide: fields.hide
          });
        }
      });
      group.push(<WeaSearchGroup col={1} needTigger showGroup={c.defaultshow} items={items}/>);
    });
    return group;
  };
  convertFormItemViewAttr = (viewAttr) => {
    const { ledgerStore: { AARForm } } = this.props;
    const { isOpenApproval } = AARForm.getFormParams();
    this.setState({
      conditions: _.map(this.state.conditions, item => ({
        ...item, items: _.map(item.items, o => {
          if (getKey(o) === "approvalWorkflowUrl") {
            return { ...o, viewAttr, hide: isOpenApproval === "0" };
          } else if (getKey(o) === "approvalItemGroup") {
            return { ...o, viewAttr, hide: isOpenApproval === "0" };
          }
          return { ...o };
        })
      }))
    });
  };
  handleFormItemChange = (value) => {
    const { ledgerStore: { AARForm } } = this.props;
    const { isOpenApproval } = AARForm.getFormParams();
    if (_.keys(value)[0] === "isOpenApproval") {
      this.convertFormItemViewAttr(isOpenApproval === "1" ? 3 : 2);
    }
  };

  render() {
    const { conditions } = this.state;
    const { ledgerStore: { AARForm } } = this.props;
    return (
      <div className="form-dialog-layout" style={{ background: "#FFF" }}>
        {this.renderForm(AARForm, conditions)}
      </div>
    );
  }
}

export default LedgerAccountApprRule;
