import React from 'react'
import {
  Modal,
  Form,
  Button,
  Input,
  Switch,
  Radio,
  InputNumber,
  Select
} from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import { IDataRule, IDataSubject } from '../types'

const FormItem = Form.Item

interface IRuleFormModalProps extends FormComponentProps<IDataRule> {
  visible: boolean
  loading: boolean
  fromView: IDataRule
  onSave: (view: IDataRule) => void
  onCancel: () => void
  inspectionType: IDataRule['inspectionType']
}

class NumberRange extends React.Component<{
  value?: { from?: number; to?: number }
  onChange?: (value: { from?: number; to?: number }) => void
}> {
  public handleNumberChange = (num, type: 'from' | 'to') => {
    this.triggerChange({ [type]: num })
  }

  public triggerChange = (changedValue: { from?: number; to?: number }) => {
    const { onChange, value } = this.props
    if (onChange) {
      onChange({
        ...value,
        ...changedValue
      })
    }
  }

  public render() {
    const { value } = this.props
    return (
      <span>
        <InputNumber
          value={value?.from}
          onChange={(val) => this.handleNumberChange(val, 'from')}
        />
        &nbsp;&nbsp;~&nbsp;&nbsp;
        <InputNumber
          value={value?.to}
          onChange={(val) => this.handleNumberChange(val, 'to')}
        />
      </span>
    )
  }
}

class RuleFormModal extends React.PureComponent<IRuleFormModalProps> {
  private formItemStyle = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 }
  }

  private save = () => {
    const { form, fromView, onSave } = this.props
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (err) {
        return
      }
      const data: IDataRule = { ...fieldsValue }

      // @ts-ignore
      onSave({
        ...data,
        ruleConfig: {
          [data.ruleType]:
            data.ruleType === 'range'
              ? {
                  // @ts-ignore
                  from: data.ruleConfig.from,
                  // @ts-ignore
                  to: data.ruleConfig.to
                }
              : data.ruleConfig
        }
      })
    })
  }

  private clearFieldsValue = () => {
    this.props.form.resetFields()
  }

  private checkRange = (rule, value, callback) => {
    if (value?.from < value?.to) {
      return callback()
    }
    callback('to must greater than from!')
  }
  private handleSetUUID = () =>
    this.props.form.setFieldsValue({
      ruleCode: Date.now() + ''
    })

  public render() {
    const { form, visible, loading, fromView, onCancel, inspectionType } =
      this.props
    const { getFieldDecorator } = form

    const modalButtons = [
      <Button key="back" size="large" onClick={onCancel}>
        取 消
      </Button>,
      <Button
        disabled={loading}
        key="submit"
        size="large"
        type="primary"
        onClick={this.save}
      >
        保 存
      </Button>
    ]

    console.log(fromView, '+++')

    return (
      <Modal
        title={fromView ? '编辑' : '新增'}
        visible={visible}
        footer={modalButtons}
        onCancel={onCancel}
        afterClose={this.clearFieldsValue}
        destroyOnClose
      >
        <Form>
          <FormItem label="规则编号" {...this.formItemStyle} required>
            {getFieldDecorator<IDataRule>('ruleCode', {
              initialValue: fromView?.ruleCode
            })(<Input />)}
            {!fromView?.id && (
              <Button onClick={this.handleSetUUID}>自动生成编号</Button>
            )}
          </FormItem>
          <FormItem label="规则名称" {...this.formItemStyle} required>
            {getFieldDecorator<IDataRule>('ruleName', {
              initialValue: fromView?.ruleName
            })(<Input />)}
          </FormItem>
          <FormItem label="规则描述" {...this.formItemStyle}>
            {getFieldDecorator<IDataRule>('ruleDesc', {
              initialValue: fromView?.ruleDesc
            })(<Input />)}
          </FormItem>
          <FormItem label="规则类型" {...this.formItemStyle}>
            {getFieldDecorator<IDataRule>('ruleType', {
              initialValue: fromView?.ruleType
            })(
              <Radio.Group>
                {inspectionType === 'integrity' && (
                  <Radio value="not_null">非空</Radio>
                )}
                {inspectionType === 'uniformity' && (
                  <Radio value="range">值域</Radio>
                )}
                {inspectionType === 'uniformity' && (
                  <Radio value="length">长度</Radio>
                )}
                {inspectionType === 'uniformity' && (
                  <Radio value="date_format">日期格式</Radio>
                )}
                {inspectionType === 'uniformity' && (
                  <Radio value="">自定义</Radio>
                )}
              </Radio.Group>
            )}
          </FormItem>
          {this.props.form.getFieldValue('ruleType') === 'range' && (
            <FormItem label="值域" {...this.formItemStyle}>
              {getFieldDecorator<IDataRule>('ruleConfig', {
                initialValue: fromView?.ruleConfig?.range,
                rules: [{ validator: this.checkRange }]
              })(<NumberRange />)}
            </FormItem>
          )}
          {this.props.form.getFieldValue('ruleType') === 'length' && (
            <FormItem label="长度" {...this.formItemStyle}>
              {getFieldDecorator<IDataRule>('ruleConfig', {
                initialValue: fromView?.ruleConfig?.length
              })(<InputNumber />)}
            </FormItem>
          )}
          {this.props.form.getFieldValue('ruleType') === 'date_format' && (
            <FormItem label="日期格式" {...this.formItemStyle}>
              {getFieldDecorator<IDataRule>('ruleConfig', {
                initialValue: fromView?.ruleConfig?.date_format
              })(
                <Select>
                  <Select.Option value="YYYY-MM-DD">YYYY-MM-DD</Select.Option>
                  <Select.Option value="YYYY-MM-DD HH:mm">
                    YYYY-MM-DD HH:mm
                  </Select.Option>
                  <Select.Option value="YYYY-MM-DD HH:mm:ss">
                    YYYY-MM-DD HH:mm:ss
                  </Select.Option>
                </Select>
              )}
            </FormItem>
          )}
        </Form>
      </Modal>
    )
  }
}

export default Form.create<IRuleFormModalProps>()(RuleFormModal)
