import React, { useState, useEffect } from 'react';
import { Form, Icon, Input, Button, DatePicker, Select, Card, Row, Col, Pagination, Alert, 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 AuthButton from '@/components/AuthButton';


const { Option } = Select;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { Meta } = Card;

const tempDate = [{ code: 's101' }]

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

/**
 *卡片
 *
 * @returns
 */
function CartBody(props) {
  const { data } = props


  function toEdi(record) {
    router.push({
      pathname: '/building/list/add',
      query: {
        id: record.buildingId,
      },
    })
  }

  /**
   *发布 取消 发布
   *
   * @param {*} record
   */
  function pulicAndUnPulic(record) {
    const modal = Modal.confirm();
    const buidingStatus = record.status === 1 ? 2 : 1
    const title = record.status === 1 ? '确认取消发布此数据?' : '确认发布此数据?'

    modal.update({
      content: title,
      okText: '确认',
      cancelText: '关闭',
      onOk: () => {
        request({ ...apis.building.updateStatus, data: { id: record.buildingId, status: buidingStatus } }).then(() => {
          openNotificationWithIcon('success', '操作成功')
          props.onSuccess()
        }).catch(err => {
          openNotificationWithIcon('error', err.message)
        })

        modal.destroy();
      },
      onCancel: () => {
        modal.destroy();
      },
    });
  }

  /**
   *删除楼盘
   *
   * @param {*} record
   */
  function deleteBuilding(record) {
    const { url, method } = apis.building.deleteBuilding
    const tempUrl = url.substring(0, url.lastIndexOf('id')).concat(record.buildingId)

    const modal = Modal.confirm();
    modal.update({
      content: '确定删除此楼盘？',
      okText: '确认',
      cancelText: '关闭',
      onOk: () => {
        request({ url: tempUrl, method }).then(() => {
          openNotificationWithIcon('success', '操作成功')
          props.onSuccess()
        }).catch(err => {
          openNotificationWithIcon('error', err.message)
        })

        modal.destroy();
      },
      onCancel: () => {
        modal.destroy();
      },
    });
  }

  return (
    <Card
      hoverable
      style={{ minWidth: '400px', borderRadius: '12px', margin: '10px', boxShadow: '0px 0px 16px 2px rgba(0,0,0,0.12)' }}
      cover={<img alt="example" src={data.poster} style={{ borderRadius: '12px 12px 0 0', width: '100%', height: '14vw' }}></img>}
      bodyStyle={{ padding: '10px 20px' }}
    >
      <p className={Styles.cardText}>
        <span className={Styles.title}>楼盘编号</span>
        <span >：{data.code}</span>
        <span className={Styles.ediText} onClick={() => toEdi(data)}>
          编辑
                <Icon type="form" style={{ color: '#C0C4CC', marginLeft: '10px' }} />
        </span>
      </p>
      <p className={Styles.cardText}>
        <span className={Styles.title}>楼盘名称</span>
        <span >：{data.name}</span>
      </p>
      <p className={Styles.cardItem}>
        <span className={Styles.title}>均价</span>
        <span >
          ：约<span style={{ color: '#FF0707', fontSize: '20px' }}> {data.price} </span>元/m
        </span>
      </p>
      <p className={Styles.cardItem}>
        <span className={Styles.title}>项目地址</span>
        <span className={Styles.address}>：{data.address}</span>
      </p>
      <p className={Styles.cardItem}>
        <span className={Styles.title}>发布状态</span>
        <span >：{data.status === 1 ? '已发布' : '未发布'}</span>
      </p>
      <p className={Styles.cardItem}>
        <span className={Styles.title}>录入时间</span>
        <span >：{data.createDate}</span>
      </p>
      <p style={{ margin: '15px 0', position: 'relative', fontSize: '18px' }}>
        <span style={{ color: '#FF4A4A' }} onClick={() => pulicAndUnPulic(data)}>
          {/* 已发布的时候，需要显示取消发布的字样 */}
          {data.status === 1 ? '取消发布' : '发布'}
          <Icon type={data.status === 1 ? 'close-circle' : 'form'} style={{ color: '#C0C4CC', marginLeft: '8px' }} />
        </span>
        <span style={{
          color: '#FF4A4A', position: 'absolute', right: '0',
        }} onClick={() => deleteBuilding(data)}>
          删除
                <Icon type="rest" style={{ color: '#C0C4CC', marginLeft: '8px' }} />
        </span>
      </p>
    </Card>
  )
}

/**
 *
 *
 * @param {*} props
 * @returns
 */
function body(props) {
  const { getFieldDecorator } = props.form

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [dataSource, setDataSource] = useState({ records: [] })

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    getList({ pageNum: 1, pageSize: 9 })
  }, [])

  function getList(params) {
    // 网路请求
    request({ ...apis.building.getList, params: { ...params } }).then(res => {
      setDataSource(res)
    }).catch(err => {
      // eslint-disable-next-line no-unused-expressions
      <Alert
        style={{
          marginBottom: 24,
        }}
        message={err}
        type="error"
        showIcon
      />
    })
  }

  // 提交事件
  function handleSubmit(e) {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        // eslint-disable-next-line no-console
        console.log('提交数据: ', values)
        const { startDate } = values
        getList({ pageNum: 1, pageSize: 9, ...values })
      }
    });
  }

  // Change 事件
  function handleSelectChange(e) {
    // eslint-disable-next-line no-console
    console.log(e)
  }

  // 分页
  function onChange(pageNumber) {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    getList({ pageNum: pageNumber, pageSize: 9 })
  }

  function getDate(value, dateString) {
    // moment(value).format('YYYY-MM-DD HH:mm:ss')
    console.log(value, dateString)
  }


  function toAdd() {
    router.push({ pathname: '/building/list/add' })
  }

  return (
    <>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
        <Form.Item>
          {getFieldDecorator('code')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="楼盘编号"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('name')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              type="password"
              placeholder="楼盘名称"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('startDate')(
            <DatePicker placeholder="开盘时间" format="YYYY-MM-DD" onChange={getDate} />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('buildingStatus')(
            <Select style={{ width: '180px' }} placeholder="楼盘状态" onChange={handleSelectChange}>
              <Option value="1">发布</Option>
              <Option value="0">未发布</Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('marketStatus')(
            <Select style={{ width: '180px' }} placeholder="销售状态" onChange={handleSelectChange}>
              <Option value="1">已销售</Option>
              <Option value="0">未销售</Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('cityId')(
            <Select style={{ width: '180px' }} placeholder="城市" onChange={handleSelectChange}>
              <Option value="male">male</Option>
              <Option value="female">female</Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('isMain')(
            <Select style={{ width: '180px' }} placeholder="首页推荐" onChange={handleSelectChange}>
              <Option value="1">首页推荐</Option>
              <Option value="0">首页未推荐</Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
      </Form>

      <AuthButton name="building.add" noRight={null}>
        <Button type="danger" className={Styles.addButton} onClick={() => toAdd()}>
          新增楼盘
        </Button>
      </AuthButton>

      {/* 卡片内容，显示楼盘项目  */}
      <Row style={{ padding: ' 0 10px' }}>
        {
          dataSource.records.map((item, _) => (
            <Col span={8}>
              <CartBody data={item} key={item.buildingId} onSuccess={getList} />
            </Col>
          ))
        }
      </Row>
      {/* 分页 */}
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={dataSource.total} onChange={onChange} />
      </div>
    </>
  );
}
const WrappedBody = Form.create({ name: 'body' })(body);

export default WrappedBody
