import React, { useEffect, useRef, useState } from 'react'
import { PageHeader, Button, Descriptions, Typography, Select, Icon, Table, Modal, Form, Input, notification } from 'antd'
import { fetch, fetchList, apis } from '@/utils/request'
import NavLink from 'umi/navlink'
import Prompt from '@/components/Prompt'
import Search from '../../components/Search'
import List from '../../components/List'
import Edit from './components/Edit'
import useRoomSelect from '../../utils/hooks/useRoomSelect'

const BillStatusDict = [
  { value: '0', label: '未缴费' },
  { value: '1', label: '已线上缴费' },
  { value: '2', label: '已线下缴费' },
]

const PayTypeDict = [
  { value: '0', label: '微信支付' },
  { value: '1', label: '线下支付' },
  { value: '2', label: '支付宝支付' },
]

const getDictLabel = (dict, v) => (dict.filter(x => x.value === v)[0] || {}).label

const getBillInvoiceList = fetch(apis.bill.getBillInvoiceList)
const deleteBillInvoiceById = fetch(apis.bill.deleteBillInvoiceById)
const billInvoiceOfflinePayment = fetch(apis.bill.billInvoiceOfflinePayment)
const updateBillInvoiceIdPayPrice = fetch(apis.bill.updateBillInvoiceIdPayPrice)
const updateBillInvoiceIdBillInvoiceExplain = fetch(apis.bill.updateBillInvoiceIdBillInvoiceExplain)
const updateBillNameAndBillExplainAndEndDate = fetch(apis.bill.updateBillNameAndBillExplainAndEndDate)
const exportBillInvoiceExcel = fetch(apis.bill.exportBillInvoiceExcel)

const Condition = props => {
  const {
    phaseId,
    setPhaseId,
    buildingId,
    setBuildingId,
    unitId,
    setUnitId,
    levelId,
    setLevelId,
    roomNoId,
    setRoomNoId,
    phaseList,
    buildingList,
    unitList,
    levelList,
    roomNoList
  } = useRoomSelect()
  
  const handleSearch = vals => {
    const data = {
      ...vals,
      phaseId,
      buildingId,
      unitId,
      levelId,
      roomNoId
    }

    if (props.onSearch) {
      props.onSearch(data)
    }
  }

  const handleReset = vals => {
    const data = {
      ...vals,
      phaseId: '',
      buildingId: '',
      unitId: '',
      levelId: '',
      roomNoId: ''
    }

    setPhaseId()
    setBuildingId()
    setUnitId()
    setLevelId()
    setRoomNoId()

    if (props.onReset) {
      props.onReset(data)
    }
  }

  return (
    <Search
      onSearch={handleSearch}
      onReset={handleReset}
      render={form => {
        const { getFieldDecorator } = form
        
        const handlePhaseChange = e => setPhaseId(e)
        const handleBuildingChange = e => setBuildingId(e)
        const handleUnitChange = e => setUnitId(e)
        const handleLevelChange = e => setLevelId(e)
        const handleRoomChange = e => setRoomNoId(e)

        return (
          <>
            <Form.Item label="选择房子">
              <Select value={phaseId} onChange={handlePhaseChange} style={{ minWidth: '120px' }} placeholder="期/区">
                {
                  phaseList.map(x => (<Select.Option key={x.id} value={x.id}>{x.name}</Select.Option>))
                }
              </Select>
            </Form.Item>
            <Form.Item>
              <Select value={buildingId} onChange={handleBuildingChange} style={{ minWidth: '120px' }} placeholder="栋">
                {
                  buildingList.map(x => (<Select.Option key={x.id} value={x.id}>{x.name}</Select.Option>))
                }
              </Select>
            </Form.Item>
            <Form.Item>
              <Select value={unitId} onChange={handleUnitChange} style={{ minWidth: '120px' }} placeholder="单元">
                {
                  unitList.map(x => (<Select.Option key={x.id} value={x.id}>{x.name}</Select.Option>))
                }
              </Select>
            </Form.Item>
            <Form.Item>
              <Select value={levelId} onChange={handleLevelChange} style={{ minWidth: '120px' }} placeholder="楼层">
                {
                  levelList.map(x => (<Select.Option key={x.id} value={x.id}>{x.name}</Select.Option>))
                }
              </Select>
            </Form.Item>
            <Form.Item>
              <Select value={roomNoId} onChange={handleRoomChange} style={{ minWidth: '120px' }} placeholder="户号">
                {
                  roomNoList.map(x => (<Select.Option key={x.id} value={x.id}>{x.name}</Select.Option>))
                }
              </Select>
            </Form.Item>
            <Form.Item label="缴费状态">
            {
              getFieldDecorator('billStatus')(
                <Select style={{ width: '160px' }} placeholder="缴费状态">
                  {
                    BillStatusDict.map(x => <Select.Option key={x.value} value={x.value}>{x.label}</Select.Option>)
                  }
                </Select>
              )
            }
            </Form.Item>
            <Form.Item label="缴费人姓名">
            {
              getFieldDecorator('payName')(<Input style={{ width: '160px' }} placeholder="缴费人姓名" />)
            }
            </Form.Item>
          </>
        )
      }}
    />
  )
}

