/**
 * Created by mar105 on 2019-02-13.
 */
/* eslint-disable no-undef,import/first,prefer-destructuring,jsx-a11y/alt-text */
import React, { Component } from 'react';
import { Input, message } 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';

const { TextArea } = Input;
export default class BatchPriceUpdate extends Component {
  /**   构造函数   */
  constructor(props) {
    super(props);
    this.state = {};
    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, masterConfig, slaveConfig, checkConfig, slaveSelectedRowKeys, batchPriceUpdateData, sModelsType,
    } = this.props;
    const dProductPrice = document.getElementById('dProductPriceNew').value; /* 外币单价 */
    const dProductQty = document.getElementById('dProductQtyNew').value;
    const OldProductQty = document.getElementById('dProductQty').value;
    const dProductMoney = document.getElementById('dProductMoneyNew').value; /* 外币金额 */
    const sChangePriceMemo = document.getElementById('sChangePriceMemo').value; /* 价格批量更新备注 */
    const models = sModelsType.includes('sales/') || sModelsType.includes('manufacture/') || sModelsType.includes('productStock/') ? 'Product' : 'Materials';
    let dMaterialsQtyOld = 0;
    let dMaterialsQtyNew = 0;
    if (models !== 'Product') {
      dMaterialsQtyOld = document.getElementById('dMaterialsQty').value;
      dMaterialsQtyNew = document.getElementById('dMaterialsQtyNew').value;
    }

