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';
import SelectCity from '../../../components/SelectButton/CitySelect'


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 modal = Modal.confirm();
    modal.update({
      content: '项目会被删除，小程序端和后台都无法再看到',
      okText: '确认',
      cancelText: '关闭',
      onOk: () => {
        request({ ...apis.building.deleteBuilding, urlData: { id: record.buildingId } }).then(() => {
          openNotificationWithIcon('success', '操作成功')
          props.onSuccess()
        }).catch(err => {
          // openNotificationWithIcon('error', err.message)
        })

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

  const { buildingImg } = data
  console.log("buildingImg: ", data.buildingImg, "data: ", data)
  return (
    <Card
      hoverable
      style={{ minWidth: '330px', borderRadius: '12px', margin: '10px', boxShadow: '0px 0px 16px 2px rgba(0,0,0,0.12)' }}
      cover={<img alt="example" src={((data.buildingImg && data.buildingImg[0]) || {}).url} 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>
        <AuthButton name="admin.building.update.put" noRight={null}>
          <span className={Styles.ediText} onClick={() => toEdi(data)}>
            编辑
                  <Icon type="form" style={{ color: '#C0C4CC', marginLeft: '10px' }} />
          </span>
        </AuthButton>
      </p>
      <p className={Styles.cardText}>
        <span className={Styles.title}>楼盘名称</span>
        <span >：{data.buildingName || 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 >：{moment(data.createDate).format('YYYY-MM-DD HH:mm:ss')}</span>
      </p>
      <p style={{ margin: '15px 0', position: 'relative', fontSize: '0.106rem' }}>
      <AuthButton name="admin.building.update.status.put" noRight={null}>
        <span style={{ color: '#FF4A4A' }} onClick={() => pulicAndUnPulic(data)}>
          {/* 已发布的时候，需要显示取消发布的字样 */}
          {data.status === 1 ? '取消发布' : '发布'}
          <Icon type={data.status === 1 ? 'close-circle' : 'form'} style={{ color: '#C0C4CC', marginLeft: '8px' }} />
        </span>
      </AuthButton>
      <AuthButton name="admin.building.delete.id.delete" noRight={null}>
        <span style={{
          color: '#FF4A4A', position: 'absolute', right: '0',
        }} onClick={() => deleteBuilding(data)}>
          删除
                <Icon type="rest" style={{ color: '#C0C4CC', marginLeft: '8px' }} />
        </span>
      </AuthButton>
      </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)
      console.log("res:",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
        if (values.startDate !== undefined) {
         
          values.startDate = `${moment(startDate).format('YYYY-MM-DDT00:00:00.000')}Z`
        }
        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, ...props.form.getFieldsValue() })
  }

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


  function toAdd() {
    // 判断楼盘是否最可以添加
    request({ ...apis.building.verifyMax}).then(res => {
      router.push({ pathname: '/building/list/add' })
    }).catch(err => {
      // eslint-disable-next-line no-unused-expressions
      <Alert
        style={{
          marginBottom: 24,
        }}
        message={err}
        type="error"
        showIcon
      />
      return
    })
  }

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


  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)' }} />}
              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="2">未发布</Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('marketStatus')(
            <Select style={{ width: '180px' }} placeholder="销售状态" onChange={handleSelectChange}>
                <Option value="待定">待定</Option>
                <Option value="在售">在售</Option>
                <Option value="售完">售完</Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('cityId')(
             <SelectCity />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('isMain')(
            <Select style={{ width: '180px' }} placeholder="首页推荐" onChange={handleSelectChange}>
              <Option value="1">首页推荐</Option>
              <Option value="2">首页未推荐</Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
        </Form.Item>
      </Form>

      <AuthButton name="admin.building.add.post" 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} pageSize={dataSource.size} />
      </div>
    </>
  );
}
const WrappedBody = Form.create({ name: 'body' })(body);

export default WrappedBody
