import React, { useRef, useState, useEffect } from 'react'
import { Form, Input, Select, Button, Radio, Modal, Descriptions } from 'antd'
import router from 'umi/router'
import { fetch, apis } from '@/utils/request'
import useRoomSelect from '../utils/hooks/useRoomSelect'

const addPerson = fetch(apis.buildingOwnerInfo.addBuilding)
const taUserHasOwner = fetch(apis.propUser.taUserHasOwner)
const taUserHas = fetch(apis.propUser.taUserHas)

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
  },
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 6,
    },
  },
}

const isEmpty = o => !o || (Array.isArray(o) && !o.length) || (typeof o === 'object' && !Object.keys(o).length)

export default Form.create()(props => {
  const {
    phaseId,
    setPhaseId,
    buildingId,
    setBuildingId,
    unitId,
    setUnitId,
    levelId,
    setLevelId,
    roomNoId,
    setRoomNoId,
    phaseList,
    buildingList,
    unitList,
    levelList,
    roomNoList
  } = useRoomSelect()

  const [owerExist, setOwnerExist] = useState(false)
  const [telAccUser, setTelAccUser] = useState()
  
  const handlePhaseChange = e => setPhaseId(e)
  const handleBuildingChange = e => setBuildingId(e)
  const handleUnitChange = e => setUnitId(e)
  const handleLevelChange = e => setLevelId(e)
  const handleRoomChange = e => setRoomNoId(e)
  const handlePhoneBlur = e => {
    const ownerTel = props.form.getFieldValue('ownerTel')
    if (ownerTel) {
      taUserHas({params: {ownerTel}}).then(res => {
        if (!isEmpty(res)) {
          setTelAccUser(res)
        }
      })
    }
  }

  useEffect(() => {
    if (roomNoId) {
      taUserHasOwner({ params: {phaseId, buildingId, unitId, levelId, roomNoId} }).then(res => {
        setOwnerExist(res.boolRole)
      })
    }
  }, [roomNoId])
  
  useEffect(() => {
    if (roomNoId) {
      taUserHasOwner({ params: {phaseId, buildingId, unitId, levelId, roomNoId} }).then(res => {
        setOwnerExist(res.boolRole)
      })
    }
  }, [roomNoId])


  const handleSubmit = e => {
    e.preventDefault();
    if (!isEmpty(telAccUser)) {
      return
    }

    props.form.validateFields((err, values) => {
      if (!err) {
        const data = {
          ...values,
          phaseId,
          buildingId,
          unitId,
          levelId,
          roomNoId
        }

        addPerson({ data }).then(res => {
          Modal.success({
            content: '添加成功',
            onOk: () => {
              router.go(-1)
            }
          })
        })
      }
    });
  }

  return (
    <div>
      <Form {...formItemLayout} onSubmit={handleSubmit}>
        <Form.Item label="期/区" required>
          <Select value={phaseId} onChange={handlePhaseChange} style={{ minWidth: '120px' }} placeholder="期/区">
            {
              phaseList.map(x => (<Select.Option key={x.id} value={x.id}>{x.name}</Select.Option>))
            }
          </Select>
        </Form.Item>
        <Form.Item label="栋/幢" required>
          <Select value={buildingId} onChange={handleBuildingChange} style={{ minWidth: '120px' }} placeholder="栋/幢">
            {
              buildingList.map(x => (<Select.Option key={x.id} value={x.id}>{x.name}</Select.Option>))
            }
          </Select>
        </Form.Item>
        <Form.Item label="单元" required>
          <Select value={unitId} onChange={handleUnitChange} style={{ minWidth: '120px' }} placeholder="单元">
            {
              unitList.map(x => (<Select.Option key={x.id} value={x.id}>{x.name}</Select.Option>))
            }
          </Select>
        </Form.Item>
        <Form.Item label="楼层" required>
          <Select value={levelId} onChange={handleLevelChange} style={{ minWidth: '120px' }} placeholder="楼层">
            {
              levelList.map(x => (<Select.Option key={x.id} value={x.id}>{x.name}</Select.Option>))
            }
          </Select>
        </Form.Item>
        <Form.Item label="户号" required>
          <Select value={roomNoId} onChange={handleRoomChange} style={{ minWidth: '120px' }} placeholder="户号">
            {
              roomNoList.map(x => (<Select.Option key={x.id} value={x.id}>{x.name}</Select.Option>))
            }
          </Select>
        </Form.Item>
        <Form.Item label="手机号">
          {
            props.form.getFieldDecorator('ownerTel', {
              rules: [
                { required: true, message: '请填写手机号' }
              ]
            })(<Input onBlur={handlePhoneBlur} />)
          }
        </Form.Item>
        <Form.Item label="身份">
          {
            props.form.getFieldDecorator('roleId')(
              <Select style={{ minWidth: '120px' }} placeholder="请选择身份">
                <Select.Option value="1" disabled={owerExist}>户主</Select.Option>
                <Select.Option value="2">租客</Select.Option>
                <Select.Option value="3">家属</Select.Option>
              </Select>
            )
          }
        </Form.Item>
        <Form.Item label="姓名">
          {
            props.form.getFieldDecorator('ownerName')(<Input />)
          }
        </Form.Item>
        <Form.Item label="性别">
          {
            props.form.getFieldDecorator('gender')(
              <Radio.Group>
                <Radio value="1">男</Radio>
                <Radio value="2">女</Radio>
              </Radio.Group>
            )
          }
        </Form.Item>
        {
          telAccUser && (
            <Form.Item label=" " colon={false}>
              <Descriptions column={3}>
                <Descriptions.Item label="姓名">{telAccUser.userName}</Descriptions.Item>
                <Descriptions.Item label="性别">{telAccUser.gender === '2' ? '女' : '男'}</Descriptions.Item>
                <Descriptions.Item label="身份证号">{(telAccUser.idCard || '').replace(/^(.{4})(?:\w+)(.{4})$/, "$1****$2")}</Descriptions.Item>
              </Descriptions>
            </Form.Item>
          )
        }
        <Form.Item {...tailFormItemLayout}>
          <Button type="primary" htmlType="submit">提交</Button>
          <Button style={{ marginLeft: '48px' }} onClick={() => router.go(-1)}>取消</Button>
        </Form.Item>
      </Form>
    </div>
  )
})