    if (this.formatOk > -1) {
      message.warning(commonFunc.showMessage(app.commonConst, 'DecimalOut'));
      return;
    }
    /*   数据参数   */
    const value = {
      sProName: 'Sp_System_BatchPriceMoney',
      paramsMap: {
        sFormGuid: sModelsId,
        sSrcGuid: slaveSelectedRowKeys[0],
        dPrice: dProductPrice,
        dMoney: dProductMoney,
        dQty: dProductQty,
        oldQty: OldProductQty,
        oldMaterialsQty: dMaterialsQtyOld,
        dMaterialsQty: dMaterialsQtyNew,
        tDeliverDate: batchPriceUpdateData[0].tDeliverDate,
        sChangePriceMemo,
      },
    };
    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('dProductMoneyNew').value = '';
      document.getElementById('dProductQtyNew').value = '';
      if (models !== 'Product') {
        document.getElementById('dMaterialsQtyNew').value = '';
      }
      this.props.onGetData(masterConfig, slaveConfig, checkConfig);
    } else { /*   失败   */
      this.props.getServiceError({ msg: commonFunc.showMessage(app.commonConst, 'priceSaveSucess') + returnData.msg });
    }
    this.props.onSaveState({
      visibleBatchPriceUpdate: false,
      enabled: false,
    });
  };

  handleCancel = () => {
    this.props.onSaveState({
      visibleBatchPriceUpdate: false,
      enabled: false,
    });
  };
  handleChange = (name, tableDataRow) => {
    const {
      slaveConfig, app, masterData, sModelsType,
    } = this.props;
    const dPprice = this.props.getFloatNum('dProductPrice'); /* 获取系统设定小数位 */
    const dPmoney = this.props.getFloatNum('dProductMoney');
    const priceValue = document.getElementById('dProductPriceNew').value;
    const dProductQty = document.getElementById('dProductQty').value;
    const dProductQtyNew = document.getElementById('dProductQtyNew').value;
    const models = sModelsType.includes('sales/') || sModelsType.includes('manufacture/') || sModelsType.includes('productStock/') ? 'Product' : 'Materials';
    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 (models === 'Product') {
            const tableDataRowNew = JSON.parse(JSON.stringify(tableDataRow));
            tableDataRowNew.dProductForeignPrice = priceValue;
            tableDataRowNew.dProductQty = dProductQtyNew;
            const batchPriceUpdateObj = commonBusiness.getCalculateAllMoney(app, models, 'dProductForeignPrice', masterData, tableDataRowNew);
            const productMoney = batchPriceUpdateObj.dProductForeignMoney;
            // const productMoney = priceValue * dProductQtyNew;
            document.getElementById('dProductPriceNew').value = priceValue;
            document.getElementById('dProductMoneyNew').value = productMoney.toFixed(dPmoney);
          } else {
            const dMaterialsQtyNew = document.getElementById('dMaterialsQtyNew').value; /* 换算数量 */
            const productMoney = priceValue * dMaterialsQtyNew;
            document.getElementById('dProductPriceNew').value = priceValue;
            document.getElementById('dProductMoneyNew').value = productMoney.toFixed(dPmoney);
          }
        }
      }
      if (name === 'dProductMoneyNew') { /* 改变外币金额 */
        const moneyValue = document.getElementById('dProductMoneyNew').value;
        const pointRep = moneyValue.match(rep); /* 匹配小数,若为整数，则为空 */
        const point = moneyValue.replace(rep, '$1');/* 通过正则表达式获取小数位后长度 */
        if (isNaN(moneyValue)) {
          this.formatOk = 1;
          message.warning(commonFunc.showMessage(app.commonConst, 'formatCheck'));
          return;
        }
        if (pointRep !== null && point.length > dPmoney) {
          this.formatOk = 1;
          message.warning(commonFunc.showMessage(app.commonConst, 'maxPointLength') + dPmoney);
        } else {
          this.formatOk = -1;/* 确定时，输入规则正常标志 */
          if (dProductQty !== 0) {
            if (models === 'Product') {
              const tableDataRowNew = JSON.parse(JSON.stringify(tableDataRow));
              tableDataRowNew.dProductForeignMoney = moneyValue; /* 外币金额 */
              tableDataRowNew.dProductQty = dProductQty;
              const batchPriceUpdateObj = commonBusiness.getCalculateAllMoney(app, models, 'dProductForeignMoney', masterData, tableDataRowNew);
              const priceValue = batchPriceUpdateObj.dProductForeignPrice;
              // const priceValue = moneyValue / dProductQty;
              document.getElementById('dProductPriceNew').value = commonUtils.convertFixNum(priceValue, dPprice);
              document.getElementById('dProductMoneyNew').value = moneyValue;
            } else {
              const dMaterialsQtyNew = document.getElementById('dMaterialsQtyNew').value; /* 换算数量 */
              const priceValue = moneyValue / dMaterialsQtyNew; /* 采购单价改变时，金额=单价*换算数量 */
              document.getElementById('dProductPriceNew').value = commonUtils.convertFixNum(priceValue, dPprice);
              document.getElementById('dProductMoneyNew').value = moneyValue;
            }
          }
        }
      }
      if (name === 'dProductQtyNew') { /* 改变订单数量 */
        const qtyValue = document.getElementById('dProductQtyNew').value;
        const pointRep = qtyValue.match(rep); /* 匹配小数,若为整数，则为空 */
        const point = qtyValue.replace(rep, '$1');/* 通过正则表达式获取小数位后长度 */
        if (isNaN(qtyValue)) {
          this.formatOk = 1;
          message.warning(commonFunc.showMessage(app.commonConst, 'formatCheck'));
          return;
        }
        if (pointRep !== null && point.length > 6) {
          this.formatOk = 1;
          message.warning('最多6位小数！');
        } else {
          this.formatOk = -1;/* 确定时，输入规则正常标志 */
          if (dProductQty !== 0 && commonUtils.isNotEmptyObject(tableDataRow)) {
            if (models === 'Product') { /* 调用通用价格计算 */
              const tableDataRowNew = JSON.parse(JSON.stringify(tableDataRow));
              tableDataRowNew.dProductForeignPrice = priceValue;
              tableDataRowNew.dProductQty = qtyValue;
              const batchPriceUpdateObj = commonBusiness.getCalculateAllMoney(app, models, 'dProductQty', masterData, tableDataRowNew);
              const moneyValue = batchPriceUpdateObj.dProductForeignMoney;
              // const moneyValue = priceValue * qtyValue;
              document.getElementById('dProductMoneyNew').value = commonUtils.convertFixNum(moneyValue, dPprice);
              document.getElementById('dProductQtyNew').value = qtyValue;
            } else {
              const tableDataRowNew = JSON.parse(JSON.stringify(tableDataRow));
              tableDataRowNew.dAuxiliaryQty = qtyValue;
              /* 输入数量 算换算数量 */
              let batchPriceUpdateObj = commonBusiness.getMaterialsQty(app, tableDataRowNew, 'dAuxiliaryQty', 'dMaterialsQty');
              document.getElementById('dMaterialsQtyNew').value = batchPriceUpdateObj.dMaterialsQty;
              batchPriceUpdateObj = commonBusiness.getCalculateAllMoney(app, models, 'dMaterialsQty', masterData, batchPriceUpdateObj);
              document.getElementById('dProductMoneyNew').value = batchPriceUpdateObj[`d${models}Money`];
            }
          }
        }
      }
      if (name === 'dMaterialsQtyNew') {
        const dMaterialsQtyNew = document.getElementById('dMaterialsQtyNew').value;
        const qtyValue = document.getElementById('dMaterialsQtyNew').value;
        if (isNaN(qtyValue)) {
          this.formatOk = 1;
          message.warning(commonFunc.showMessage(app.commonConst, 'formatCheck'));
          return;
        }
        this.formatOk = -1;/* 确定时，输入规则正常标志 */
        if (dMaterialsQtyNew !== 0 && commonUtils.isNotEmptyObject(tableDataRow)) {
          if (models !== 'Product') {
            const tableDataRowNew = JSON.parse(JSON.stringify(tableDataRow));
            tableDataRowNew.dMaterialsQty = qtyValue;
            tableDataRowNew[`d${models}Price`] = priceValue;
            /* 输入换算数量 算数量 */
            let batchPriceUpdateObj = commonBusiness.getAuxiliaryQty(app, tableDataRowNew, 'dMaterialsQty', 'dAuxiliaryQty');
            document.getElementById('dProductQtyNew').value = batchPriceUpdateObj.dAuxiliaryQty;
            batchPriceUpdateObj = commonBusiness.getCalculateAllMoney(app, models, 'dMaterialsQty', masterData, batchPriceUpdateObj);
            document.getElementById('dProductMoneyNew').value = batchPriceUpdateObj[`d${models}Money`];
          }
        }
      }
    }
  };

  /**   渲染   */
  render() {
    const {
      batchPriceUpdateData, visibleBatchPriceUpdate, app, sModelsType,
    } = this.props;
    // const pane = app.panes.filter(paneTmp => paneTmp.key === sTabId)[0];
    const disabled = true;
    const priceBatchUpdate = commonFunc.showMessage(app.commonConst, 'priceBatchUpdate');/* 价格批量更新 */
    const OldQty = commonFunc.showMessage(app.commonConst, 'OldQty');/* 原数量 */
    const OldMaterialsQty = commonFunc.showMessage(app.commonConst, 'OldMaterialsQty');/* 原换算数量 */
    const OldPrice = commonFunc.showMessage(app.commonConst, 'OldPrice');/* 原单价 */
    const OldTotalMoney = commonFunc.showMessage(app.commonConst, 'OldTotalMoney');/* 原金额 */
    const qty = commonFunc.showMessage(app.commonConst, 'qty');/* 数量 */
    const materialsQty = commonFunc.showMessage(app.commonConst, 'materialsQty');/* 换算数量 */
    const price = commonFunc.showMessage(app.commonConst, 'price');/* 单价 */
    const money = commonFunc.showMessage(app.commonConst, 'money');/* 金额 */
    // const sChangePriceMemoTitle = commonFunc.showMessage(app.commonConst, 'sChangePriceMemoTitle');/* 价格批量更新备注 */

    /* 通用价格批量更新 */
    let dQty = 0;
    let dPrice = 0;
    let dMoney = 0;
    let dMaterialsQty = 0;
    let models = '';
    let batchPriceUpdateObj = {};
    if (commonUtils.isNotEmptyObject(sModelsType)) {
      models = sModelsType.includes('sales/') || sModelsType.includes('manufacture/') || sModelsType.includes('productStock/') ? 'Product' : 'Materials';
      const sFieldName = sModelsType.includes('sales/') || sModelsType.includes('manufacture/') || sModelsType.includes('productStock/') ? 'dProductQty' : 'dAuxiliaryQty';
      batchPriceUpdateObj = commonUtils.isNotEmptyArr(batchPriceUpdateData) ? batchPriceUpdateData[0] : {};
      if (commonUtils.isNotEmptyObject(batchPriceUpdateObj)) {
        dQty = batchPriceUpdateObj[sFieldName];
        if (models === 'Product') { /* 产品 取外币单价、外币金额 */
          dPrice = batchPriceUpdateObj[`d${models}ForeignPrice`];
          if (commonUtils.isEmptyNumber(dPrice) || dPrice === 0) { /* 外币单价为0时，等于本位币单价 */
            dPrice = batchPriceUpdateObj[`d${models}Price`];
          }

          dMoney = batchPriceUpdateObj[`d${models}ForeignMoney`];
          if (commonUtils.isEmptyNumber(dMoney) || dMoney === 0) { /* 外币金额为0时，等于本位币金额 */
            dMoney = batchPriceUpdateObj[`d${models}Money`];
          }
        } else {
          dPrice = batchPriceUpdateObj[`d${models}Price`];
          dMoney = batchPriceUpdateObj[`d${models}Money`];
        }
        dMaterialsQty = batchPriceUpdateObj.dMaterialsQty;
      }
    }

    return (
      <div className={styles.toolBar}>
        { visibleBatchPriceUpdate ?
          <AntdDraggableModal
            title={priceBatchUpdate}
            visible={visibleBatchPriceUpdate}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            destroyOnClose
          >
            <div className="priceUpdate">
              {
                batchPriceUpdateData !== undefined ?
                  <div style={{ marginBottom: 16 }}>
                    <Input addonBefore={OldQty} id="dProductQty" disabled={disabled} defaultValue={dQty} value={dQty} />
                    {
                      models === 'Product' ? '' :
                      <Input addonBefore={OldMaterialsQty} id="dMaterialsQty" disabled={disabled} defaultValue={dMaterialsQty} value={dMaterialsQty} />
                    }

                    <Input addonBefore={OldPrice} disabled={disabled} defaultValue={dPrice} value={dPrice} />
                    <Input addonBefore={OldTotalMoney} disabled={disabled} defaultValue={dMoney} value={dMoney} />
                    <Input id="dProductQtyNew" addonBefore={qty} onChange={this.handleChange.bind(this, 'dProductQtyNew', batchPriceUpdateObj)} defaultValue={dQty} />
                    {
                      models === 'Product' ? '' :
                      <Input id="dMaterialsQtyNew" addonBefore={materialsQty} onChange={this.handleChange.bind(this, 'dMaterialsQtyNew', batchPriceUpdateObj)} defaultValue={dMaterialsQty} />
                    }
                    <Input id="dProductPriceNew" addonBefore={price} onChange={this.handleChange.bind(this, 'dProductPriceNew', batchPriceUpdateObj)} defaultValue={dPrice} />
                    <Input id="dProductMoneyNew" addonBefore={money} onChange={this.handleChange.bind(this, 'dProductMoneyNew', batchPriceUpdateObj)} defaultValue={dMoney} />
                    <TextArea id="sChangePriceMemo" rows={2} defaultValue="" />
                  </div>
                  : null }
            </div>
          </AntdDraggableModal>
          : '' }
      </div>
    );
  }
}
