import React, { useState, useEffect } from 'react'
import { Form, Row, Col, Button, Modal } from 'antd'
import LazyCascader from '@/components/LazyCascader'
import { ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form'
import { useDispatch, connect } from 'umi'
import { ChangeCompMap } from '@/pages/Customer/Company/components/ChangeCompany'
import { isNullOrUnDef } from '@/utils/is'
import TelephoneFormItem from './TelephoneFormItem'
import { validateEnum } from '@/pages/Customer/Company/components/AddCompany/CompanyFormItem'

const AddClient = props => {
  const {
    onCancel,
    reload,
    onConfirm,
    dataId,
    dataType,
    defaultValues,
    sourceList,
    ...resetModalProps
  } = props

  const [formRef] = Form.useForm()
  const layout = {
    layout: 'horizontal',
    labelCol: { flex: '100px' }
  }
  const [showDataItem, setShowDataItem] = useState(false)
  const [validStatusFtl, setValidStatusFtl] = useState('')
  const dispatch = useDispatch()
  useEffect(() => {
    if (!sourceList?.length) {
      dispatch({
        type: 'client/fetchSourceList'
      })
    }
  }, [])

  const handleChange = changedValues => {
    if (!changedValues) return
    if ('clientName' in changedValues) {
      if (!changedValues.clientName || changedValues.clientName?.length === 1) {
        formRef?.setFieldsValue({ niceName: '' })
        return
      }
      const [lastName, ...firstName] = changedValues.clientName.split('')
      const newClientName = `${lastName}（${firstName.join('')}）工：`
      formRef?.setFieldsValue({ niceName: newClientName })
    }
    if ('qq' in changedValues) {
      if (!changedValues.qq) {
        formRef?.setFieldsValue({ email: '' })
        return
      }
      formRef?.setFieldsValue({ email: `${changedValues.qq}@qq.com` })
    }
  }

  const handleOnOk = () => {
    formRef
      ?.validateFields()
      .then(async values => {
        try {
          const success = await onConfirm(values)
          if (success) {
            !isNullOrUnDef(reload) && reload()
            formRef?.resetFields()
            setTimeout(() => {
              setValidStatusFtl('')
              onCancel()
            }, 80)
          }
        } catch (error) {}
      })
      .catch(({ values }) => {
        if ('telephone' in values && !values.telephone) {
          setValidStatusFtl(validateEnum.Error)
        }
      })
  }

  return (
    <Modal
      {...resetModalProps}
      onCancel={onCancel}
      width="43vw"
      title="添加客户"
      footer={
        <div>
          <Button type="default" className="mr-2" onClick={onCancel}>
            取消
          </Button>
          <Button type="primary" onClick={handleOnOk}>
            确认
          </Button>
          {dataId ? (
            <Button
              type="primary"
              className="ml-2"
              onClick={() => {
                setShowDataItem(true)
                const values = {}
                if (dataType === ChangeCompMap.BUSINESS.key) {
                  values.businessId = dataId
                }
                formRef?.setFieldsValue(values)
                handleOnOk()
              }}>
              添加并关联
            </Button>
          ) : null}
        </div>
      }>
      <Form {...layout} form={formRef} onValuesChange={handleChange} initialValues={defaultValues}>
        {showDataItem ? <ProFormText name={`${dataType}Id`} hidden /> : null}
        <ProFormText
          name="clientName"
          label="姓名"
          placeholder="请输入客户名称"
          rules={[{ required: true, message: '请输入姓名' }]}
        />
        <Form.Item
          label="客户地区"
          name="districtIds"
          rules={[{ required: true, message: '请选择地区' }]}>
          <LazyCascader showFooter={true} />
        </Form.Item>
        <Row>
          <Col span={12}>
            <ProFormSelect
              name="gender"
              label="性别"
              placeholder=""
              rules={[{ message: '请选择性别' }]}
              options={[
                { label: '男', value: '男' },
                { label: '女', value: '女' }
              ]}
            />
            <ProFormText label="部门" name="department" placeholder="" />

            <Form.Item
              label="手机"
              name="telephone"
              validateStatus={validStatusFtl}
              hasFeedback
              rules={[{ required: true, message: '请输入手机号码' }]}>
              <TelephoneFormItem validateFn={status => setValidStatusFtl(status)} />
            </Form.Item>
            <ProFormText
              label="电话"
              name="phone"
              rules={[{ message: '请输入电话/座机号' }]}
              placeholder=""
            />
          </Col>
          <Col span={12}>
            <ProFormText label="昵称" name="niceName" placeholder="" />
            <ProFormText label="职位" name="position" placeholder="" />
            <ProFormText label="QQ" name="qq" placeholder="" />
            <ProFormText label="邮箱" name="email" placeholder="" />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <ProFormText label="办公室" name="office" placeholder="" />
          </Col>
          <Col span={12}>
            <ProFormSelect
              name="sourceId"
              label="来源"
              placeholder=""
              rules={[{ message: '来源' }]}
              options={sourceList}
            />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <ProFormText label="客户地址" name="address" placeholder="" />
            <ProFormText label="客户地标" name="landmarks" placeholder="" />
          </Col>
          <Col span={12}>
            <ProFormText label="客户乘车" name="ride" placeholder="" />
            <ProFormText label="客户住宿" name="stay" placeholder="" />
          </Col>
        </Row>

        <ProFormTextArea label="备注" name="mark" placeholder="" />
      </Form>
    </Modal>
  )
}

export default connect(({ client }) => ({
  sourceList: client.sourceList
}))(AddClient)
