/*
 * Create:      柿子
 * CreateDate:  2025/03/28
 * Describe：   账内转账 - 账内用途转账
 * */
import React, { Component } from 'react';
import { Modal, Select, Input, Row, Col, Form, message } from 'antd';
import { Util } from 'tools';
import './style/index.less';

class InAccountTransfer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      selectData: {},
      rowData: {},
      outPurPose: undefined, // 转出账户用途
      inPurPose: undefined, // 转入账户用途
      payamt: 0, // 转出金额(元)
      transferOutPurposeAmt: 0.00, // 转出用途金额
      transferInPurposeAmt: 0.00, // 转入用途金额
      afterTransferAmt: 0.00, // 转入后金额
      okLoading: false, // 确认loading
    };

    this.formItemInput = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };
  };

  static getDerivedStateFromProps(nextProps, prevState) {
    if (JSON.stringify(nextProps.selectData) !== JSON.stringify(prevState.selectData)) {
      return {
        selectData: nextProps.selectData,
      }
    }
    return null
  };

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
  };

  modifyVisible = (visible, rowData = {}) => {
    if (visible) {
      this.state.rowData = rowData;
      let accPurposeCode = rowData?.accPurposeCode || undefined;
      this.state.outPurPose = accPurposeCode; // 当前用途
      this.state.transferOutPurposeAmt = rowData?.accPurposeAmt || 0.00; // 当前用途金额
      this.props.form.setFieldsValue({ outPurPose: accPurposeCode });
    };
    this.setState({ visible }, () => {
      !visible && this.handleReset();
    });
  };

  // 确认
  handleOk = () => {
    try {
      const { payamt, transferOutPurposeAmt } = this.state;
      if (payamt && parseFloat(payamt) > parseFloat(transferOutPurposeAmt)) {
        message.error('转出金额不能大于转出用途金额');
        return;
      }
      if (payamt && parseFloat(payamt) < 0) {
        message.error('转出金额不能小于0');
        return;
      }
      this.props.form.validateFields(async (err, values) => {
        if (!err) {
          this.setState({ okLoading: true });
          const { rowData } = this.state;
          let data = {
            params: [{
              paymenttype: rowData?.paymenttype || 'P',
              depositType: rowData?.depositType || 'O',
              channel: rowData?.channel || 'OP', //缴款渠道 OP 门诊窗口充值、SM 自助机充值、IP住院预交金充值
              accmanID: rowData?.accmanID || '',
              admID: rowData?.admID || '',
              patID: rowData?.patID || '',
              ...values,
            }]
          }
          let res = await React.$asyncPost(this, '05210097', data);
          message.success(res?.errorMessage || '转账成功');
          this.modifyVisible(false);
          this.setState({ okLoading: false });
          this.props.handleQuery && this.props.handleQuery();
        } else {
          message.error('请完善必填信息！');
        }
      });
    } catch (error) {
      this.setState({ okLoading: false });
    }
  };

  handleTransferOutChange = async (e) => {
    const { payamt, inPurPose } = this.state;
    let purposeAmt = await this.getAccountPurposeAmount(e);
    if (payamt && (parseFloat(purposeAmt) < parseFloat(payamt))) { // 如果实际用途金额小于填写的转出金额，将转出金额设置为实际用途金额
      this.setTransferOutAmt(purposeAmt || undefined);
    };
    if (e === inPurPose) { // 如果选择的转出用途和选择的转入用途一致，则清空转入用途
      this.state.inPurPose = undefined;
      this.state.transferInPurposeAmt = 0.00;
      this.state.afterTransferAmt = 0.00;
      this.props.form.setFieldsValue({ inPurPose: undefined });
    }
    this.setState({ outPurPose: e, transferOutPurposeAmt: purposeAmt }, () => {
      this.getAfterTransferAmt(); // 计算转入后的金额
    });
  };

  // 获取账户用途金额
  getAccountPurposeAmount = async (accPurposeCode) => {
    let purposeAmount = 0;
    try {
      let { rowData } = this.state;
      if (!accPurposeCode) {
        return 0
      };
      let data = {
        params: [{
          accmanID: rowData?.accmanID || '',
          puposeCode: accPurposeCode,
          admID: rowData?.admID || ''
        }]
      }
      let res = await React.$asyncPost(this, '03040039', data);
      purposeAmount = res?.purposeBlance || 0;
    } catch (error) {
      console.log(error)
    }
    return purposeAmount;
  };

  // 设置转出金额
  setTransferOutAmt = (val) => {
    this.props.form.setFieldsValue({ payamt: val });
    this.setState({ payamt: val });
  };

  // 全部转出
  handleAllTransferOut = () => {
    const { transferOutPurposeAmt } = this.state;
    this.setTransferOutAmt(transferOutPurposeAmt);
    this.setState({}, () => {
      this.getAfterTransferAmt(); // 计算转入后的金额
    })
  };

  handleTransferOutAmtChange = e => {
    this.setState({ payamt: e.target.value }, () => {
      this.getAfterTransferAmt(); // 计算转入后的金额
    })
  };

  // 转入用途切换
  handleTransferInChange = async (e) => {
    let purposeAmt = await this.getAccountPurposeAmount(e);
    this.setState({ inPurPose: e, transferInPurposeAmt: purposeAmt }, () => {
      this.getAfterTransferAmt();
    });
  };

  // 重置数据
  handleReset = () => {
    this.props.form.resetFields();
    this.setState({
      payamt: 0,
      outPurPose: undefined, // 转出账户用途
      inPurPose: undefined, // 转入账户用途
      transferOutPurposeAmt: 0.00,
      transferInPurposeAmt: 0.00,
      afterTransferAmt: 0.00,
    });
  };

  // 计算转入后的金额
  getAfterTransferAmt = () => {
    const { payamt, inPurPose, transferInPurposeAmt } = this.state;
    if (payamt && inPurPose) {
      this.setState({ afterTransferAmt: Util.retainDecimalPlaces(parseFloat(payamt) + parseFloat(transferInPurposeAmt), 2) });
    } else {
      this.setState({ afterTransferAmt: 0.00 });
    }
  };

  render() {
    const { width, title } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { visible, selectData, transferOutPurposeAmt, transferInPurposeAmt, afterTransferAmt, outPurPose, payamt, okLoading } = this.state;

    return (
      <div>
        <Modal
          width={width || '520px'}
          title={title || '账内用途转账'}
          maskClosable={false}
          visible={visible}
          okButtonProps={{
            loading: okLoading
          }}
          onOk={this.handleOk}
          onCancel={() => this.modifyVisible(false)}
        >
          <div className="in-account-transfer-form">
            <Form>
              <div>
                <Form.Item label="转出用途" {...this.formItemInput}>
                  {getFieldDecorator('outPurPose', {
                    initialValue: undefined,
                    rules: [{ required: true, message: '转出用途不能为空！' }],
                  })(
                    <Select
                      allowClear
                      showSearch
                      style={{ width: '100%' }}
                      placeholder="请选择"
                      optionFilterProp="search"
                      onChange={this.handleTransferOutChange}
                    >
                      {React.$SelectOptions(selectData?.accPurpose || [], 'code')}
                    </Select>
                  )}
                </Form.Item>
              </div>
              <Row style={{ marginBottom: '10px' }}>
                <Col span={this.formItemInput?.labelCol?.span || 7}></Col>
                <Col span={this.formItemInput?.wrapperCol?.span || 14} className="flex-between-center">
                  <div>
                    <span className="common-remark-label">可用余额：</span>
                    <span className="common-number">¥ {transferOutPurposeAmt}</span>
                  </div>
                  <div>
                    <span className="span" style={{ fontSize: '14px' }} onClick={this.handleAllTransferOut}>全部转出</span>
                  </div>
                </Col>
              </Row>
              <div style={{ marginBottom: '16px' }}>
                <Form.Item
                  label="转出金额(元)"
                  {...this.formItemInput}
                  validateStatus={payamt && (parseFloat(payamt) > parseFloat(transferOutPurposeAmt) || parseFloat(payamt) < 0) ? 'error' : undefined}
                  help={payamt && parseFloat(payamt) > parseFloat(transferOutPurposeAmt) ? '转出金额不能大于可用余额！' : (payamt && parseFloat(payamt) < 0 ? '转出金额不能小于0！' : undefined)}
                >
                  {getFieldDecorator('payamt', {
                    initialValue: undefined,
                    rules: [{ required: true, message: '转出金额不能为空！' }],
                  })(
                    <Input
                      placeholder="请输入"
                      type="number"
                      className="input-number"
                      style={{ width: '100%' }}
                      onChange={this.handleTransferOutAmtChange}
                    />
                  )}
                </Form.Item>
              </div>
              <div>
                <Form.Item label="转入用途" {...this.formItemInput}>
                  {getFieldDecorator('inPurPose', {
                    initialValue: undefined,
                    rules: [{ required: true, message: '转入用途不能为空！' }],
                  })(
                    <Select
                      allowClear
                      showSearch
                      style={{ width: '100%' }}
                      placeholder="请选择"
                      optionFilterProp="search"
                      onChange={this.handleTransferInChange}
                    >
                      {React.$SelectOptions((selectData?.accPurpose || []).filter(item => (item?.code || item.id || '') !== outPurPose), 'code')}
                    </Select>
                  )}
                </Form.Item>
              </div>
              <Row style={{ marginBottom: '24px' }}>
                <Col span={this.formItemInput?.labelCol?.span || 7}></Col>
                <Col span={this.formItemInput?.wrapperCol?.span || 14}>
                  <span className="common-remark-label">当前余额：</span>
                  <span className="span">¥ {transferInPurposeAmt}</span>
                  <span style={{ marginLeft: '20px' }} className="common-remark-label">转入后余额：</span>
                  <span className="span">¥ {afterTransferAmt}</span>
                </Col>
              </Row>
            </Form>
          </div>
        </Modal>
      </div>
    );
  }
};

const InAccountTransferForm = Form.create()(InAccountTransfer);
export default InAccountTransferForm;