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


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

  const handleCommunityChange = v => {
    setCommunityId(v)

    props.onCommunityChange(v)
  }

  const handleSearch = v => {
    props.onSearch({
      ...v,
      startDate: rangeDate[0] ? rangeDate[0].format('YYYY-MM-DD') : undefined,
      endDate: rangeDate[1] ? rangeDate[1].format('YYYY-MM-DD') : undefined,
    })
  }

  const handleReset = v => {
    setRangeDate([])
    props.onReset({
      ...v,
      startDate: undefined,
      endDate: undefined,
    })
  }

  return (    
    <Search
      onSearch={handleSearch}
      onReset={handleReset}
      render={form => {
        const { getFieldDecorator } = form

        return (
          <>
            <Form.Item label="小区">
              <CommunitySelect value={communityId} onChange={handleCommunityChange} autoInited />
            </Form.Item>
            <Form.Item label="收费ID">
            {
              getFieldDecorator('billId')(<Input />)
            }
            </Form.Item>
            <Form.Item label="收费名称">
            {
              getFieldDecorator('billName')(<Input />)
            }
            </Form.Item>
            <Form.Item label="收费时间">
              <DatePicker.RangePicker value={rangeDate} onChange={v => setRangeDate(v)} />
            </Form.Item>
            <Form.Item label="收费类型">
            {
              getFieldDecorator('isTicket')(
                <Select style={{minWidth: 100}} allowClear>
                  <Select.Option value={1}>物业</Select.Option>
                  <Select.Option value={0}>工单</Select.Option>
                </Select>
              )
            }
            </Form.Item>
          </>
        )
      }}
    />
  )
}

const TableList = props => {
  const columns = [
    {
      title: '收费编号',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
    },
    {
      title: '类型',
      dataIndex: 'isTicket',
      key: 'isTicket',
      render: t => t === 1 || t === true ? '工单' : '物业'
    },
    {
      title: '收费名称',
      dataIndex: 'billName',
      key: 'billName',
    },
    {
      title: '收费时间',
      dataIndex: 'startDate',
      key: 'startDate',
      render: (t, row) => `${row.startDate ? moment(row.startDate).format('YYYY-MM-DD') : '--'} ~ ${row.endDate ? moment(row.endDate).format('YYYY-MM-DD') : '--'}`
    },
    {
      title: '应缴户数',
      dataIndex: 'payTotalNum',
      key: 'payTotalNum',
    },
    {
      title: '已缴户数',
      dataIndex: 'payedNum',
      key: 'payedNum',
    },
    {
      title: '未缴户数',
      dataIndex: 'unpayedNum',
      key: 'unpayedNum',
    },
    {
      title: '收费状态',
      key: 'billStatus',
      render: (t, row) => {
        switch (row.billStatus) {
          case '0':
            return '进行中'
          case '1':
            return '完成'
          case '2':
            return '草稿'
          default:
            return '异常'
        }
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, row) => {
        return (
          <span>
            <Button type="link" size="small" onClick={() => props.onDetail(row)}>详情</Button>
            <Divider type="vertical" />
            <Popconfirm
              title="确认删除当前记录?"
              onConfirm={() => props.onDeleteRow(row)}
              okText="Yes"
              cancelText="No"
            >
              <Button type="link" size="small">删除</Button>
            </Popconfirm>
          </span>
        )
      }
    },
  ]

  return (
    <List
      {...props}
      columns={columns}
      rowKey="id"
    />
  )
}

const FetchBillList = fetchList(apis.bill.fetchBillList)
const deleteBillBeach = fetch(apis.bill.deleteBillBeach)

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 handleQuery = vals => {
    setQueryParams({
      ...queryParams,
      ...vals,
      pageNum: 1
    })
  }

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

  const handleDetail = row => {
    if (row.billStatus === '2') {
      router.push(`/property/bill/management/edi?id=${row.id}`)
    } else {
      router.push(`/property/bill/management/info?id=${row.id}`);
    }
  }

  const handleDeleteRow = row => {
    setLoading(true)
    deleteBillBeach({ data: [row.id] }).then(res => {
      setLoading(false)
      handleQuery()
    })
  }

  useEffect(() => {
    if (communityId) {
      setLoading(true)
      FetchBillList({...queryParams, communityId}).then(res => {
        const {list, ...pagi} = res[1]
        setListData(list)
        setPagination(pagi)
        setLoading(false)
      })
    }
  }, [queryParams, communityId])

  return (
    <div>
      <Condition onReset={handleQuery} onSearch={handleQuery} onCommunityChange={v => setCommunityId(v)} />
      <div style={{ margin: '24px 0' }}>
        <NavLink to={`/property/bill/management/add`}>
          <Button type="primary">添加</Button>
        </NavLink>
      </div>
      <Spin spinning={loading}>
        <TableList
          dataSource={listData}
          pagination={pagination}
          onPageChange={handlePageChange}
          onDetail={handleDetail}
          onDeleteRow={handleDeleteRow}
        />
      </Spin>
    </div>
  )
}
