import React, { useState, useEffect } from 'react';
import { Form, Icon, Input, Button, DatePicker, Select, Card, Row, Col, Pagination, Alert, Radio, Tag, Tooltip, Tabs, Table, notification, Modal } from 'antd';
import moment from 'moment';
import request from '../../../../../utils/request';
import apis from '../../../../../services/apis';
import Styles from './style.less';
import { router } from 'umi';
import BlockSelect from '../../../../../components/HouseSelect/BlockSelect'
import UnitSelect from '../../../../../components/HouseSelect/UnitSelect'
import FloorSelect from '../../../../../components/HouseSelect/FloorSelect'
import RoomSelect from '../../../../../components/HouseSelect/RoomSelect'
import ApartmentSelect from '../../../../../components/HouseSelect/ApartmentSelect';
import styles from '../../../../style/GoodsList.less';
import EditIcon from '@/components/EditIcon';

/**
 *图片设置
 *
 * @param {*} props
 * @returns
 */
function House(props) {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [data, setData] = useState([])
  const [viable, setViable] = useState(false)
  const [houseIdList, setHouseIdList] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([])

  useEffect(() => {
    getList()
  }, [])

  function openNotificationWithIcon(type, message) {
    notification[type]({
      message,
      description:
        '',
    });
  }

  function getList(params) {
    // 网路请求
    request({ ...apis.house.taHousingResources, params: { ...params, salesBatchId: props.salesBatchId, buildingId: props.buildingId } }).then(res => {
      console.log(res, "resresres")
      setData(res)
    }).catch(err => {
      openNotificationWithIcon('error', err.message)
    })
  }

  // 重置搜索
  function handleReset() {
    props.form.resetFields();
    getList({ pageNumber: 1, pageSize: 10 })
  }

  // 分页
  function changePageNum(pageNumber) {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    getList({ pageNumber: pageNumber, pageSize: 10, ...props.form.getFieldsValue() })
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setSelectedRowKeys(selectedRowKeys)
      setHouseIdList(selectedRows)
    },
  };

  function showEdi(e) {
    props.onSuccess(e);
  }

  //打开model
  function showAparement() {
    if (houseIdList.length < 1) {
      openNotificationWithIcon('error', '请先选择需要改变的房源')
      return
    }
    setViable(true)
  }

  function handleCancel() {
    setViable(false)
  }

  // 提交事件
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        console.log('提交数据: ', values)

        getList({ pageNumber: 1, pageSize: 10, ...values })
      }
    });
  }

  // model提交事件
  const handleSubmitApartMent = e => {
    props.form.validateFields((err, values) => {
      // if (!err) {
      if (!values.apartmentIdSelected) {
        openNotificationWithIcon('error', '请选择户型')
        return
      }
      request({ ...apis.house.changeApartment, data: { apartmentId: values.apartmentIdSelected, houseIdList } }).then(res => {
        setViable(false)
        setSelectedRowKeys([])
        setHouseIdList([])
        getList({ pageNumber: data.current, pageSize: 10 })
        openNotificationWithIcon('success', '操作成功')
      }).catch(err => {
        openNotificationWithIcon('error', err.message)
      })
      // }
    });
  }
  /**
   * 删除
   *
   * @param {*} record
   */
  function deleteHouseResource(record) {
    Modal.confirm({
      title: '确定将所选房删除?',
      content: '如果只是不想让用户看到房源，请修改发布状态为否，删除房源会导致大量关联数据异常。若房源有预选记录或认筹记录则无法删除，请先删除预选记录。',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        // 网路请求
        request({ ...apis.house.houseDelete, urlData: { id: record.houseId } }).then(res => {
          getList({ pageNumber: 1, pageSize: 10 })
          openNotificationWithIcon('success', '操作成功')
        }).catch(err => {
          // openNotificationWithIcon('error', err.message)
        })
      },
      onCancel() { },
    });
  }


  const columns = [
    {
      title: '房源编号',
      dataIndex: 'houseId',
      key: 'houseId',
    },
    {
      title: '房源',
      render: (x, row) => <><span>{row.termName}/{row.blockName}/{row.unitName}/{row.floorName}/{row.roomName}</span></>,
    },
    // {
    //   title: '期/区',
    //   dataIndex: 'termName',
    //   key: 'termName',
    // },
    // {
    //   title: '楼栋',
    //   dataIndex: 'blockName',
    //   key: 'blockName',
    // },
    // {
    //   title: '单元',
    //   dataIndex: 'unitName',
    //   key: 'unitName',
    // },
    // {
    //   title: '层',
    //   dataIndex: 'floorName',
    //   key: 'floorName',
    // },
    // {
    //   title: '房号',
    //   dataIndex: 'roomName',
    //   key: 'roomName',
    // },
    {
      title: '价格（万元）',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '对应户型',
      dataIndex: 'apartmentName',
      key: 'apartmentName',
    },
    // {
    //   title: '预选基础热度',
    //   dataIndex: 'heat',
    //   key: 'heat',
    // },
    // {
    //   title: '预选实际热度',
    //   dataIndex: 'realHeat',
    //   key: 'realHeat',
    //   render:  (x, row) => <><span style={{color: 'blue',cursor: 'pointer'}} onClick={() => showEdi({type: "preselection",houseId: row.houseId})}>{row.realHeat}</span></>,
    // },
    {
      title: '发布状态',
      dataIndex: 'status',
      key: 'status',
      render: status => <><span>{status == 0 ? '否' : status == 1 ? '是' : ''}</span></>,
    },
    {
      title: '最后修改人',
      dataIndex: 'updateName',
      key: 'updateName',
    },
    {
      title: '最后修改时间',
      dataIndex: 'updateDate',
      key: 'updateDate',
      render: (x, row) => <><span>{row.updateDate != null ? `${moment(row.updateDate).format('YYYY-MM-DD HH:mm:ss')}` : null}</span></>,
    },
    {
      title: '操作',
      dataIndex: 'apartmentId',
      key: 'apartmentId',
      render: (_, record) => (
        <>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ marginRight: '16px' }} onClick={() => showEdi({ type: "add", houseId: record.houseId })}> <EditIcon text="编辑" color='#ff925c' type="edit"></EditIcon></div>
            <div onClick={() => deleteHouseResource(record)}><EditIcon text="删除" color='#FF4A4A' type="delete"></EditIcon></div>
          </div>
        </>
      ),
    },
  ]
  const { getFieldDecorator } = props.form
  return (
    <>
      <div align="right" style={{ marginTop: '-52px', marginBottom: '20px' }}><Button onClick={() => router.go(-1)}>返回</Button></div>
      <Form layout="inline" onSubmit={e => handleSubmit(e)}>
        <Form.Item>
          {getFieldDecorator('termName')(
            <Input placeholder="请输入期/区" />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('blockName')(
            <Input placeholder="请输入楼栋" />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('unitName')(
            <Input placeholder="请输入单元" />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('floorName')(
            <Input placeholder="请输入层" />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('roomName')(
            <Input placeholder="请输入房号" />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('apartmentId')(
            <ApartmentSelect buildingId={props.buildingId} />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('status')(
            <Select placeholder="发布状态" style={{ width: '120px' }}>
              <Option value="0">否</Option>
              <Option value="1">是</Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('houseId')(
            <Input placeholder="请输入房源编号" />,
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" >
            搜索
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
            </Button>
        </Form.Item>
      </Form>
      <Button type="danger" onClick={() => showEdi({ type: "add", houseId: '' })} style={{ marginTop: '20px' }}>新增房源</Button>
      <Button type="primary" onClick={() => showEdi({ type: "batch" })} style={{ marginLeft: '18px' }}>批量导入房源</Button>
      <Button type="primary" onClick={() => showAparement()} style={{ marginLeft: '18px' }}>批量修改对应户型</Button>

      <Table rowSelection={rowSelection} dataSource={data.records} columns={columns} pagination={{ defaultCurrent: 1, current: data.current, total: data.total, onChange: e => changePageNum(e) }} style={{ marginTop: '20px' }} rowKey={r => r.houseId} />

      <Modal
        title="批量修改对应户型"
        width={400}
        destroyOnClose="true"
        footer={null}
        visible={viable}
        onOk={() => this.handleOk()}
        onCancel={e => handleCancel(e)}
      >
        <Form onSubmit={e => handleSubmitApartMent(e)}>
          <Form.Item label="将所选房源对应户型信息修改为" >
            {getFieldDecorator('apartmentIdSelected')(
              <ApartmentSelect buildingId={props.buildingId} />
            )}
          </Form.Item>
          <Form.Item style={{ width: '400px', margin: 'auto', display: 'flex', justifyContent: 'space-between' }}>
            <Button type="primary" htmlType="submit">保存</Button>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <Button onClick={() => handleCancel()}>取消</Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
const WrappedHeader = Form.create({ name: 'House' })(House);
export default WrappedHeader
