/**
 * 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 { Form } from '@ant-design/compatible';
// import '@ant-design/compatible/assets/index.css';
import { Input, message } from 'antd-v4';
import * as commonUtils from '../../utils/utils';
import ShowType from './CommonComponent';/* 通用方法 */
import AntdDraggableModal from '../Common/AntdDraggableModal';
import moment from 'moment';
import * as commonFunc from "@/components/Common/commonFunc";
import * as commonBusiness from '@/components/Common/commonBusiness'; /* 单据业务功能 */

const { TextArea } = Input;
const FormItem = Form.Item;
export default class SlaveMemo extends Component {
  /**   构造函数   */
  constructor(props) {
    super(props);
    this.handleTextareaChange = this.handleTextareaChange.bind(this);
    this.state = { textareaValue: '' };
    this.max = 2000;
    this.min = 0;
    this.sDateFormat = 'YYYY-MM-DD';
    this.bInit = true; // 是否初始化
    // this.isChoosedate = btnName.toLowerCase().endsWith('choosedate');
  }

  componentWillMount() {
    this.componentWillReceiveProps(this.props);
  }

  componentWillReceiveProps(nextProps) {
    /*   state和this属性赋值   */
    const { sCurrMemoProps } = nextProps;
    if (this.bInit && sCurrMemoProps && sCurrMemoProps.bVisibleMemo) {
      this.bInit = false;
      if (commonUtils.isNotEmptyObject(sCurrMemoProps) && sCurrMemoProps.btnName === undefined) {
        this.setState({ textareaValue: nextProps.sCurrMemoProps.sValue });
      } else {
        this.setState({ textareaValue: nextProps.sValue });
      }
      if (commonUtils.isNotEmptyObject(sCurrMemoProps)) {
        this.max = commonUtils.convertStrToNumber(commonUtils.isNotEmptyObject(nextProps.sCurrMemoProps.sMemoConfig) && commonUtils.isNotEmptyObject(nextProps.sCurrMemoProps.sMemoConfig.sMaxValue) ? nextProps.sCurrMemoProps.sMemoConfig.sMaxValue : this.max); /*   最大值(数据格式:数字)   */
        this.min = commonUtils.convertStrToNumber(commonUtils.isNotEmptyObject(nextProps.sCurrMemoProps.sMemoConfig) && commonUtils.isNotEmptyObject(nextProps.sCurrMemoProps.sMemoConfig.sMinValue) ? nextProps.sCurrMemoProps.sMemoConfig.sMinValue : this.min); /*   最小值(数据格式:数字)   */
      }
    }
  }
  handleOk = () => {
    const { sCurrMemoProps, slaveMemoConfig, masterData } = this.props;
    const sValue = {};
    const name = sCurrMemoProps.name;
    const bVisibleMemo = sCurrMemoProps.bVisibleMemo;
    const sMemoField = sCurrMemoProps.sMemoField;
    const sRecord = sCurrMemoProps.sRecord;
    const btnName = sCurrMemoProps.btnName ? sCurrMemoProps.btnName : '';
    const fillContent = commonFunc.showLocalMessage(this.props, 'fillContent', '请填写内容');
    if (!Array.isArray(slaveMemoConfig) || !slaveMemoConfig.length) {
      if (!sCurrMemoProps?.bNoMemo && sMemoField !== undefined && !btnName.toLowerCase().endsWith('choosedate') && !this.state.textareaValue?.trim()) {
        return message.warning(fillContent);
      }
    }

    let valueKey = '';
    if (commonUtils.isNotEmptyArr(slaveMemoConfig) && commonUtils.isNotEmptyObject(masterData)) {
      const newConfig = {
        gdsconfigformslave :slaveMemoConfig
      }
      if (!commonBusiness.validateTable(newConfig, [masterData], this.props)) {
        return;
      }
      // eslint-disable-next-line array-callback-return
      slaveMemoConfig.map((item) => {
        /**
         * 修改日期：2021-03-24
         * 修改人：吕杰
         * 区域：以下 18 行
         * BUG：
         * 说明：过滤伪字段，为下拉框时替换为id
         * 原代码：
         */
        let realName = item.sName;
        if (item.sRelation && item.sRelation !== 'noQuery') { // 伪字段处理
          if (item.sDropDownType && item.sDropDownType === 'sql') { // 下拉框处理
            /** 此处存在替换隐患，暂无好的解决方案（存在多个Name且需要替换的位置不确定时，无解决方案） */
            realName = realName.replace('Name', 'Id');
          } else { // 过滤
            // eslint-disable-next-line array-callback-return
            return;
          }
        }
        sValue[realName] = masterData[realName];
        if (btnName.toLowerCase().endsWith('choosedate') && realName.length > 0 && realName.substring(0, 1) === 'p') {
          const tStartDate = moment(sValue[realName][0]).format(this.sDateFormat);
          const tEndDate = moment(sValue[realName][1]).add(1, 'days').format(this.sDateFormat);
          sValue[realName][0] = tStartDate;
          sValue[realName][1] = tEndDate;
        }
        valueKey += `${realName},`;
      });
      sValue.valueKey = valueKey;
    }
    sValue.textareaValue = this.state.textareaValue;
    if (btnName.indexOf('BtnRepair') > -1) {
      const btnConfig = this.props.masterConfig.gdsconfigformslave.filter(item => (item.sControlName === btnName))[0];
      if (commonUtils.isNotEmptyObject(btnConfig)) {
        this.props.onBtnEent(btnConfig, btnName, sValue);
      }
      if (btnName.toLowerCase().endsWith('choosedate')) {
        const iIndex = slaveMemoConfig.findIndex(item => item.sName === 'pChooseDate');
        if (iIndex > -1) {
          /* 日期凭证调用存储过程后清除时间区间 */
          masterData.pChooseDate = null;
        }
      }
    } else if (btnName.indexOf('BtnForceComplete') > -1) {
      this.props.onGetMemo(name, sValue, sMemoField, sRecord, bVisibleMemo, btnName);
    } else {
      this.props.onGetMemo(name, this.state.textareaValue, sMemoField, sRecord, bVisibleMemo, btnName);
    }
    this.bInit = true;
  };
  handleSlaveMemoMasterChange = async (name, sFieldName, changeValue, sId, dropDownData, isWait, masterDataNew) => {
    const { masterData: masterDataOld, enabled } = this.props;
    const addState = { enabled };
    const masterData = masterDataNew === undefined ? masterDataOld === undefined ? {} : masterDataOld : masterDataNew;
    const returnData = await this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, true, masterData);
    if (isWait) {
      return { ...returnData, ...addState };
    } else {
      this.props.onSaveState({ ...returnData, ...addState });
      return returnData;
    }
  }

  handleCancel = () => {
    this.bInit = true;
    this.props.onGetMemoCancel();
  };
  /* 设置textareaValue */
  handleTextareaChange(e) {
    this.setState({
      textareaValue: e.target.value,
    });
  }
  handleViewClick = (name, sName, sId) => {
    this.props.onViewClick(name, sName, sId);
  };
  /**   渲染   */
  render() {
    const {
      sCurrMemoProps,
      masterData,
      app,
      sModelsId,
      form,
      slaveMemoConfig,
    } = this.props;
    let bVisibleMemo;
    let sMemoField;
    let btnName = '';
    const title = commonFunc.showLocalMessage(this.props, 'sDetailTitle', '详细');
    let bEnabledTextArea = false; /* 多行文本默认可输入 非编辑状态多行文本禁止输入 */
    let bNoMemo = false;
    if (commonUtils.isNotEmptyObject(sCurrMemoProps)) {
      bNoMemo = sCurrMemoProps.bNoMemo;
      bVisibleMemo = sCurrMemoProps.bVisibleMemo;
      sMemoField = sCurrMemoProps.sMemoField;
      btnName = sCurrMemoProps.btnName ? sCurrMemoProps.btnName : '';
      if (sCurrMemoProps.bOnlyShow !== undefined) { /* 查看状态下备注弹窗只能查看不能修改 */
        bEnabledTextArea = sCurrMemoProps.bOnlyShow;
      }
    }
    let bVisibleTextArea = true;
    if (commonUtils.isNotEmptyArr(slaveMemoConfig)) {
      if (slaveMemoConfig[0].sName === 'sDevelopMemo') {
        bVisibleTextArea = false; /* 开发备注多行文本不显示 */
      }
    }
    // const tStartDate = moment(); /* 开始时间 */
    // 判断是否备注双击弹出的弹窗
    // if (fromToorBar) {
    //   bVisibleMemo = false;
    // }
    const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };
    return (
      <div>
        {
          bVisibleMemo ?
            <AntdDraggableModal
              className="slaveMemo"
              zIndex={1000}
              title={title}
              visible={bVisibleMemo}
              onOk={this.handleOk}
              width={btnName.toLowerCase().endsWith('choosedate') ? 778 : '70%'}
              bodyStyle={{
               height: bNoMemo ? 'auto' : '60vh',
              }}
              onCancel={this.handleCancel}
            >
              <div>
                {
                  btnName.indexOf('BtnRepair') > -1 ?
                    <Form>
                      <FormItem>
                        { commonUtils.isNotEmptyArr(slaveMemoConfig) ?
                          slaveMemoConfig.map((child) => {
                            const sMemo = child.sName.toLowerCase().endsWith('memo');
                            let enabledNew = !child.bReadonly;
                            const iColValue = sMemo ? 21 : child.iColValue * 6;
                            if (child.iTag === 1) {
                              enabledNew = false;
                            } else if (child.iTag === 3) {
                              enabledNew = true;
                            } else if (child.iTag === 5) { // 单据
                              enabledNew = true;
                            }
                            const showTypeProps = {
                              app,
                              iColValue,
                              record: masterData,
                              name: 'master',
                              form,
                              formId: sModelsId,
                              getSqlDropDownData: this.props.getSqlDropDownData,
                              getSqlCondition: this.props.getSqlCondition,
                              handleSqlDropDownNewRecord: this.props.handleSqlDropDownNewRecord,
                              getFloatNum: this.props.getFloatNum,
                              getDateFormat: this.props.getDateFormat,
                              onChange: this.handleSlaveMemoMasterChange,
                              showConfig: child,
                              formItemLayout,
                              textArea: sMemo,
                              enabled: enabledNew,
                              dataValue: masterData ? masterData[child.sName] : undefined,
                              bTable: false,
                              onFilterDropDownData: this.props.onFilterDropDownData,
                              onViewClick: this.handleViewClick,
                              onSaveState: this.props.onSaveState,
                              style: { backgroundColor: '#eaeaea' },
                              bInSlaveMemo: true,
                            };
                            return <ShowType {...showTypeProps} />;
                          }) : ''
                        }
                      </FormItem>
                    </Form>
                    : ''
                }
                {!bNoMemo && sMemoField !== undefined && !btnName.toLowerCase().endsWith('choosedate') ? (
                  <TextArea
                    value={this.state.textareaValue}
                    maxLength={this.max}
                    minLength={this.min}
                    rows={18}
                    style={{ display: bVisibleTextArea ? 'block' : 'none' }}
                    onChange={this.handleTextareaChange}
                    disabled={bEnabledTextArea}
                  />
                ) : null}
              </div>
            </AntdDraggableModal>
            : ''
        }

      </div>
    );
  }
}
