import React, { useEffect, useState } from 'react'
import { connect } from 'dva';
import { Button, Form, Input, message, Select } from 'antd'
import { fetch, apis } from '@/utils/request'
import AuthButton from '@/components/AuthButton'
import InputNumber from './components/InputNumber'
import { formItemLayout, validMinNum } from './utils'

const getChannel = fetch(apis.building.channel.get)
// const saveChannel = fetch(apis.building.channel.save)
const updateChannel = fetch(apis.building.channel.update)
const getChannelDict = fetch(apis.channelList.getList)

const ChannelForm = React.forwardRef((props, ref) => {
  const { form, history, user } = props
  const { getFieldDecorator, setFieldsValue, validateFields } = form
  const { query } = history.location;
  const { id } = query;

  const [loading, setLoading] = useState(false)
  const [dict, setDict] = useState([])

  const handleSubmit = (e) => {
    e.preventDefault();
    validateFields((err, values) => {
      if (!err) {
        const data = {
          ...values,
          buildingId: id,
        }

        setLoading(true)
        updateChannel({ data }).then(() => {
          setLoading(false)
          message.success('数据保存成功')
        }).catch(() => {
          setLoading(false)
        })
      }
    });
  }

  useEffect(() => {
    getChannelDict({ params: { pageSize: 500, institutionId: user.institutionId }}).then((res) => {
      const { records } = res || {}
      if (records?.length) {
        setDict(records)
      }
    })
  }, [])

  useEffect(() => {
    if (id) {
      getChannel({ urlData: { id } }).then((res) => {
        if (res) {
          setFieldsValue(res)
        }
      })
    }
  }, [id])

  return (
    <Form {...formItemLayout} onSubmit={handleSubmit}>
      <Form.Item label="渠道">
      {getFieldDecorator('channelIdList', {
        rules: [{required: true, message: '请选择渠道'}]
      })(
        <Select mode="multiple" style={{ width: '100%' }}>
          {
            dict.map((item) => (<Select.Option key={item.channelId} value={`${item.channelId}`}>{item.channelName}</Select.Option>))
          }          
        </Select>
      )}
      </Form.Item>
      <Form.Item label="报备有效期">
      {getFieldDecorator('expirationDate', {
          rules: [{ validator: validMinNum }],
      })(<InputNumber min={0} step={1} addonAfter="天" />)}
      </Form.Item>
      <Form.Item label="报备规则">
      {getFieldDecorator('remark', {})(<Input.TextArea row={4} />)}
      </Form.Item>
      <Form.Item label=" " colon={false} style={{marginTop: '2em'}}>
        <AuthButton name="building.channel.save">
          <Button style={{marginLeft: '4em'}} loading={loading} type="primary" htmlType="submit">保存</Button>
        </AuthButton>
        <Button style={{marginLeft: '4em'}} loading={loading} type="primary" htmlType="submit">保存</Button>
        {/* <Button style={{marginLeft: '2em'}} onClick={props.onCancel}>取消</Button> */}
      </Form.Item>
    </Form>
  )
})

export default connect((s) => ({ user: s.user.currentUser }))(Form.create({})(ChannelForm))
