/**
 * 此组件用于生产工单列表批量更新价格 by pm 20210518
 */
/* eslint-disable no-undef,import/first,prefer-destructuring,jsx-a11y/alt-text */
import React, { Component } from 'react';
import { Input, message, Radio } from 'antd-v4';
import styles from '../../index.less';
import * as commonBusiness from '../Common/commonBusiness';
import * as commonServices from '../../services/services'; /*   服务类   */
import commonConfig from '../../utils/config';
import * as commonUtils from '../../utils/utils';
import * as commonFunc from '../Common/commonFunc';
import AntdDraggableModal from '../Common/AntdDraggableModal';

export default class BatchWorkListPriceUpdate extends Component {
  /**   构造函数   */
  constructor(props) {
    super(props);
    this.state = {
      radioValue: 1,

    };
    this.formatOk = -1;
  }

  handleBtnSave = () => {
    const {
      reportData, reportDelData, reportConfig,
    } = this.props;
    const data = [];
    if (!commonBusiness.validateTable(reportConfig, reportData)) {
      return;
    }
    data.push(commonBusiness.mergeData('report', 'sysreport', reportData, reportDelData));
    this.handleSaveData({ data, sClientType: '1', optName: commonFunc.showMessage(app.commonConst, 'priceSaveSucess') });
  };
  handleSaveData = async (params) => {
    const {
      token, sModelsId, masterData,
    } = this.props;
    const returnData = await commonBusiness.saveData({ token, value: params, sModelsId });
    if (returnData.code === 1) {
      this.props.onSaveState({
        enabled: false, currentId: masterData.sId,
      });
      this.getReportData();
    } else {
      this.props.getServiceError(returnData);
    }
  };

  handleOk = async () => {
    const {
      sModelsId, app, slaveConfig, slaveSelectedRowKeys, slaveFilterCondition,
    } = this.props;
    const { radioValue } = this.state;
    const dProductPrice = document.getElementById('dProductPriceNew').value;
    const dFlowRate = document.getElementById('dFlowRate').value; /* 上浮比率 */

    if (this.formatOk > -1) {
      message.warning(commonFunc.showMessage(app.commonConst, 'DecimalOut'));
      return;
    }
    /* 勾选行文本框作为单价的参数 */
    let dNProductPrice = 0;
    let dFloatRate = 0;
    /*   数据参数   */
    const value = {
      sProName: 'Sp_System_BatchWorkListPriceMoney',
      paramsMap: {
        sFormGuid: sModelsId, sSrcGuid: slaveSelectedRowKeys,
      },
    };
    if (radioValue === 1) { /* 上浮比率 */
      dFloatRate = dFlowRate;
      value.paramsMap.dFloatRate = dFloatRate;
    } else if (radioValue === 2) {
      dNProductPrice = dProductPrice;
      value.paramsMap.dNProductPrice = dNProductPrice;
    }
    const url = `${commonConfig.server_host}business/updatePriceBatch?sModelsId=${sModelsId}`;
    const returnData = (await commonServices.postValueService(app.token, value, url)).data;
    if (returnData.code === 1) { /*   成功   */
      message.success(commonFunc.showMessage(app.commonConst, 'priceSaveSucess') + returnData.msg);
      document.getElementById('dProductPriceNew').value = '';
      document.getElementById('dFlowRate').value = '';
      this.props.onGetData(slaveConfig, slaveFilterCondition);
    } else { /*   失败   */
      this.props.getServiceError({ msg: commonFunc.showMessage(app.commonConst, 'priceSaveSucess') + returnData.msg });
    }
    this.props.onSaveState({
      visibleBatchWorkListPriceUpdate: false,
      enabled: false,
    });
  };

  handleCancel = () => {
    this.props.onSaveState({
      visibleBatchWorkListPriceUpdate: false,
      enabled: false,
    });
  };
  handleRadioChange = (e) => {
    this.setState({
      radioValue: e.target.value,
    });
  };

