import React, { useState, useEffect } from 'react';
import { Form, Icon, Input, Button, DatePicker, Select, Card, Row, message, 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 Prompt from 'umi/prompt';
import AuthButton from '@/components/AuthButton';
import EditIcon from '@/components/EditIcon';
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)
          message.info(err.msg || 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();
      },
    });
  }
  // src={((data.buildingImg && data.buildingImg[0]) || {}).url}background: `url(${item.caseCoverImg})` style={{ background: `url(((data.buildingImg && data.buildingImg[0]) || {}).url)` }}
  const { buildingImg } = data
  console.log("buildingImg1: ", data.buildingImg)
  return (
    <Card
      hoverable
      style={{ minWidth: '330px', borderRadius: '12px', margin: '10px', boxShadow: '0px 0px 16px 2px rgba(0,0,0,0.12)' }}
    // cover={}
    // bodyStyle={{ padding: '10px 20px' }}
    >
      {/* 因为 background 方式设置图片背景，如果 图片url 存在空格或者其他特殊字符，导致显示不出来，需要进行 encodeURI(xxx) 转码 */}
      <span className={Styles.recommderTag}>{data.isMain === 1 ? '首页推荐' : ''}</span>
      <img className={Styles.cover} style={{ backgroundImage: `url('${encodeURI(((data.buildingListImg && data.buildingListImg[0]) || {}).url)}')` }}   ></img>
      <div style={{ padding: '10px 20px' }}>
        <p className={Styles.cardText}>
          <span className={Styles.title}>楼盘编号</span>
          <span style={{ textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden' }}>：{data.code}</span>
          <AuthButton name="admin.building.update" noRight={null}>
            <span className={Styles.ediText} onClick={() => toEdi(data)}>
              <EditIcon text="编辑" type="edit"></EditIcon>
            </span>
          </AuthButton>
        </p>
        <p className={Styles.cardText}>
          <span className={Styles.title}>楼盘名称</span>
          <span style={{ textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden' }}>：{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>
          </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: '20px 0', position: 'relative', fontSize: '0.106rem' }}>
          <AuthButton name="admin.building.public" noRight={null}>
            <span style={{ color: '#FF4A4A' }} onClick={() => pulicAndUnPulic(data)}>
              {/* 已发布的时候，需要显示取消发布的字样 */}
              {data.status === 1 ? <EditIcon text="取消发布" type="cancel"></EditIcon> : <EditIcon text="发布" type="publish"></EditIcon>}
            </span>
          </AuthButton>
          <AuthButton name="admin.building.delete" noRight={null}>
            <span style={{
              color: '#FF4A4A', position: 'absolute', right: '0', bottom: '0'
            }} onClick={() => deleteBuilding(data)}>
              <EditIcon text="删除" color='#FF4A4A' type="delete"></EditIcon>
            </span>
          </AuthButton>
        </p>
      </div>
    </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: [], size: 0 })

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    if (localStorage.getItem("pageParams")) {

      // const { getFieldDecorator } = JSON.parse(localStorage.getItem("pageParams"))
      const localStorageValue = JSON.parse(localStorage.getItem("pageParams"))
      localStorageValue.startDate = localStorageValue.startDate ? moment(localStorageValue.startDate) : ''
      props.form.setFieldsValue(localStorageValue);

      getList({ pageNum: 1, pageSize: 9, ...JSON.parse(localStorage.getItem("pageParams")) })
    } else {
      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`
        }
        localStorage.setItem("pageParams", JSON.stringify({ pageNum: 1, pageSize: 9, ...values }));
        getList({ pageNum: 1, pageSize: 9, ...values })
      }
    });
  }

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

  // 分页
  function onChange(pageNumber) {
    localStorage.setItem("pageParams", JSON.stringify({ pageNum: pageNumber, pageSize: 9, ...props.form.getFieldsValue() }));
    // 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();
    localStorage.setItem("pageParams", JSON.stringify({ pageNum: 1, pageSize: 9 }));
    getList({ pageNum: 1, pageSize: 9 })
  }

  function onSuccess() {
    if (localStorage.getItem("pageParams")) {
      getList(JSON.parse(localStorage.getItem("pageParams")))
    } else {
      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" 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={() => onSuccess()} />
            </Col>
          ))
        }
      </Row>
      {/* 分页 */}
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper current={dataSource.current} total={dataSource.total} onChange={onChange} pageSize={dataSource.size} />
      </div>
      <Prompt message={location =>
        location.pathname.startsWith("/building/list")
          ? true
          : localStorage.removeItem("pageParams")} />
    </>
  );
}
const WrappedBody = Form.create({ name: 'body' })(body);

export default WrappedBody
