import React, { useEffect, useState } from 'react'
import { Button, Upload, Icon, Table } from 'antd'
import { fetch, apis } from '@/utils/request'
import List from '../../../components/List'

const billDownloadExcel = fetch(apis.bill.billDownloadExcel)
const billUploadExcel = fetch(apis.bill.billUploadExcel)

const Section = props => {
  return (
    <p style={{ color: '#99a9bf', fontSize: '13px' }}>
      {props.children}
    </p>
  )
}

export default props => {
  const [loading, setLoading] = useState(false)
  const [listData, setListData] = useState([])
  const [pagination, setPagination] = useState({})

  const handleDownloadExcel = () => {
    billDownloadExcel().then(res => {
      const url = window.URL.createObjectURL(new Blob([res]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', '缴费单模板.xls')
      link.click()
    })
  }

  const handleUploadExcel = () => {
    const input = document.createElement('input')
    input.setAttribute('type', 'file')
    input.addEventListener('input', e => {
      const file = e.target.files[0]
      if (!file) {
        return
      }

      const data = new FormData()
      data.append('file', file)

      if (props.onFileInput) {
        props.onFileInput(file)
      }

      setLoading(true)
      billUploadExcel({data}).then(res => {
        setListData(res.list)
        setPagination({ total: res.total })
        setLoading(false)
      }).catch(() => setLoading(false))
    })

    input.click()
  }

  useEffect(() => {
    if (props.dataSource) {
      setListData(props.dataSource.billInvoice)
      setPagination({ total: props.dataSource.total })
    }
  }, [props.dataSource])

  return (
    <div>
      <Section>
        <span>如果还未制作账单，请先下载账单模板，按规则填写费用后再上传</span>
        <Button type="link" size="small" style={{ marginLeft: '6px' }} onClick={handleDownloadExcel}><Icon type="download" />下载模板</Button>
        <Button type="link" size="small" onClick={handleUploadExcel}><Icon type="upload" />选取账单文件并预览</Button>
      </Section>
      <Section>
        <span>如果想修改下表的内容，请重新下载excel模板填写金额后上传，系统会直接删除下表所有旧数据，以新的excel内容为准</span>
      </Section>
      <List dataSource={listData} loading={loading} pagination={pagination} size="small" bordered>
        <Table.Column align="center" title="房屋信息" dataIndex="phase" key="phase" render={(_, row) => (row.phase + row.building + row.unit + row.level + row.roomNo)} />
        <Table.Column align="center" title="收费说明" dataIndex="billExplain" key="billExplain" />
        <Table.Column align="center" title="收费金额(元)" dataIndex="payPrice" key="payPrice" render={payPrice => (payPrice === null || payPrice === undefined ? '' : Number(payPrice/100).toFixed(2))} />
      </List>
      <Section>
        <span>点击发送后账单会发送给对应家庭，家庭中的成员都可以查看到他们家的收费项，缴费成功无法线上退款，只能线下当面退款，请先保存为草稿，核对无误后再发送账单给住户</span>
      </Section>
    </div>
  )
}
