import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Form, Pagination, Card, Button, Icon, Tooltip, message, notification, Modal, Table, Select, Input, DatePicker, Row, Col } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import className from 'classnames';
import Cell from '../../../components/Cell';
import styles from './style.less';
import { fetch, apis } from '../../../utils/request';
import request from '../../../utils/request';
import AuthButton from '@/components/AuthButton';
import H5Card from './components/H5Card';

const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

function header(props) {
  // 获取初始化数据
  const [data, setData] = useState({})

  useEffect(() => {
    getList({ pageNum: 1, pageSize: 12 });
  }, [])

  // 查询列表
  const getList = (params) => {
    request({ ...apis.sample.h5list, params: { ...params } }).then((data) => {
      console.log(data)
      setData(data)
    })
  }


  // 提交事件
  const handleSubmit = (e, props) => {
    e.preventDefault();
    e.stopPropagation();
    props.form.validateFields((err, values) => {
      if (!err) {
        let { createDate, ...submitValue } = values
        if (null != createDate && createDate.length > 0) {
          const [startCreateDate, endCreateDate] = createDate
          submitValue.startCreateDate = moment(startCreateDate).format('YYYY-MM-DD');
          submitValue.endCreateDate = moment(endCreateDate).format('YYYY-MM-DD');
        } else {
          submitValue.startCreateDate = null
          submitValue.endCreateDate = null
        }
        getList({ pageNum: 1, pageSize: 12, ...submitValue })
      }
    });
  }

  const changePageNum = (pageNumber) => {
    let { createDate, ...submitValue } = props.form.getFieldsValue()
    if (null != createDate && createDate.length > 0) {
      const [startCreateDate, endCreateDate] = createDate
      submitValue.startCreateDate = moment(startCreateDate).format('YYYY-MM-DD');
      submitValue.endCreateDate = moment(endCreateDate).format('YYYY-MM-DD');
    } else {
      submitValue.startCreateDate = null
      submitValue.endCreateDate = null
    }
    getList({ pageNum: pageNumber, pageSize: 12, ...submitValue })
  }


  // 跳转到编辑资讯
  const toEditH5 = (id) => () => {
    router.push({
      pathname: '/sample/h5/edit',
      query: {
        id
      },
    });
  }


  const changeNewsStatus = (row, newsId) => () => {
    const title = row.status === 0 ? '确定启用吗' : '停用后，此账号将无法登录渠道代理商后台'
    Modal.confirm({
      title: title,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        if (row.status === 0) {
          request({ ...apis.channel.put, urlData: { id: newsId }, data: { ...row, status: 1 } }).then((data) => {
            message.info('操作成功！')
            getList({ pageNum: 1, pageSize: 12 });
          }).catch((err) => {
            console.log(err)
            message.info(err.msg || err.message)
          })
        } else {
          request({ ...apis.channel.put, urlData: { id: newsId }, data: { ...row, status: 0 } }).then((data) => {
            message.info('操作成功！')
            getList({ pageNum: 1, pageSize: 12 });
          }).catch((err) => {
            console.log(err)
            message.info(err.msg || err.message)
          })
        }

      }
    });
  }

  function handleReset() {
    props.form.resetFields();
    getList({ pageNum: 1, pageSize: 12 })
  }

  const { getFieldDecorator } = props.form
  return (

    <>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
        <Form.Item>
          {getFieldDecorator('sampleName')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="样例名"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('status')(
            <Select style={{ width: '180px' }} placeholder="发布状态">
              <Select.Option value="1">是</Select.Option>
              <Select.Option value="0">否</Select.Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
          <span style={{ marginRight: '10px' }}>新增时间段：</span>
          {getFieldDecorator('createDate')(
            <RangePicker placeholder={['开始时间', '结束时间']} />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('tag')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="标签"
            />,
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className={styles.searchBtn}>
            搜索
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
          </Button>
        </Form.Item>
      </Form>

      <Button type="danger" className={styles.addBtn} onClick={toEditH5()}>新增</Button>
      <Row>
        {(data.records || []).map((x, index) => (
          <Col key={index} span={6}>
            <H5Card h5Data={x} onChange={handleReset} />
          </Col>
        ))}
      </Row>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={changePageNum} current={data.current} />
      </div>
    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader