/*
  * 扣除名单确认
  * 编辑是否扣除
  * @Author:    黎永顺
  * @Date:      2025/3/27
  * @Wechat:
  * @Email:     971387674@qq.com
  * @description:
*/
import React, { Component } from "react";
import { WeaDialog, WeaLocaleProvider, WeaTools } from "ecCom";
import { Button, message } from "antd";
import { WeaForm } from "comsMobx";
import FormInfo from "../../../components/FormInfo";
import { deductConditions } from "../constants";
import * as API from "../../../apis/declare";

const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;
const form = new WeaForm();

class DeductionAmountEditDialog extends Component {
  constructor(props) {
    super(props);
    this.state = {
      conditions: [], loading: false
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) this.initForm(nextProps);
    if (nextProps.visible !== this.props.visible && !nextProps.visible) form.resetForm();
  }

  initForm = (props) => {
    const { record } = props;
    this.setState({
      conditions: _.map(deductConditions, item => ({
        ...item,
        items: _.map(item.items, o => ({ ...o, value: record[getKey(o)] + "", label: getLabel(o.lanId, o.label) }))
      }))
    }, () => form.initFormFields(this.state.conditions));
  };
  save = () => {
    form.validateForm().then(f => {
      if (f.isValid) {
        const { id } = this.props.record;
        const paylaod = { id, deductFlag: form.getFormParams().deductFlag };
        this.setState({ loading: true });
        API.editDeductionAmount(paylaod).then(({ status, errormsg }) => {
          this.setState({ loading: false });
          if (status) {
            message.success(getLabel(30700, "操作成功！"));
            this.props.onCancel(this.props.onSuccess);
          } else {
            message.error(errormsg);
          }
        }).catch(() => this.setState({ loading: false }));
      } else {
        f.showErrors();
      }
    });
  };


  render() {
    const { conditions, loading } = this.state;
    const height = _.reduce(conditions, (pre, cur) => pre + cur.items.length, 0).length * 47;
    return (<WeaDialog {...this.props} initLoadCss title={getLabel(111, "编辑")} style={{ height }}
                       buttons={[<Button type="primary" loading={loading}
                                         onClick={this.save}>{getLabel(111, "确定")}</Button>,
                         <Button type="ghost" onClick={() => this.props.onCancel()}>{getLabel(111, "取消")}</Button>]}>
      <FormInfo className="form-dialog-layout" center={false} form={form} formFields={conditions}/>
    </WeaDialog>);
  }
}

export default DeductionAmountEditDialog;
