import React from 'react';
import { Button, Row, Col, message } from 'antd';
import ZdyTable from '../Table';
import { getOrderUid } from './splitChildForm';
import { Card } from 'antd-mobile';


const sortKeys = (a = '', b = '') => {
  if (a && b && typeof a === 'string' && typeof b === 'string' && a.length > 13 && b.length > 13) {
    return Number(a.slice(0, 13)) - Number(b.slice(0, 13));
  } else {
    return 0;
  }
};

export default class ChildForm extends React.Component {
  constructor(props) {
    super(props);
    const value = props.value || {};

    this.state = value;
  }

  triggerChange = (changedValue) => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(changedValue);
      // if (changedValue && typeof changedValue === 'object' && !Object.keys(changedValue).length) {
      //   onChange(changedValue);
      //   // onChange(null);
      // } else {
      //   onChange(changedValue);
      // }
    }
  };

  componentWillReceiveProps(nextProps) {
    if ('value' in nextProps) {
      const value = nextProps.value;
      this.state = value;
    }
  }

  componentDidMount = () => {
    if (Object.keys(this.state).length == 0 && this.props.isEdit) {
      if (this.props.num != null && this.props.num > 0) {
        const objs = this.state;
        if (this.props.min != null && this.props.min > this.props.num) {
          for (var i = 0; i < this.props.min; i++) {
            objs[getOrderUid()] = {};
          }
        } else {
          for (var i = 0; i < this.props.num; i++) {
            objs[getOrderUid()] = {};
          }
        }

        if (!('value' in this.props)) {
          this.setState(objs);
        }
        this.triggerChange(objs);
      }
    }
  };
  delete = (uuid) => {
    const objs = this.state;
    const {
      json: { numCode },
      form,
      base52,
    } = this.props;
    if (this.props.min != null && Object.keys(objs).length - 1 < this.props.min) {
      message.error('不能小于最小限制');

      return;
    }
    const x = form.getFieldsValue()[base52];
    delete x[uuid];
    delete x[''];

    if (!('value' in this.props)) {
      this.state = x;
    }
    this.triggerChange(x);

    if (numCode != null) {
      this.props.form.setFieldsValue({ [numCode]: Object.keys(objs).length });
    }
  };
  add = () => {
    const objs = this.state;
    const {
      json: { numCode },
      form,
      base52,
    } = this.props;
    if (this.props.max != null && Object.keys(objs).length + 1 > this.props.max) {
      message.error('不能大于最大限制');

      return;
    }
    objs[getOrderUid()] = {};

    if (!('value' in this.props)) {
      this.setState(objs);
    }
    this.triggerChange(objs);
    if (numCode != null) {
      this.props.form.setFieldsValue({ [numCode]: Object.keys(objs).length });
    }
  };

  render() {
    const objs = this.state;
    // console.log(objs);
    const {
      form,
      mapData,
      sqlData,
      defaultValues,
      datas,
      base52,
      isEdit: isEditProps,
      addName,
      deleteName,
      obj,
      isMobile,
      json,
      modalInit,
      isPreview,
      hfInstance,
      getCurrentFormTitle,
      getCellValue,
      taskId,
      datasAll,
    } = this.props;

    const span = json.span || 24;
    const gutter = json.gutter != null ? json.gutter : 0;
    const rights = this.props.rights;
    const { disabled } = json;
    const isEdit = !disabled && isEditProps; // 29128 北电]资助-新生入学资助管理-批次设置，2张图2问题不要详情改编辑只能修改是否启用
    if (datas == null) {
      return <div>还没有配置子表单key</div>;
    }

    if (!objs) {
      return null;
    }

    if (isMobile) {
      return (
        // 2022年11月24日 姚新国说的 把干掉两翼留白 解决北电科工作情况考核 移动端样式的问题
        <div>
          {Object.keys(objs).length >= 1 || rights.includes('add') ? (
            <Card>
              <Card.Body style={{ minHeight: 10 }}>
                {Object.keys(objs)
                  .sort((a, b) => {
                    return sortKeys(a,b);
                  })
                  .map((r) => {
                    if (r == '') {
                      return '';
                    }
                    return (
                      <Row key={r} gutter={gutter}>
                        <Col
                          style={{
                            zIndex: 55,
                          }}
                          span={isEdit ? 24 : span}>
                          <ZdyTable
                            changedValues={this.props.changedValues}
                            setRealTimeValues={this.props.setRealTimeValues}
                            trees={this.props.trees}
                            key={r}
                            taskId={taskId}
                            modalInit={modalInit}
                            hfInstance={hfInstance}
                            currentFormTitle={
                              getCurrentFormTitle ? getCurrentFormTitle(json.childFormKey) : null
                            }
                            getCellValue={getCellValue}
                            formCode={this.props.formCode}
                            formId={this.props.formId}
                            isPreview={isPreview}
                            currentFormKey={json.childFormKey}
                            formConfig={datas}
                            get="mobile"
                            fatherCode={base52}
                            isEdit={isEdit}
                            index={r}
                            obj={objs[r]}
                            fatherObj={this.props.fatherObj}
                            init={objs}
                            isChild={true}
                            form={form}
                            mapData={mapData}
                            sqlData={sqlData}
                            datas={datasAll}
                            {...datas}
                            defaultValues={defaultValues}
                          />
                        </Col>
                        {rights.includes('delete') && isEdit ? (
                          <Col style={{ textAlign: 'right' }}>
                            <Button type="danger" size="small" onClick={this.delete.bind(this, r)}>
                              {deleteName || '删除'}{' '}
                            </Button>{' '}
                          </Col>
                        ) : (
                          ''
                        )}
                      </Row>
                    );
                  })}

                {rights.includes('add') && isEdit ? (
                  <Row>
                    <Col style={{ textAlign: 'center' }}>
                      <Button
                        type="primary"
                        size="small"
                        style={{ margin: 'auto' }}
                        onClick={this.add}>
                        {addName || '新增'}
                      </Button>{' '}
                    </Col>
                  </Row>
                ) : (
                  ''
                )}
              </Card.Body>
            </Card>
          ) : (
            ''
          )}
        </div>
      );
    }

    /***
     * 子表单
     * */
    return (
      <div style={{ width: '100%' }}>
        <Row gutter={gutter}>
          {Object.keys(objs)
            .sort((a, b) => {
              return sortKeys(a,b);
            })
            .map((r) => {
              if (r == '') {
                return '';
              }
              return (
                <Col span={span} key={r}>
                  <ZdyTable
                    changedValues={this.props.changedValues}
                    taskId={taskId}
                    setRealTimeValues={this.props.setRealTimeValues}
                    modalInit={modalInit}
                    hfInstance={hfInstance}
                    currentFormTitle={
                      getCurrentFormTitle ? getCurrentFormTitle(json.childFormKey) : null
                    }
                    getCellValue={getCellValue}
                    formConfig={datas}
                    key={r}
                    fatherCode={base52}
                    isEdit={isEdit}
                    index={r}
                    isPreview={isPreview}
                    obj={objs[r]}
                    currentFormKey={json.childFormKey}
                    formCode={this.props.formCode}
                    formId={this.props.formId}
                    fatherObj={this.props.fatherObj}
                    init={objs}
                    isChild={true}
                    get="web"
                    form={form}
                    mapData={mapData}
                    sqlData={sqlData}
                    datas={datasAll}
                    {...datas}
                    defaultValues={defaultValues}
                  />

                  {rights.includes('delete') && isEdit ? (
                    <Button
                      size="small"
                      style={{
                        position: 'absolute',
                        left: ' 95%',
                        top: '10px',
                        transform: 'translateY(-50%)',
                        borderRadius: '50%',
                        height: '13px',
                        width: '13px',
                        padding: 0,
                        lineHeight: '10px',
                      }}
                      type="danger"
                      onClick={this.delete.bind(this, r)}>
                      {deleteName || '-'}
                    </Button>
                  ) : (
                    ''
                  )}
                </Col>
              );
            })}
        </Row>
        {rights.includes('add') && isEdit ? (
          <Row>
            <Col span={24} style={{ textAlign: 'center' }}>
              <Button style={{ margin: 'auto' }} type="primary" onClick={this.add} size="small">
                {addName || '新增'}
              </Button>
            </Col>{' '}
          </Row>
        ) : (
          ''
        )}
      </div>
    );
  }
}
