import React, { Component } from 'react';
import { Form } from '@ant-design/compatible';
// import '@ant-design/compatible/assets/index.css';
import { Layout, Spin, message } from 'antd-v4'; // Button
import CommonListEvent from '@/components/Common/CommonListEvent';/* 继承销售模块业务功能 */
import * as commonFunc from '@/components/Common/commonFunc';/* 通用单据方法 */ /* 通用单据方法 */
import StaticEditTable from '@/components/Common/CommonTable';/* 可编辑表格 */
import CommonBase from '@/components/Common/CommonBase';/* 获取配置及数据 */
import * as commonBusiness from '@/components/Common/commonBusiness';/* 单据业务功能 */
// import SearchComponent from '@/components/Common/SearchComponent'; /* 搜索组件 */
import commonConfig from '@/utils/config';
import CommonView from '@/components/Common/CommonViewNew';
import * as commonServices from '@/services/services';/*   服务类   */
import * as commonUtils from '@/utils/utils';/* 通用方法 */
import styles from '@/index.less';

const { Content } = Layout;

class UnifiedPlanning extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  componentWillReceiveProps(nextProps) {
    const { masterData: OldmasterData, slaveData } = nextProps;
    const masterData = { ...OldmasterData };
    if (commonUtils.isNotEmptyObject(masterData) && commonUtils.isEmpty(masterData.tCurrTime) && commonUtils.isNotEmptyArr(slaveData)) {
      const currDate = new Date();
      const time = `${currDate.getFullYear()}-${currDate.getMonth() + 1}-${currDate.getDate()} ${currDate.getHours()}:${currDate.getMinutes()}`;
      masterData.tCurrTime = time;
      slaveData.forEach((item, index) => {
        slaveData[index] = { ...item, tCStartTime: time };
      });
      this.props.onSaveState({ masterData, slaveData });
    }
  }
  /**   确认下单   */
  handleSelect = () => {
    const { slaveSelectedData, app } = this.props;
    this.props.app.currentPane.select(app.currentPane.name, app.currentPane.config, slaveSelectedData);
    this.props.app.currentPane.selectCancel(app.currentPane.name);
  };
  /**   关闭   */
  handleCancelModal = () => {
    const { app } = this.props;
    this.props.app.currentPane.selectCancel(app.currentPane.name);
  };

  handleMasterChange = (name, sFieldName, changeValue, sId, dropDownData) => {
    const { slaveData } = this.props;
    const returnData = this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, true);
    if (sFieldName === 'tCurrTime') {
      slaveData.forEach((item, i) => {
        slaveData[i] = {
          ...item, tCStartTime: changeValue[sFieldName], bIsCalculation: false, handleType: 'update',
        };
      });
      this.props.onSaveState({ ...returnData, slaveData });
    }
  }

 handleTableChange = (name, sFieldName, changeValue, sId, dropDownData) => {
   const {
     [`${name}Data`]: tableData,
   } = this.props;
   const iIndex = tableData.findIndex(item => item.sId === sId);
   tableData[iIndex] = this.props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
   if (sFieldName === 'sCurrStatus') {
     // {"1":"正常运行","2":"正常","3":"返回重排"}
     if (changeValue[sFieldName] === '3') {
       tableData[iIndex] = { ...tableData[iIndex], tCStartTime: undefined };
     }
   }
   if (tableData[iIndex].bIsCalculation) {
     tableData.forEach((item, i) => {
       tableData[i] = { ...item, bIsCalculation: false };
     });
   }
   this.setState({ [`${name}Data`]: tableData });
 }
  //  按钮操作
  handleButtonClick = (itag, btnName) => {
    if (btnName === 'BtnCalculation') {
      this.handleCalculation();
    }
  };
  handleCalculation = async () => {
    // 获得滚动条div
    const dom = document.getElementById('productionPlanning').getElementsByClassName('ant-table-body')[0];
    const { slaveData } = this.props;
    if (commonUtils.isNotEmptyArr(slaveData)) {
      let calculation = true;
      const slaveWarning = slaveData.filter(item => item.sCurrStatus === '1' || item.sCurrStatus === '2' || item.sCurrStatus === '3');
      if (commonUtils.isEmptyArr(slaveWarning)) {
        message.error('必须选择机器运行状态！');
        return;
      }
      for (const item of slaveData) {
        if (commonUtils.isNotEmptyObject(item.sCurrStatus) && item.sCurrStatus === '2' && (item.dWeek === undefined || item.dWeek <= 0)) {
          calculation = false;
          message.error('暂停状态下周期不能小于0');
          break;
        }
      }
      if (calculation) {
        this.props.onSaveState({ pageLoading: true });
        let iCount = 0;
        if (commonUtils.isNotEmptyArr(slaveData)) {
          const slaveDataError = slaveData.filter(item => commonUtils.isNotEmptyObject(item.sCurrStatus) && (item.sCurrStatus === '2' || item.sCurrStatus === '3'));
          const slaveDataFilter = slaveData.filter(item => commonUtils.isNotEmptyObject(item.sCurrStatus) && item.sCurrStatus === '1');
          if (commonUtils.isNotEmptyArr(slaveDataError)) { /* 先执行故障机器，返回重拍机器 */
            for (const item of slaveDataError) {
              const iIndex = slaveData.findIndex(data => data.sId === item.sId);
              if (iIndex > -1) {
                const isCalculation = await (this.handleCalculationProcedureCall('Sp_unifiedPlanning_BtnCalculation', JSON.stringify({ params: [{ ...item, isClear: iCount, iCount: slaveData.length }] })));
                if (isCalculation) {
                  slaveData[iIndex] = { ...slaveData[iIndex], bIsCalculation: isCalculation };
                  this.props.onSaveState({ slaveData });
                  iCount += 1;
                  if (iCount > 5) {
                    // 设置滚动条的高度
                    dom.scrollTop = (iCount - 5) * 27.5;
                  }
                }
              }
            }
          }
          if (commonUtils.isNotEmptyArr(slaveDataFilter)) {
            for (const item of slaveDataFilter) {
              const iIndex = slaveData.findIndex(data => data.sId === item.sId);
              if (iIndex > -1) {
                const isCalculation = await (this.handleCalculationProcedureCall('Sp_unifiedPlanning_BtnCalculation', JSON.stringify({ params: [{ ...item, isClear: iCount, iCount: slaveData.length }] })));
                if (isCalculation) {
                  slaveData[iIndex] = { ...slaveData[iIndex], bIsCalculation: isCalculation };
                  this.props.onSaveState({ slaveData });
                  iCount += 1;
                  if (iCount > 5) {
                    // 设置滚动条的高度
                    dom.scrollTop = (iCount - 5) * 27.5;
                  }
                }
              }
            }
          }
        }
        this.props.onSaveState({ pageLoading: false });
        this.props.app.currentPane.selectCancel();
      }
    }
  }
  // 计算
  handleCalculationProcedureCall = async (proName, proInParam, other) => {
    const { app, sModelsId } = this.props;
    const value = { sProName: proName, sProInParam: proInParam };
    if (other?.iFlag === 1) {
      value.iFlag = 1;
    }
    const url = `${commonConfig.server_host}procedureCall/doGenericProcedureCall?sModelsId=${sModelsId}`;
    const returnData = (await commonServices.postValueService(app.token, value, url)).data;
    if (returnData.code === 1) {
      return true;
    } else {
      this.props.getServiceError({ ...returnData, fn: () => this.handleCalculationProcedureCall(proName, proInParam, { iFlag: 1 }) });
      return false;
    }
  }
  // ----------------------------数据修改回带end  ---------------------------- //

  render() {
    const { pageLoading } = this.props;
    return (
      <div style={{ height: '100%' }}>
        <Spin spinning={pageLoading}>
          <div style={{ height: '100%' }}>
            <UnifiedPlanningComponent
              {...this.props}
              {...this.state}
              onSelect={this.handleSelect}
              onCancel={this.handleCancelModal}
              onDoubleClick={this.handleSelect}
              onChange={this.handleMasterChange}
              onDataChange={this.handleTableChange}
              onBtnClick={this.handleButtonClick}
            />
          </div>
        </Spin>
      </div>
    );
  }
}

const UnifiedPlanningComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form);
    return obj;
  },
})((props) => {
  const { form, onReturnForm, slavePagination } = props;
  /*   回带表单   */
  onReturnForm(form);
  const pagination = {
    ...slavePagination,
    size: 'large',
    pageSize: 1000,
    showQuickJumper: true,
    hideOnSinglePage: true,
  };
  const tableProps = {
    ...commonBusiness.getTableTypes('slave', props),
    tableProps: {
      rowSelection: null, rowKey: 'sSlaveId', pagination, onChange: props.onTitleChange,
    },
  };
  /*
  <div style={{ textAlign: 'right', marginRight: '9px', marginBottom: '9px' }}>
    <Button key="back" style={{ marginRight: '8px' }} onClick={props.onCancel}>取消</Button>
    <Button type="primary" onClick={props.onSelect}>确认</Button>
  </div>
  */
  return (
    <Form >
      <Layout>
        <Layout>
          <div id="modalChooseProcess">
            <div className={styles.content} id="productionPlanningMaster">
              <CommonView {...commonBusiness.getWriteTypes('master', props)} />
            </div>
            <Content className="xly-normal-list" id="productionPlanning">
              <StaticEditTable {...tableProps} noVlist footer="hidden" />
            </Content>
          </div>
        </Layout>
      </Layout>
    </Form>
  );
});

export default CommonBase(CommonListEvent(UnifiedPlanning));
