import React, { Fragment, Component, useEffect } from 'react';
import {
  DatePicker,
  Picker,
  TextareaItem,
  InputItem,
  List,
  Switch,
  Modal,
  Button,
  Checkbox,
} from 'antd-mobile';
import moment from 'moment';
import PropTypes from 'prop-types';
import styles from './styles.less';
import TextareaItemMultiRows from '../TextareaItemMultiRows';
import { useState } from 'react';
import DiyUploadOneStopFile from '@/H5Public/baseComponents/FormArray/DiyUploadOneStopFile';

const DiyInput = props => {
  let { config, formValue, changeValue, otherProps } = props;
  if (config.readOnly) {
    config.placeholder = '';
  } else {
    config.placeholder = config.placeholder || '点击输入';
  }
  if(config.readOnly) {
    delete config.otherProps?.placeholder;
  }
  return (
    <InputItem
      key={config.key}
      type={config.dataType}
      editable={!config.readOnly}
      value={formValue[config.key]}
      placeholder={config.readOnly ? '' : config.placeholder}
      onChange={e => {
        changeValue(e, config.key);
      }}
      {...config.otherProps}
    >
      {giveRequiredName(config)}
    </InputItem>
  );
};

const DiyTextarea = props => {
  let { config, formValue, changeValue, noLengthLimit, rows } = props;
  if (config.readOnly) {
    config.placeholder = '';
  } else {
    config.placeholder = config.placeholder || '点击输入';
  }
  if(config.readOnly) {
    delete config.otherProps?.placeholder;
  }
  return (
    <TextareaItem
      key={config.key}
      title={giveRequiredName(config)}
      maxLength={200}
      autoHeight={true}
      placeholder={config.placeholder}
      editable={!config.readOnly}
      value={formValue[config.key]}
      onChange={e => {
        changeValue(e, config.key);
      }}
      {...config.otherProps}
    ></TextareaItem>
  );
};

const DiyPicker = props => {
  let { config, formValue, changeValue } = props;
  if (config.readOnly) {
    config.extra = ' ';
  } else {
    config.extra = config.placeholder || '请选择';
  }
  let opt = config.options.map(x => {
    return {
      label: x.name,
      value: x.key,
    };
  });
  return (
    <Picker
      data={opt}
      cols={1}
      // extra={' '}
      key={config.key}
      value={formValue[config.key] ? [formValue[config.key]] : undefined}
      disabled={config.readOnly}
      onChange={val => {
        changeValue(val[0], config.key);
      }}
      extra={config.extra}
      {...config.otherProps}
    >
      <List.Item arrow={config.readOnly ? '' : 'horizontal'}>{giveRequiredName(config)}</List.Item>
    </Picker>
  );
};

const DiySwitch = props => {
  let { config, formValue, changeValue } = props;
  if (config.readOnly) {
    config.placeholder = ' ';
  } else {
    config.placeholder = config.placeholder || '点击输入';
  }
  return (
    <List.Item
      key={config.key}
      extra={
        <Switch
          checked={formValue[config.key]}
          disabled={config.readOnly}
          onChange={val => {
            changeValue(val, config.key);
          }}
          {...config.otherProps}
        />
      }
    >
      {giveRequiredName(config)}
    </List.Item>
  );
};

const DiyDatePicker = props => {
  let { config, formValue, changeValue } = props;
  let value = formValue[config.key] ? new Date(formValue[config.key].replace(/-/g, '/')) : null;
  const change = date => {
    let v = moment(date.valueOf()).format(config.formatter || 'YYYY-MM-DD');
    changeValue(v, config.key);
  };
  if (config.readOnly) {
    config.placeholder = '';
  } else {
    config.placeholder = config.placeholder || '点击输入';
  }
  return (
    <DatePicker
      value={value}
      extra={config.placeholder}
      mode={config.mode || 'date'}
      key={config.key}
      disabled={config.readOnly}
      onChange={date => change(date)}
      locale={{
        okText: '确定',
        dismissText: '取消',
        dateFormat: 'YYYY-MM-DD',
      }}
      {...config.otherProps}

    >
      <List.Item arrow="horizontal">{giveRequiredName(config)}</List.Item>
    </DatePicker>
  );
};

