import React, { useRef, useState } from 'react'
import { Button, Spin, Table, Icon, notification } from 'antd'
import router from 'umi/router'
import { fetch, apis } from '@/utils/request'

const { Column } = Table
const spaceStyle = { marginLeft: '16px' }

const uploadBuildingTreeExcel = fetch(apis.buildingOwnerInfo.uploadBuildingTreeExcel)
const submitBuildingTreeExcel = fetch(apis.buildingOwnerInfo.submitBuildingTreeExcel)

export default props => {
  const [loading, setLoading] = useState(false)
  const [dataList, setDataList] = useState([])
  const [pagenavi, setPagenavi] = useState({ pageSize: 10, total: 0 })

  const excelRef = useRef()

  const downloadExcel = () => {
    const link = document.createElement('a')
    link.href = "http://jingcheng-h5temp.oss-cn-shanghai.aliyuncs.com/%E6%A5%BC%E6%A0%8B%E5%BA%93%E6%A8%A1%E6%9D%BF.xlsx"
    link.setAttribute('download', '楼栋库模板.xlsx')
    link.click()
  }

  const importExcel = () => {
    const input = document.createElement('input')
    input.setAttribute('type', 'file')
    input.addEventListener('input', e => {
      const files = e.target.files
      if (files && files[0]) {
        excelRef.current = files[0]
        const formData = new FormData()
        formData.append('file', excelRef.current)
        
        setLoading(true)
        uploadBuildingTreeExcel({ data: formData }).then(res => {
          setDataList(res.list)
          setPagenavi({
            ...pagenavi,
            pageSize: res.size,
            total: res.total
          })
          setLoading(false)
        }).catch(() => {
          setLoading(false)
        })
      }
    })
    input.click()
  }

  const submitExcel = () => {
    if (!excelRef.current) {
      notification.warning({ message: '没有选择文件' })
      return
    }

    const formData = new FormData()
    formData.append('file', excelRef.current)

    setLoading(true)
    submitBuildingTreeExcel({ data: formData }).then(res => {
      notification.success({ message: '提交成功' })

      setLoading(false)
    }).catch(() => {
      setLoading(false)
    })
  }

  return (
    <div>
      <div style={{ marginBottom: '24px' }}>
        <Button type="primary" onClick={importExcel}><Icon type="upload" />选取文件并预览</Button>
        <Button type="danger" onClick={submitExcel} style={spaceStyle}>提交</Button>
        <Button style={spaceStyle} onClick={() => router.go(-1)}>取消</Button>
        <Button type="link" onClick={downloadExcel} style={spaceStyle}><Icon type="download" />下载模板</Button>
      </div>

      <Table dataSource={dataList} pagination={pagenavi} loading={loading}>
        <Column key="phaseName" title="期/区" dataIndex="phaseName" />
        <Column key="buildingName" title="栋" dataIndex="buildingName" />
        <Column key="unitName" title="单元" dataIndex="unitName" />
        <Column key="levelName" title="楼层" dataIndex="levelName" />
        <Column key="roomNoName" title="户号" dataIndex="roomNoName" />
      </Table>
    </div>
  )

}
