import React, { useState, useEffect } from 'react'
import { Select, Spin, Table, Button, Form, Input, Divider, Icon, DatePicker } from 'antd'
import NavLink from 'umi/navlink'
import moment from 'moment';
import { fetchList, apis, fetch } from '@/utils/request'
import CommunitySelect from '@/components/CommunitySelect'
import Search from '../../components/Search'
import List from '../../components/List'

const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

const exportStatementExcel = fetch(apis.bill.exportStatementExcel)
const getBillStatementAll = fetch(apis.bill.getBillStatementAll)

const StatusDict = {
  '0': '未支付',
  '1': '已支付',
  '2': '支付中',
  '3': '已关闭',
}

const PayStatusDict = [
  {
    label: '未支付',
    value: '0',
  },
  {
    label: '已支付',
    value: '1',
  },
  {
    label: '支付中',
    value: '2',
  },
  {
    label: '已关闭',
    value: '3',
  },
]

const PayTypeDict = {
  '0': '微信缴费',
  '1': '线下缴费',
  // '2': '支付宝缴费',
}

const PayTypesDict = [
  {
    label: '微信缴费',
    value: '0',
  },
  {
    label: '线下缴费',
    value: '1',
  },
]

const Condition = props => {
  const [communityId, setCommunityId] = useState()

  const handleCommunityChange = v => {
    setCommunityId(v)

    props.onCommunityChange(v)
  }

  return (
    <Search
      onSearch={props.onSearch}
      onReset={props.onReset}
      render={form => {
        const { getFieldDecorator, setFieldsValue } = form
        
        return (
          <>
            <Form.Item label="小区">
              <CommunitySelect value={communityId} onChange={handleCommunityChange} autoInited />
            </Form.Item>
            <Form.Item label="订单号">
            {
              getFieldDecorator('orderBumber')(<Input placeholder="订单号" />)
            }
            </Form.Item>
            <Form.Item label="缴费项目编号">
            {
              getFieldDecorator('billId')(<Input placeholder="缴费项目编号" />)
            }
            </Form.Item>
            <Form.Item label="缴费项目名">
            {
              getFieldDecorator('billName')(<Input placeholder="缴费项目名" />)
            }
            </Form.Item>
            <Form.Item label="收费单号">
            {
              getFieldDecorator('billInvoiceId')(<Input placeholder="收费单号" />)
            }
            </Form.Item>
            <Form.Item label="缴费人手机号">
            {
              getFieldDecorator('payPhone')(<Input placeholder="缴费人手机号" />)
            }
            </Form.Item>
            <Form.Item label="订单状态">
            {
              getFieldDecorator('orderStatus')(
                <Select placeholder="选择订单状态" style={{ width: '120px' }}>
                  {
                    PayStatusDict.map(x => (<Select.Option key={x.value} value={x.value}>{x.label}</Select.Option>))
                  }
                </Select>
              )
            }
            </Form.Item>
            <Form.Item label="缴费方式">
            {
              getFieldDecorator('payType')(
                <Select placeholder="选择缴费方式" style={{ width: '120px' }}>
                  {
                    PayTypesDict.map(x => (<Select.Option key={x.value} value={x.value}>{x.label}</Select.Option>))
                  }
                </Select>
              )
            }
            </Form.Item>
            <Form.Item label="缴费时间">
            {getFieldDecorator('createTime')(
              <RangePicker placeholder={['开始时间', '结束时间']} />
            )}
          </Form.Item>
          </>
        )
      }}
    />
  )
}

export default props => {
  const [loading, setLoading] = useState(false)
  const [listData, setListData] = useState([])
  const [pagination, setPagination] = useState({})
  const [queryParams, setQueryParams] = useState({ pageNum: 1, pageSize: 10 })
  const [communityId, setCommunityId] = useState()

  const handleSearch = vals => {
    let { createTime, ...submitValue  } = vals
    if (null != createTime && createTime.length > 0) {
      const [startCreateDate, endCreateDate] = createTime
      submitValue.startCreateDate = moment(startCreateDate).format('YYYY-MM-DD');
      submitValue.endCreateDate = moment(endCreateDate).format('YYYY-MM-DD');
    } else {
      submitValue.startCreateDate = null
      submitValue.endCreateDate = null
    }
    setQueryParams({
      ...queryParams,
      ...submitValue,
      pageNum: 1,
    })
  }

  const handlePageChange = (pageNum, pageSize) => {
    setQueryParams({
      ...queryParams,      
      pageNum,
      pageSize,
    })
  }

  const handleTableChange = (pagination, filters, sorter) => {
      console.log(sorter)
      setQueryParams({
        ...queryParams,      
        sortKey: sorter.columnKey,
        sortOrder: sorter.order,
      })
  };

  const exportExcel = () => {
    exportStatementExcel().then(res => {
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(new Blob([res]))
      link.setAttribute('download', '流水信息.xls')
      link.click()
    })
  }

  useEffect(() => {
    setLoading(true)
    getBillStatementAll({ data: {...queryParams, communityId} }).then(res => {
      const {list, ...pagi} = res || {}
      setListData(list)
      setPagination(pagi)
      setLoading(false)
    }).catch(err => setLoading(false))
  }, [queryParams, communityId])

  return (
    <div>
      <Condition onSearch={handleSearch} onReset={handleSearch} onCommunityChange={v => setCommunityId(v)}  />
      {/* <div style={{ margin: '24px 0' }}>
        <Button type="link" onClick={exportExcel}><Icon type="download"/>导出数据</Button>
      </div> */}
      <List dataSource={listData} loading={loading} pagination={pagination} onPageChange={handlePageChange} 
        onChange={handleTableChange}
      rowKey="id">
        <Table.Column
          title="订单号"
          dataIndex="id"
          key="id"
          render={(_, row) => {
            return (
              <NavLink to={`/property/bill/order/info?id=${row.orderBumber}`}>
                <Button type="link">{row.orderBumber}</Button>
              </NavLink>
            )
          }}
        />
        <Table.Column
          title="收费组"
          dataIndex="billId"
          key="billId"
          render={(_, row) => {
            return (row.billIdList || []).map(item => (
              <NavLink key={item} to={`/property/bill/management/info?id=${item}`}>
                <Button type="link">{item}</Button>
              </NavLink>
            ))
          }}
        />
        <Table.Column
          title="收费单号"
          dataIndex="billInvoiceId"
          key="billInvoiceId"
          render={(_, row) => {
            return (row.billInvoiceIdList || []).map(item => (
              <span key={item}>{item}</span>
            ))
          }}
        />
        <Table.Column title="总费用金额" dataIndex="sumPrice" key="sumPrice" render={sumPrice => (sumPrice === null || sumPrice === undefined ? '' : sumPrice/100)} />
        <Table.Column
          title="订单状态"
          dataIndex="orderStatus"
          key="order_status"
          render={(_, row) => StatusDict[row.orderStatus]}
          sorter={true}
        />
        <Table.Column title="缴费人手机号" dataIndex="payPhone" key="payPhone" />
        <Table.Column title="缴费备注" dataIndex="payRemark" key="payRemark" />
        <Table.Column title="缴费方式" dataIndex="payType" key="payType" render={payType => PayTypeDict[payType]}/>
        <Table.Column title="订单生成时间" dataIndex="createDate" key="create_date" 
          sorter={true}/>
        <Table.Column title="缴费完成时间" dataIndex="createTime" key="create_time" 
          sorter={true}/>
      </List>

    </div>
  )
}