const DiyCheckBox = ({ config, formValue, changeValue }) => {
  const [modalVisible, toggleModal] = useState(false);
  const [selectedKeys, setSelectedKeys] = useState([]);
  useEffect(() => {
    setSelectedKeys(formValue[config.key] || []);
  }, [formValue, config.key]);

  function onChange(item) {
    if (selectedKeys.includes(item.key)) {
      setSelectedKeys(selectedKeys.filter(i => i !== item.key));
    } else {
      setSelectedKeys([...selectedKeys, item.key]);
    }
  }
  function submit() {
    toggleModal(false);
    changeValue(selectedKeys, config.key);
  }
  return (
    <>
      <List.Item
        arrow="horizontal"
        onClick={() => !config.readOnly && toggleModal(true)}
        extra={config.options
          .filter(i => formValue[config.key] && formValue[config.key].includes(i.key))
          .map(i => i.name)
          .join('，')}
      >
        {giveRequiredName(config)}
      </List.Item>
      <Modal
        popup
        visible={modalVisible}
        onClose={() => toggleModal(false)}
        animationType="slide-up"
      >
        <List renderHeader={() => <div>{config.name}</div>}>
          <div style={{ maxHeight: '50vh', overflow: 'scroll' }}>
            {config.options.map(i => (
              <Checkbox.CheckboxItem
                checked={selectedKeys.includes(i.key)}
                key={i.key}
                onChange={() => onChange(i)}
              >
                {i.name}
              </Checkbox.CheckboxItem>
            ))}
          </div>
          <List.Item>
            <Button type="primary" onClick={submit}>
              确定
            </Button>
          </List.Item>
        </List>
      </Modal>
    </>
  );
};

const giveRequiredName = config => {
  if (config.required) {
    return (
      <Fragment>
        <i style={{ color: 'red' }}>*&nbsp;</i>
        {config.name}
      </Fragment>
    );
  } else {
    return (
      <Fragment>
        <i style={{ color: 'red' }}>&nbsp;&nbsp;</i>
        {config.name}
      </Fragment>
    );
  }
};

class FormArray extends Component {
  changeValue = (value, key) => {
    this.props.changeValue(value, key);
  };

  detailDom = () => {
    const { config, formValues, readOnly } = this.props;
    return (
      config &&
      config.length &&
      config.map(x => {
        x.readOnly = readOnly || x.readOnly;
        switch (x.type) {
          case 'InputItem':
            return (
              <DiyInput
                key={x.key}
                config={x}
                formValue={formValues}
                changeValue={this.changeValue}
              />
            );
          case 'TextareaItem':
            return (
              <DiyTextarea
                key={x.key}
                config={x}
                formValue={formValues}
                changeValue={this.changeValue}
              />
            );
          case 'TextareaItemMultiRows':
            return (
              <TextareaItemMultiRows
                key={x.key}
                config={x}
                value={formValues[x.key]}
                onChange={val => this.changeValue(val, x.key)}
              />
            );
          case 'Picker':
            return (
              <DiyPicker
                config={x}
                key={x.key}
                formValue={formValues}
                changeValue={this.changeValue}
              />
            );
          case 'DatePicker':
            return (
              <DiyDatePicker
                key={x.key}
                config={x}
                formValue={formValues}
                changeValue={this.changeValue}
              />
            );
          case 'Switch':
            return (
              <DiySwitch
                key={x.key}
                config={x}
                formValue={formValues}
                changeValue={this.changeValue}
              />
            );
          case 'CheckBox':
            return (
              <DiyCheckBox
                key={x.key}
                config={x}
                formValue={formValues}
                changeValue={this.changeValue}
              />
            );
          case 'UploadOneStopFile':
            return (
              <DiyUploadOneStopFile
                key={x.key}
                config={x}
                formValue={formValues}
                changeValue={this.changeValue}
                giveRequiredName={giveRequiredName}
                extInfo={x.extInfo}
              />
            )
          case 'Components':
            return x.render(formValues[x.key], this.changeValue, x.key);
          default:
            return null;
        }
      })
    );
  };

  render() {
    return <List className={styles.formArray}>{this.detailDom()}</List>;
  }
}

FormArray.propTypes = {
  formValues: PropTypes.object.isRequired, //数据
  config: PropTypes.array.isRequired, // 配置项
  changeValue: PropTypes.func.isRequired, // 改值的方法
  readOnly: PropTypes.bool, // 是否 只读
};
FormArray.defaultProps = {
  formValues: {},
  config: [
    {
      type: 'input',
    },
  ],
  changeValue: (value, key) => {
    console.log(value, key);
  },
  readOnly: false,
};
export  { giveRequiredName }
export default FormArray;
