import React from "react"
import { Button, Spin, Modal, Form, Input, Select } from "antd"

import { dispatch } from '../../../../model'

const FC = (props) => {
  const { visible, type, item, onCancel } = props
  const [waiting, setWaiting] = React.useState(false)
  const basicRef = React.useRef()

  const title = React.useMemo(() => {
    if (type === 'add') return '新增规范'
    if (type === 'edit') return '修改规范'
    if (type === 'detail') return '规范详情'

    return ''
  }, [type])

  const close = (refresh = false) => {
    setWaiting(false)
    onCancel?.(refresh)
  }

  const save = async() => {
    try {
      const rows = await basicRef.current?.validate()
      setWaiting(true)
      if (type === 'add') {
        dispatch({
          type: 'datamodel.addRuleCatalog',
          payload: {
            data: rows
          },
          callback: data => {
            close(true)
          },
          error: () => {
            setWaiting(false)
          }
        })
      } else {
        dispatch({
          type: 'datamodel.updateRuleCatalog',
          payload: {
            data: {...item, ...rows}
          },
          callback: data => {
            close(true)
          },
          error: () => {
            setWaiting(false)
          }
        })
      }
       
    } catch (e) {
      
    }
  }

  const footer = React.useMemo(() => {
    return [
      <Button key='cancel'
        onClick={() => close()}
      >取消</Button>,
      <Button key='save' type='primary'
        onClick={() => save()}
      >确定</Button>
    ]
  }, [close, save])

  return (
    <Modal
      visible={visible}
      footer={type!=='detail'?footer:null}
      width='80%'
      bodyStyle={{ padding: '15px', overflowX: 'auto', maxHeight: '80vh' }}
      title={title}
      centered destroyOnClose
      onCancel={() => { close() }}
    >
      <Spin spinning={waiting}>
        <Basic ref={basicRef} type={type} item={item} />
      </Spin>
    </Modal>
  )
}

export default FC

export const Basic = React.forwardRef(function ({ type, item }, ref) {
  const [loadingStatus, setLoadingStatus] = React.useState(false)
  const [status, setStatus] = React.useState()
  const [form] = Form.useForm()

  React.useImperativeHandle(ref, () => ({
    validate: async () => {
      return await form?.validateFields()
    },
  }), [form])

  React.useEffect(() => {
    getStatus()
  }, [])

  React.useEffect(() => {
    if (item) {
      form?.setFieldsValue(item)
    }
  }, [item])

  const marginBottom = React.useMemo(() => {
    return type === 'detail' ? 5 : 15
  }, [type])

  const getStatus = () => {
    setLoadingStatus(true)
    dispatch({
      type: 'datamodel.getRuleCatalogStatus',
      callback: (data) => {
        setLoadingStatus(false)
        setStatus(data)        
      },
      error: () => {
        setLoadingStatus(false)
      }
    })
  } 

  const onValuesChange = (changedValues, allValues) => {

  }

  return (
    <Form
      form={form}
      labelCol={{ span: 3 }}
      wrapperCol={{ span: 21 }}
      autoComplete="off"
      onValuesChange={onValuesChange}
    >
      <Form.Item name='name' label='规范名称'
        style={{ marginBottom }}
        rules={[{ required: true, message: '请输入规范名称!' }]}
      >
        {
          type === 'detail' ? <span>{item?.name}</span> : <Input placeholder='请输入规范名称' allowClear />
        }
      </Form.Item>
      <Form.Item name='remark' label='描述'
        style={{ marginBottom }}
      >
        {
          type === 'detail' ? <span>{item?.name}</span> : <Input placeholder='请输入描述' allowClear />
        }
      </Form.Item>
      <Form.Item name='statusId' label='状态'
        style={{ marginBottom }}
      >
        {
          type === 'detail' ? <span>{item?.statusName}</span> : <Select loading={loadingStatus} allowClear placeholder='请选择状态'>
            { (status??[]).map(item => ( <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option> )) }
          </Select>
        }
      </Form.Item>
      <Form.Item name='maintenanceContent' label='维护说明'
        style={{ marginBottom }}
      >
        {
          type === 'detail' ? <span>{item?.name}</span> : <Input placeholder='请输入维护说明' allowClear />
        }
      </Form.Item>
    </Form>
  )
})