import consts from '@/basic/consts'
import { apiUpdateContract } from '@/services/contact'
import { Input, Row, Col, Select } from 'antd'
import React, { useState, useEffect, useRef } from 'react'
import './index.less'

const EditableFormItem = ({ label, dataIndex, record, dataId, span, editCellType }) => {

  const [editing, setEditing] = useState(false)
  const inputRef = useRef(null)
  const [val, setVal] = useState('')
  useEffect(() => {
    setVal('')
  }, [])
  useEffect(() => {
    // 处于编辑状态自动聚焦
    if (editing) {
      inputRef.current.focus()
    }
    // 当val为空时，需要设置默认值
    if (!val) {
      setVal(record)
    }
  }, [record, editing])

  // 单独设置一个依赖，防止dataId变化
  useEffect(() => {
    setVal(record)
  }, [dataId])


  const toggleEdit = () => {
    setEditing(!editing)
  }

  const handleConfirm = async value => {
    const { code = -1 } = await apiUpdateContract({ [dataIndex]: value, id: dataId })
    if (code === consts.RET_CODE.SUCCESS) {
      toggleEdit()
    }
  }
  const save = async e => {
    const { value = '' } = e.currentTarget
    if (value === record || !value) {
      return
    }
    setVal(value)
    await handleConfirm(value)
    toggleEdit()
  }

  // const handleOnChange = e => {
  //   setVal(value)
  //   const { value = '' } = e.currentTarget
  // }

  let cell = null

  if (editing) {
    switch (editCellType) {
      case 'cascader':
        // cell = ()
        break
      case 'select':
        cell = (
          <Select
            defaultValue="男"
          >
            <option vlaue="男">男</option>
            <option vlaue="女">女</option>
          </Select>
        )
        break
      default:
        cell = (
          <Input
            ref={inputRef}
            onPressEnter={save}
            onBlur={save}
            defaultValue={val}
          // onChange={handleOnChange}
          />
        )
        break
    }
  } else {
    cell = (
      <div className="editable-cell-value-wrap" onClick={toggleEdit}>
        {val}
      </div>
    )
  }

  return (
    <Col span={span}>
      <Row wrap={false}>
        <Col flex="100px" className="zh-text-right zh-mg-bottom-8">
          <span className="zh-lh-32 zh-mg-right-10">{label}:</span>
        </Col>
        <Col flex="auto">{cell}</Col>
      </Row>
    </Col>
  )
}

export default EditableFormItem
