import React, { useState } from 'react'
import { Form, Radio, DatePicker, Switch, Modal } from 'antd'
import { dayjsFormat } from '@/utils/utils'
import dayjs from 'dayjs'
import { ProFormTextArea } from '@ant-design/pro-form'

const AddRecord = props => {
  const [formRef] = Form.useForm()
  const { onConfirm, ...resetModalProps } = props
  const [state, setState] = useState({
    showExtraItem: false,
    loading: false
  })

  const onChange = value => {
    setState({ ...state, showExtraItem: value })
  }

  const disabledDate = current => {
    return current && current < dayjs().endOf('day')
  }

  return (
    <Modal
      {...resetModalProps}
      title="添加服务记录"
      getContainer={() => document.getElementById('root')}
      onOk={() => {
        setState({ ...state, loading: true })
        formRef
          ?.validateFields()
          .then(async values => {
            const newVal = { ...values }
            formRef.current?.resetFields()
            if (values.date) {
              newVal.date = dayjsFormat(values.date, 'YYYY-MM-DD')
            }
            if (values.remindTime) {
              newVal.remindTime = dayjsFormat(values.remindTime, 'YYYY-MM-DD')
            }
            const isSuccess = await onConfirm(newVal)
            isSuccess && resetModalProps.onCancel()
            setState({ ...state, loading: false })
          })
          .catch(() => {
            setState({ ...state, loading: false })
          })
      }}
      confirmLoading={state.loading}
    >
      <Form layout="vertical" form={formRef}>
        <Form.Item name="status" label="服务类型" rules={[{ required: true, message: '请选择类型' }]}>
          <Radio.Group>
            <Radio value={1}>上门服务</Radio>
            <Radio value={2}>电话拜访</Radio>
            <Radio value={3}>其他事项</Radio>
            <Radio value={4}>在线服务</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          name="date"
          label="服务日期"
          initialValue={dayjs(new Date())}
          rules={[{ required: true, message: '请选择服务日期' }]}
        >
          <DatePicker style={{ width: '100%' }} />
        </Form.Item>
        <ProFormTextArea name="mark" label="内容" rules={[{ required: true, message: '请输入服务内容' }]} />

        <div className="pb-5">
          <Switch onChange={onChange} checked={state.showExtraItem} />
          <span className="ml-2">添加备忘录</span>
        </div>
        {state.showExtraItem ? (
          <>
            <Form.Item
              name="remindTime"
              label="备忘日期"
              rules={[{ required: true, message: '请选择备忘日期' }]}
            >
              <DatePicker style={{ width: '100%' }} disabledDate={disabledDate} />
            </Form.Item>
            <ProFormTextArea name="remarks" label="备忘内容" />
          </>
        ) : null}
      </Form>
    </Modal>
  )
}

export default AddRecord