export default props => {
  const [loading, setLoading] = useState(false)
  const [showEditor, setShowEditor] = useState(false)
  const [showPrompt, setShowPrompt] = useState(false)
  const [billData, setBillData] = useState({})
  const [listData, setListData] = useState([])
  const [pagination, setPagination] = useState({})
  const [queryParams, setQueryParams] = useState({ pageNum: 1, pageSize: 10 })
  
  const { id } = props.location.query
  const editData = useRef({ type: undefined, data: undefined })

  const handleSearch = vals => {
    setQueryParams({
      ...queryParams,
      ...vals,
      pageNum: 1,
    })
  }

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

  const handleExplainChange = row => {
    editData.current = {type: 'explain', data: row}
    setShowPrompt(true)
  }

  const handlePriceChange = row => {
    editData.current = {type: 'price', data: row}
    setShowPrompt(true)
  }

  const handleDeleteRow = row => {
    deleteBillInvoiceById({data: [row.id]}).then(res => {
      notification.success({ message: '删除数据成功' })

      // 触发数据刷新
      setQueryParams({...queryParams})   
    })
  }

  const handleOffline = row => {
    billInvoiceOfflinePayment({data: [row.id]}).then(res => {
      notification.success({ message: '设置线下缴费成功' })

      // 触发数据刷新
      setQueryParams({...queryParams})
    })
  }

  const handlePrompt = val => {
    const {type, data} = editData.current
    if (type === 'explain') {
      updateBillInvoiceIdBillInvoiceExplain({urlData: {id: data.id}, data: {billInvoiceExplain: val}}).then(res => {
        notification.success({ message: '修改费用说明成功' })
  
        // 触发数据刷新
        setQueryParams({...queryParams})
        setShowPrompt(false)
      })
    } else if (type === 'price') {
      updateBillInvoiceIdPayPrice({urlData: {id: data.id}, data: {payPrice: val}}).then(res => {
        notification.success({ message: '修改费用成功' })
  
        // 触发数据刷新
        setQueryParams({...queryParams})
        setShowPrompt(false)
      })
    }
  }

  const handleEditorSubmit = vals => {
    updateBillNameAndBillExplainAndEndDate({data: {id, ...vals}}).then(res => {
      notification.success({ message: '修改费用信息成功' })

      // 触发数据刷新
      setQueryParams({...queryParams})
      setShowEditor(false)
    })
  }

  const exportExcel = () => {
    exportBillInvoiceExcel({ urlData: {id} }).then(res => {
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(new Blob([res]))
      link.setAttribute('download', '缴费单.xls')
      link.click()
    })
  }

  useEffect(() => {
    setLoading(true)
    getBillInvoiceList({data: {
      billId: id,
      ...queryParams,
    }}).then(res => {
      const {list, pageNum, pageSize, total, ...billInfo} = res || {}
      setListData(list)
      setPagination({
        ...pagination,
        current: pageNum,
        pageSize,
        total,
      })
      setBillData(billInfo)
      setLoading(false)
    }).catch(e => setLoading(false))
  }, [id, queryParams])

  return (
    <div>
      <PageHeader
        title="收费情况"
        backIcon={false}
        extra={[<Button key="1" onClick={() => setShowEditor(true)}>修改</Button>]}
        style={{ borderBottom: '1px solid rgb(235, 237, 240)' }}
      >
        <Descriptions column={3}>
          <Descriptions.Item label="收费组名称">{billData.billName}</Descriptions.Item>
          <Descriptions.Item label="截止时间">{billData.endDate}</Descriptions.Item>
          <Descriptions.Item label="收费组说明">
            <Typography.Text ellipsis>{billData.billExplain}</Typography.Text>
          </Descriptions.Item>
        </Descriptions>
      </PageHeader>

      <div style={{margin: '36px 0'}}>
        <Condition onSearch={handleSearch} onReset={handleSearch} />
      </div>

      <div style={{margin: '24px 0'}}>
        <NavLink to="/property/bill/management/info/add"><Button type="primary"><Icon type="plus" />添加更多收费单</Button></NavLink>
        <Button type="link" onClick={exportExcel}><Icon type="export" />导出数据</Button>
        <div style={{height: '40px', lineHeight: '40px', marginLeft: '10px', fontSize: '14px', color: '#888' }}>未缴户主费用可以直接点击 收费金额数字 修改，已缴费户主无法修改，需要线下多退少补</div>
      </div>

      <div>
        <List dataSource={listData} loading={loading} pagination={pagination} onPageChange={handlePageChange} rowKey="id">
          <Table.Column title="收费单号" dataIndex="id" key="id" />
          <Table.Column title="房屋信息" dataIndex="roomNo" key="roomNo" render={(_, row) => row.phase + row.building + row.unit + row.roomNo} />
          <Table.Column title="收费单说明" dataIndex="billInvoiceExplain" key="billInvoiceExplain" render={(t, row) => (
            <Button type="link" onClick={() => handleExplainChange(row)}><Icon type="edit" />{t}</Button>
          )} />
          <Table.Column title="金额(元)" dataIndex="payPrice" key="payPrice" render={(t, row) => (
            <Button type="link" onClick={() => handlePriceChange(row)}><Icon type="edit" />{t/100}</Button>
          )} />
          <Table.Column title="订单号" dataIndex="billStatement" key="billStatement" />
          <Table.Column title="缴费状态" dataIndex="billStatus" key="billStatus" render={t => getDictLabel(BillStatusDict, t)} />
          <Table.Column title="缴费途径" dataIndex="payType" key="payType" render={t => getDictLabel(PayTypeDict, t)} />
          <Table.Column title="缴费人" dataIndex="payName" key="payName" />
          <Table.Column title="缴费时间" dataIndex="payDate" key="payDate" />
          <Table.Column title="新建时间" dataIndex="createDate" key="createDate" />
          <Table.Column title="新建人" dataIndex="createUserName" key="createUserName" />
          <Table.Column title="修改时间" dataIndex="updateDate" key="updateDate" />
          <Table.Column title="修改人" dataIndex="updateUserName" key="updateUserName" />
          <Table.Column
            title="操作"
            key="action"
            render={(_, row) => {
              return (
                <>
                  <Popconfirm
                    title="确认进行删除操作?"
                    onConfirm={() => handleDeleteRow(row)}
                    okText="删除"
                    cancelText="取消"
                  >
                    <Button type="link">删除</Button>
                  </Popconfirm>
                  <Divider type="vertical" />
                  <Popconfirm
                    title="确认设置为线下缴费?"
                    onConfirm={() => handleOffline(row)}
                    okText="缴费"
                    cancelText="取消"
                  >
                    <Button type="link">线下缴费</Button>
                  </Popconfirm>
                </>
              )
            }}
          />
        </List>
      </div>
      <Prompt visible={showPrompt} onOk={handlePrompt} onCancel={() => setShowPrompt(false)} />
      <Edit
        visible={showEditor}
        initialData={billData}
        onSubmit={handleEditorSubmit}
        onCancel={() => setShowEditor(false)}
      />
    </div>
  )
}
