import React, { useCallback } from 'react'
import classNames from 'classnames'
import dayjs from 'dayjs'
import { useInfo } from '../InfoContext'
import { Cascader, DatePicker, Input } from 'antd'
import TextArea from 'antd/es/input/TextArea'

type Props = {
  item: any
  isLook: boolean
}

function EditInput({ item, isLook }: Props) {
  const { info, setInfoFu } = useInfo()

  // 数据改变
  const dataChangeFu = useCallback(
    (val: any, item: any) => {
      const type = item.type
      const key = item.key

      if (type === 'DatePicker') {
        setInfoFu({ ...info, [key]: dayjs(val).format('YYYY-MM-DD') })
      } else if (['TextArea', 'Input'].includes(type)) {
        const varRes = item.noNull ? val.replace(/\s+/g, '') : val
        setInfoFu({
          ...info,
          [key]: varRes
        })
      } else if (type === 'Cascader') {
        setInfoFu({ ...info, dictIdApply: val ? val.join(',') : '' })
      }
    },
    [info, setInfoFu]
  )

  return (
    <div className={classNames('Edtop1row', item.full ? 'Edtop1rowFull' : '')}>
      <div className='Edtop1ll'>
        {item.must ? <span>* </span> : null}
        {item.name}：
      </div>

      <div className='Edtop1rr'>
        {item.type === 'txt' ? (
          <>
            {dayjs(info.createTime).format('YYYY年MM月DD日')}-{info.deptName}-{info.creatorName}
          </>
        ) : item.type === 'DatePicker' ? (
          <DatePicker
            disabled={isLook}
            allowClear={!item.must}
            value={dayjs(info[item.key as 'date'])}
            onChange={e => dataChangeFu(e, item)}
            disabledDate={current => current && current > dayjs().endOf('day')}
          />
        ) : item.type === 'Input' ? (
          <Input
            readOnly={isLook}
            placeholder={isLook ? '（空）' : '请输入'}
            value={info[item.key as 'date']}
            onChange={e => dataChangeFu(e.target.value, item)}
            maxLength={item.maxLength || 30}
            showCount
          />
        ) : item.type === 'Cascader' ? (
          <Cascader
            disabled={isLook}
            changeOnSelect
            options={item.options}
            placeholder={isLook ? '（空）' : '请选择'}
            fieldNames={{ label: 'name', value: 'id', children: 'children' }}
            allowClear={!item.must}
            value={info[item.key as 'date'] ? (info[item.key as 'date'] as string).split(',') : []}
            onChange={e => dataChangeFu(e, item)}
          />
        ) : item.type === 'TextArea' ? (
          <TextArea
            readOnly={isLook}
            placeholder={isLook ? '（空）' : '请输入'}
            value={info[item.key as 'date']}
            onChange={e => dataChangeFu(e.target.value, item)}
            maxLength={item.maxLength || 500}
            showCount
          />
        ) : null}
      </div>
    </div>
  )
}

const MemoEditInput = React.memo(EditInput)

export default MemoEditInput
