import React, { useEffect, useState, useRef } from 'react'
import router from 'umi/router'
import { fetch, apis } from '@/utils/request'
import { Button, Form, Input, Select, DatePicker, notification, Modal, Spin } from 'antd'
import CommunitySelect from '@/components/CommunitySelect'
import AddOn from './components/AddOn'

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 billUploadExcelAdd = fetch(apis.bill.billUploadExcelAdd)
const billInvoiceGetInvoiceInvalid = fetch(apis.bill.billInvoiceGetInvoiceInvalid)
const fetchPhaseList = fetch(apis.buildingOwnerInfo.getPhaseList)
const fetchBuildingList = fetch(apis.buildingOwnerInfo.getBuildingList)

export default Form.create()(props => {
  const [loading, setLoading] = useState(false)
  const [queryParams, setQueryParams] = useState({ pageNum: 1, pageSize: 10 })
  const [formData, setFormData] = useState()
  const [addOnData, setAddOnData] = useState()
  const [communityId, setCommunityId] = useState()
  const [phaseId, setPhaseId] = useState()
  const [buildingId, setBuildingId] = useState()
  const [phaseList, setPhaseList] = useState([])
  const [buildingList, setBuildingList] = useState([])
  const [rangeDate, setRangeDate] = useState([])
  const file = useRef()
  
  const { id } = props.location.query
  const { getFieldDecorator, setFieldsValue } = props.form

  const handleSubmit = billStatus => {
    props.form.validateFields((err, values) => {
      if (!err) {
        if (!file.current) {
          notification.warn({
            message: '请先上传账单文件'
          })
          return
        }

        if (!rangeDate || rangeDate.length !== 2) {
          notification.warn({
            message: '请设置缴费时间'
          })
          return
        }

        const data = new FormData()
        data.append('file', file.current)
        data.append('communityId', communityId)
        // data.append('billExplain', values.billExplain)
        data.append('billName', values.billName)
        data.append('startDate', rangeDate[0].format('YYYY-MM-DD'))
        data.append('endDate', rangeDate[1].format('YYYY-MM-DD'))
        data.append('billStatus', billStatus)

        if (id) {
          data.append('billId', id)
        }

        setLoading(true)
        billUploadExcelAdd({ data }).then(res => {
          setLoading(false)
          Modal.success({
            content: '生成数据成功',
            onOk: () => router.go(-1)
          })
        }).catch(e => console.error(e) || setLoading(false))
      }
    })
  }

  useEffect(() => {
    if (id) {
      setLoading(true)
      billInvoiceGetInvoiceInvalid({
        data: {
          ...queryParams,
          billId: id,
          communityId,
        }
      }).then(res => {
        setFormData(res.bill)
        // setCommunityId(communityId)
        setAddOnData(res)
        setLoading(false)
      }).catch(e => console.error(e) || setLoading(false))
    }
  }, [id, queryParams])

  useEffect(() => {
    setFieldsValue(formData || {})
  }, [formData])

  // 获取期
  useEffect(() => {
    if (communityId) {
      fetchPhaseList({params: {communityId}}).then(res => setPhaseList(res))
    }
  }, [communityId])

  // 楼栋
  useEffect(() => {
    if (phaseId) {
      fetchBuildingList({params: {phaseId}}).then(res => setBuildingList(res))
    }
    setBuildingId()
  }, [phaseId])

  return (
    <Spin spinning={loading}>
      <Form {...formItemLayout} onSubmit={e => e.preventDefault()}>
        <Form.Item label="小区" required>
          <CommunitySelect value={communityId} onChange={v => setCommunityId(v)} autoInited />
        </Form.Item>
        <Form.Item label="期/区">
          <Select onChange={v => setPhaseId(v)} placeholder="期/区" allowClear>
            {
              phaseList.map(x => (<Select.Option key={x.id} value={x.id}>{x.name}</Select.Option>))
            }
          </Select>
        </Form.Item>
        <Form.Item label="楼栋">
          <Select onChange={v => setBuildingId(v)} placeholder="栋" allowClear>
            {
              buildingList.map(x => (<Select.Option key={x.id} value={x.id}>{x.name}</Select.Option>))
            }
          </Select>
        </Form.Item>
        <Form.Item label="收费名称">
        {
          getFieldDecorator('billName', {
            rules: [
              { required: true, message: '请填写收费名称', },
            ],
          })(<Input />)
        }
        </Form.Item>
        {/* <Form.Item label="收费组说明">
        {
          getFieldDecorator('billExplain', {
            rules: [
              { required: true, message: '请填写收费组说明', },
            ],
          })(<Input />)
        }
        </Form.Item> */}
        <Form.Item label="缴费时间" required>
          <DatePicker.RangePicker value={rangeDate} onChange={v => setRangeDate(v)} style={{width: '100%'}} />
        </Form.Item>
        <Form.Item label=" " colon={false}>
          <AddOn dataSource={addOnData} onFileInput={f => file.current = f} communityId={communityId} phaseId={phaseId} buildingId={buildingId} />
        </Form.Item>
        <Form.Item {...tailFormItemLayout} >
          {/* <Button type="primary" onClick={() => handleSubmit(2)}>草稿</Button> */}
          <Button type="danger" style={{ marginLeft: '24px' }} onClick={() => handleSubmit(0)}>发布</Button>
          <Button style={{ marginLeft: '24px' }} onClick={() => router.go(-1)}>取消</Button>
        </Form.Item>
      </Form>
    </Spin>
  )
})
