import React, { useState, useEffect } from 'react';
import { Form, Icon, Input, Button, DatePicker, Select, Modal, message, Card, Row, Col, Pagination, Alert } from 'antd';
import moment from 'moment';
import router from 'umi/router';
import request from '../../../utils/request';
import apis from '../../../services/apis';
import Styles from './style.less';
import NewsTypeSelect from '../../../components/SelectButton/NewTypeSelect'
import BuildSelect from '../../../components/SelectButton/BuildSelect'
import SelectCity from '../../../components/SelectButton/CitySelect'

import AuthButton from '@/components/AuthButton';


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

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

/**
 *
 *
 * @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: 6 })
  }, [])

  function getList(params) {
    // 网路请求
    request({ ...apis.news.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) {
        console.log('提交数据: ', values)
        const { startDate } = values
        getList({ pageNum: 1, pageSize: 6, ...values })
      }
    });
  }

  // 跳转到编辑资讯列表
  const toEditList = (id) => () => {
    router.push({
      pathname: '/news/list/editNewsList',
      query: {
        id
      },
    });
  }



  /**
   *卡片
   *
   * @returns
   */
  function CartBody(props) {
    const { data } = props
    console.log(data);
    const cancelPage = () => {
      router.push({
        pathname: '/news/list/NewsList',
      });
    }

    //删除资讯
    const changeNewsListStatus = (newsId) => () => {
      Modal.confirm({
        title: '确认删除该资讯?',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          request({ ...apis.news.delete, urlData: { id: newsId },}).then((data) => {
            message.info('操作成功!')
            getList({ pageNum: 1, pageSize: 10 });
          }).catch((err) => {
            console.log(err)
            message.info(err.msg || err.message)
          })
        }
      });
    }

    // 跳转到编辑资讯列表
    const toEditList = (newsId) => () => {
      router.push({
        pathname: '/news/list/editNewsList',
        query: {
          newsId
        },
      });
    }

    function cancelRelease(newsId, newsStatus, buildingId, newsTypeId) {
      console.log("newsId" + newsId + "status" + newsStatus);
      if (newsStatus === 1) {
        Modal.confirm({
          title: '确认取消该资讯?',
          okText: '确认',
          cancelText: '取消',
          onOk() {
            request({ ...apis.news.cancel, data:{"newsStatus": newsStatus, "buildingId": buildingId, "newsTypeId": newsTypeId}, urlData: { id: newsId },}).then((data) => {
              message.info('操作成功!')
              getList({ pageNum: 1, pageSize: 10 });
            }).catch((err) => {
              console.log(err)
              message.info(err.msg || err.message)
            })
          },
          onCancel() {
            console.log('Cancel');
          },
        });
      } else if (newsStatus === 0) {
        Modal.confirm({
          title: '确认发布该资讯?',
          okText: '确认',
          cancelText: '取消',
          onOk() {
            request({ ...apis.news.cancel, data:{"newsStatus": newsStatus, "buildingId": buildingId, "newsTypeId": newsTypeId}, urlData: { id: newsId },}).then((data) => {
              message.info('操作成功!')
              getList({ pageNum: 1, pageSize: 10 });
            }).catch((err) => {
              console.log(err)
              message.info(err.msg || err.message)
            })
          },
          onCancel() {
            console.log('Cancel');
          },
        });
      }
    }

    return (
      <Card
        hoverable
        style={{ height: '255px', minWidth: '640px', borderRadius: '12px', margin: '10px', boxShadow: '0px 0px 16px 2px rgba(0,0,0,0.12)', position: 'relative' }}
        cover={<img alt="example" src={data.newsImg} style={{ borderRadius: '12px 0 0 12px', width: '260px', height: '253px' }}></img>}
        bodyStyle={{ padding: '10px 20px' }}
      >
        <AuthButton name="admin.taNews.id.put" noRight={null}>
          <span style={{ position: 'absolute', right: '20px', top: '20px', fontSize: ' 0.11rem', color: '#FF7E48' }} onClick={toEditList(data.newsId)}>
            编辑
                  <Icon type="form" style={{ color: '#C0C4CC', marginLeft: '10px' }} />
          </span>
          {data.newsStatus === 0 ?
            <span style={{ position: 'absolute', left: '280px', bottom: ' 0.11rem', fontSize: ' 0.11rem', color: '#FF7E48',zIndex:1 }} onClick={cancelRelease.bind(this, data.newsId, 1, data.buildingId, data.newsType.newsTypeId)}>
              取消发布
                <Icon type="close-circle" style={{ color: '#C0C4CC', marginLeft: '8px' }} />
            </span> :
            <span style={{ position: 'absolute', left: '280px', bottom: ' 0.11rem', fontSize: ' 0.11rem', color: '#FF7E48',zIndex:1 }} onClick={cancelRelease.bind(this, data.newsId, 0, data.buildingId, data.newsType.newsTypeId)}>
              发布
                <Icon type="form" style={{ color: '#C0C4CC', marginLeft: '8px' }} />
            </span>
          }
        </AuthButton>
        <AuthButton name="admin.taNews.id.delete" noRight={null}>
            <span style={{ position: 'absolute', right: '20px', bottom: ' 0.11rem', fontSize: ' 0.11rem', color: '#FF7E48' }} onClick={changeNewsListStatus(data.newsId)}>
                  删除
                <Icon type="rest" style={{ color: '#C0C4CC', marginLeft: '8px' }} />
            </span>
        </AuthButton>
        <div style={{ position: 'absolute', left: '260px', top: '0px', padding: '20px' }}>
          <p style={{
            fontSize: ' 0.11rem', color: '#333', fontWeight: '600', marginBottom: '10px', overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            width: '300px',
          }}>{data.newsName}</p>
          <p style={{ fontSize: ' 0.11rem', color: '#555', marginBottom: '8px',display:'flex' }}>
            <span style={{ display: 'inline-block', width: '180px',overflow: 'hidden',textOverflow: 'ellipsis',whiteSpace: 'nowrap' }}>资讯类型:{data.newsType.newsTypeName}</span>
            <span>状态:{data.newsStatus == 0 ? "已发布" : "未发布"}</span>
          </p>

          <p style={{ fontSize: ' 0.11rem', color: '#555', marginBottom: '8px' }}>
            <span style={{ display: 'inline-block', width: '180px',overflow: 'hidden',textOverflow: 'ellipsis',whiteSpace: 'nowrap' }}>阅读数量:{data.pvNum}</span>
            <span>转发数量:{data.shareNum}</span>
          </p>

          <p style={{ fontSize: ' 0.11rem', color: '#555', marginBottom: '8px' }}>
            <span style={{ display: 'inline-block', width: '180px',overflow: 'hidden',textOverflow: 'ellipsis',whiteSpace: 'nowrap' }}>点赞数量:{data.favorNum}</span>
            <span>收藏数量:{data.saveNum}</span>
          </p>

          <p style={{ fontSize: ' 0.11rem', color: '#999', marginBottom: '8px' }}>发布时间:{data.createDate}</p>
        </div>
      </Card>
    )
  }


  // 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: 6 })
  }

   //重置搜索
   function handleReset() {
    props.form.resetFields();
  }
  
  function getDate(value, dateString) {
    // moment(value).format('YYYY-MM-DD HH:mm:ss')
    console.log(value, dateString)
  }

  return (
    <>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>

        <Form.Item>
          {getFieldDecorator('cityId')(
            <SelectCity />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('buildingId')(
            <BuildSelect />,
          )}
        </Form.Item>
        {/* <Form.Item>
          {getFieldDecorator('title')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="请输入标题"
            />,
          )}
        </Form.Item> */}
        <Form.Item>
          {getFieldDecorator('newsTypeId')(
            <NewsTypeSelect />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('newsStatus')(
            <Select style={{ width: '180px' }} placeholder="状态">
              <Option value="0">已发布</Option>
              <Option value="1">未发布</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.taNews.post" noRight={null}>
        <Button type="danger" style={{ padding: '0 40px', margin: '20px 0' }} onClick={toEditList()}>
          新增
        </Button>
      </AuthButton>

      {/* 卡片内容,显示楼盘项目  */}
      <Row style={{ padding: ' 0 10px' }}>
        {
          dataSource.records.map((item, index) => (
            <Col span={12}>
              <CartBody data={item} key={item.buildingId} />
            </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