import React, { useState, useEffect } from 'react'
import { Select, Spin, Table, Button, Form, Input, Icon, Modal, Popconfirm } from 'antd'
import NavLink from 'umi/navlink'
import { fetch, fetchList, apis } from '@/utils/request'
import { exportExcel } from '@/utils/utils'
import CommunitySelect from '@/components/CommunitySelect'
import Search from '../components/Search'
import List from '../components/List'
import useRoomSelect from '../utils/hooks/useRoomSelect'

const buildingInfoList = fetch(apis.buildingOwnerInfo.buildingList)
const buildingInfoListExport = fetch(apis.buildingOwnerInfo.buildingListExport)
const deleteBuilding = fetch(apis.buildingOwnerInfo.deleteBuilding)

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

  const {
    phaseId,
    setPhaseId,
    buildingId,
    setBuildingId,
    unitId,
    setUnitId,
    levelId,
    setLevelId,
    roomNoId,
    setRoomNoId,
    phaseList,
    buildingList,
    unitList,
    levelList,
    roomNoList
  } = useRoomSelect(communityId)

  const handleSearch = vals => {
    const data = {
      ...vals,
      communityId,
      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)
    }
  }

  const handleCommunityChange = v => {
    setCommunityId(v)

    props.onCommunityChange(v)
  }

  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>
              <CommunitySelect value={communityId} onChange={handleCommunityChange} autoInited />
            </Form.Item>
            <Form.Item>
              <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>
            {
              getFieldDecorator('ownerName')(<Input style={{ width: '160px' }} placeholder="姓名" />)
            }
            </Form.Item>
            <Form.Item>
            {
              getFieldDecorator('ownerTel')(<Input style={{ width: '160px' }} placeholder="手机号" />)
            }
            </Form.Item>
            <Form.Item>
            {
              getFieldDecorator('idCard')(<Input style={{ width: '200px' }} placeholder="身份证" />)
            }
            </Form.Item>
            <Form.Item>
            {
              getFieldDecorator('roleName')(
                <Select style={{ width: '200px' }} placeholder="身份">
                  <Select.Option value={1}>户主</Select.Option>
                  <Select.Option value={3}>家属</Select.Option>
                  <Select.Option value={2}>租客</Select.Option>
                </Select>
              )
            }
            </Form.Item>
            <Form.Item>
            {
              getFieldDecorator('verifyStatus')(
                <Select style={{ width: '200px' }} placeholder="审核状态">
                  <Select.Option value={0}>未审核</Select.Option>
                  <Select.Option value={1}>审核通过</Select.Option>
                  <Select.Option value={2}>审核不通过</Select.Option>
                </Select>
              )
            }
            </Form.Item>
          </>
        )
      }}
    />
  )
}

const verifyStatusDict = {
  '0': '未审核',
  '1': '审核通过',
  '2': '审核不通过'
}

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

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      // console.log('------>', selectedRowKeys)
      setSelectedKeys(selectedRowKeys)
    }
  }

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

  const handleDeleteRow = row => {
    deleteBuilding({ data: [row.id] }).then(res => {
      Modal.success({
        content: '数据删除成功',
        onOk: () => {
          window.location.reload()
        }
      })
    })
  }

  const handleDeleteSelected = () => {
    deleteBuilding({ data: selectedKeys }).then(res => {
      Modal.success({
        content: '数据删除成功',
        onOk: () => {
          window.location.reload()
        }
      })
    })
  }

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

  const handleExport = () => {
    setLoading(true)
    buildingInfoListExport({ data: {...queryParams, communityId, pageNum: 1, pageSize: 9999} }).then(res => {
      setLoading(false)
      exportExcel(res, "业主列表")
    }).catch(() => setLoading(false))
  }

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

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

  return (
    <div>
      <Condition onSearch={handleSearch} onReset={handleSearch} onCommunityChange={v => setCommunityId(v)} />
      <div style={{ margin: '24px 0' }}>
        <NavLink to={`/property/proprietor/add`}>
          <Button type="primary">添加</Button>
        </NavLink>
        <div style={{marginLeft: 16, display: 'inline-block'}}>
          <Popconfirm
            title="确认进行批量删除操作?"
            onConfirm={handleDeleteSelected}
            okText="确定"
            cancelText="取消"
          >
            <Button type="danger" disabled={!selectedKeys.length}>批量删除</Button>
          </Popconfirm>
        </div>
        <div style={{marginLeft: 16, display: 'inline-block'}}>
          <Button onClick={handleExport}>导出</Button>
        </div>
        <NavLink to={`/property/proprietor/batch?community=${communityId}`}>
          <Button type="link"><Icon type="upload"/>批量导入业主资料</Button>
        </NavLink>
      </div>
      <List
        dataSource={listData}
        loading={loading}
        pagination={pagination}
        rowSelection={rowSelection} 
        onPageChange={handlePageChange}
        onChange={handleTableChange}
        rowKey="id"
      >
        <Table.Column
          title="姓名"
          dataIndex="ownerName"
          key="ownerName"
          render={(_, row) => {
            return row.userVerifyId ? (
              <NavLink to={`/property/proprietor/detail?id=${row.userVerifyId}`}>
                <Button type="link">{row.ownerName}</Button>
              </NavLink>
            ) : row.ownerName
          }}
        />
        <Table.Column title="手机号" dataIndex="ownerTel" key="ownerTel" />
        <Table.Column title="身份证" dataIndex="idCard" key="idCard" />
        <Table.Column title="性别" dataIndex="idCard" key="idCard1" render={t => !t ? '' : (t.substring(-2, 1) - 0) % 2 === 1 ? '男' : '女'} />
        <Table.Column
          title="房间号"
          dataIndex="roomNoName"
          key="roomNoName"
          render={(_, row) => {
            return (
              <span>
                {row.phaseName + row.buildingName + row.unitName + row.levelName + row.roomNoName}
              </span>
            )
          }}
        />
        <Table.Column title="身份" dataIndex="roleName" key="roleName" />
        <Table.Column
          title="审核状态"
          dataIndex="verifyStatus"
          key="verifyStatus"
          render={(_, row) => {
            return (
              <span>
                {verifyStatusDict[row.verifyStatus] || ''}
              </span>
            )
          }}
          sorter={true}
        />
        <Table.Column title="审核人" dataIndex="updateName" key="updateName" />
        <Table.Column title="编辑时间" dataIndex="createDate" key="createDate" />
        <Table.Column
          title="操作"
          key="action"
          render={(_, row) => {
            return (
              <Popconfirm
                title="确认进行删除操作?"
                onConfirm={() => handleDeleteRow(row)}
                okText="删除"
                cancelText="取消"
              >
                <Button type="link">删除</Button>
              </Popconfirm>
            )
          }}
        />
      </List>

    </div>
  )
}