  handleChange = (name) => {
    const { slaveConfig, app } = this.props;
    const dPprice = this.props.getFloatNum('dProductPrice'); /* 获取系统设定小数位 */
    const priceValue = document.getElementById('dProductPriceNew').value;
    const iNewIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.sName === 'dProductPrice');
    if (iNewIndex > -1 && (commonUtils.isNotEmptyObject(slaveConfig.gdsconfigformslave[iNewIndex].sMaxValue) || commonUtils.isNotEmptyObject(slaveConfig.gdsconfigformslave[iNewIndex].sMinValue))) {
      const product = slaveConfig.gdsconfigformslave[iNewIndex];
      document.getElementById('dProductMoneyNew').value = 0;
      if (commonUtils.isNotEmptyObject(product.sMaxValue) && parseFloat(product.sMaxValue, dPprice) < parseFloat(priceValue, dPprice)) {
        message.warning(commonFunc.showMessage(app.commonConst, 'maxValue') + product.sMaxValue);
      }
      if (commonUtils.isNotEmptyObject(product.sMinValue) && parseFloat(product.sMinValue, dPprice) < parseFloat(priceValue, dPprice)) {
        message.warning(commonFunc.showMessage(app.commonConst, 'minValue') + product.sMinValue);
      }
    } else {
      const rep = /\d+\.(\d*)/;
      if (name === 'dProductPriceNew') {
        const pointRep = priceValue.match(rep); /* 匹配小数,若为整数，则为空 */
        const point = priceValue.replace(rep, '$1');/* 通过正则表达式获取小数位后长度 */
        if (isNaN(priceValue)) {
          this.formatOk = 1;
          message.warning(commonFunc.showMessage(app.commonConst, 'formatCheck'));
          return;
        }
        if (pointRep !== null && point.length > dPprice) {
          this.formatOk = 1;
          document.getElementById('dProductMoneyNew').value = 0;
          message.warning(commonFunc.showMessage(app.commonConst, 'maxPointLength') + dPprice);
        } else if (pointRep === null && priceValue.length > 9) { /* 整数超9位 */
          message.warning(`${commonFunc.showMessage(app.commonConst, 'maxIntegerLength')}9`);
          this.formatOk = 1;
        } else {
          this.formatOk = -1;/* 确定时，输入规则正常标志 */
        }
      }
      if (name === 'dFlowRate') {
        const dFlowRate = document.getElementById('dFlowRate').value; /* 上浮比率 */
        const pointRep = dFlowRate.match(rep); /* 匹配小数,若为整数，则为空 */
        const point = dFlowRate.replace(rep, '$1');/* 通过正则表达式获取小数位后长度 */
        if (isNaN(dFlowRate)) {
          this.formatOk = 1;
          message.warning(commonFunc.showMessage(app.commonConst, 'formatCheck'));
          return;
        }
        if (pointRep !== null && point.length > dPprice) {
          this.formatOk = 1;
          message.warning(commonFunc.showMessage(app.commonConst, 'maxPointLength') + dPprice);
        } else {
          this.formatOk = -1;/* 确定时，输入规则正常标志 */
        }
      }
    }
  };

  /**   渲染   */
  render() {
    const {
      batchPriceWorkListUpdateData, visibleBatchWorkListPriceUpdate, app,
    } = this.props;
    const priceBatchUpdate = commonFunc.showMessage(app.commonConst, 'workPriceBatchUpdate');/* 价格批量更新 */
    const sOrderMoney = commonFunc.showMessage(app.commonConst, 'sOrderMoney');/* 订货单价标题 */
    const sFlowRate = commonFunc.showMessage(app.commonConst, 'sFlowRate');/* 浮动比率%标题 */
    return (
      <div className={styles.toolBar}>
        { visibleBatchWorkListPriceUpdate ?
          <AntdDraggableModal
            title={priceBatchUpdate}
            visible={visibleBatchWorkListPriceUpdate}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            destroyOnClose
            body={{ width: '400px' }}
          >
            <div className="priceUpdatelist">
              {
                batchPriceWorkListUpdateData !== undefined ?
                  <div style={{ marginBottom: 16 }}>
                    <Radio.Group name="radiogroup" onChange={this.handleRadioChange} value={this.state.radioValue}>
                      <Radio style={{ height: '38px', lineHeight: '36px' }} value={1}> <Input id="dFlowRate" disabled={this.state.radioValue === 2} bordered addonBefore={sFlowRate} onChange={this.handleChange.bind(this, 'dFlowRate')} /> </Radio> <br />
                      <Radio style={{ height: '38px', lineHeight: '36px' }} value={2}> <Input id="dProductPriceNew" disabled={this.state.radioValue === 1} bordered addonBefore={`${sOrderMoney}  `} onChange={this.handleChange.bind(this, 'dProductPrice')} /></Radio>
                    </Radio.Group>
                  </div>
                  : null }
            </div>
          </AntdDraggableModal>
          : '' }
      </div>
    );
  }
}
