import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Form, Input, Button, Icon, Select, message, Table, Divider, Tag, Pagination, Modal, Breadcrumb } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import styles from './style.less';
import { fetch, apis } from '../../utils/request';
import request from '../../utils/request';
import AuthButton from '@/components/AuthButton';
import Navigate from '@/components/Navigate';

function header(props) {
    
    const [taNoticeList, setTaNoticeList] = useState([])
    const [ data, setData ] = useState({})

    useEffect(() => {
        getList({ pageNum: 1, pageSize: 10 });
    }, [])
    // 查询列表

    const getList = params => {
        request({ ...apis.officenews.list, params: { ...params } }).then(data => {
            setData(data)
        })
    }

    const toEditResource = (id) => () => {
        router.push({
            pathname: '/officenews/edit',
              query: {
                id
              },
        });
    }

    const publishNew = (row) => () => {
        row.status = row.status === 1 ? 0 : 1
        editNewsById(row)
    }

    const topNew = (row) => () => {
        row.weight = row.weight === 1 ? 0 : 1
        editNewsById(row)
    }

    const deleteRow = (row) => () =>{
        row.status = -1
        editNewsById(row)
    }

    //编辑资讯
    const editNewsById = values => {
        request({ ...apis.officenews.update, urlData: { id: values.newsId }, data: { ...values }}).then((data) => {
            getList({ pageNum: 1, pageSize: 10 });
          }).catch((err) => {
            message.error(err.msg || err.message)
          })
    }

    const handleSubmit = (e, props) => {
        e.preventDefault();
        getList({ pageNum: 1, pageSize: 10, ...props.form.getFieldsValue() });
    }

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

    const toDelBatch = rowData => () => {
        console.log(taNoticeList, 'taNoticeList')
        if (taNoticeList.length < 1) {
            message.error('请至少选择一条数据')
            return
        }

        Modal.confirm({
            title: '确认将所选数据删除？',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                request({ ...apis.openScreen.delete, data: taNoticeList, }).then((data) => {
                  message.info("操作成功")
                  getList({ pageNum: 1, pageSize: 10 });
                  setTaNoticeList([])
                }).catch((err) => {
                })
            },
        });
    }

    const changePageNum = pageNumber => {
        getList({ pageNum: pageNumber, pageSize: 10, ...props.form.getFieldsValue() })
    }


    const columns = [
        {
            title: '资讯主图',
            dataIndex: 'thumb',
            key: 'thumb',
            align: 'center',
            render: (text, record) => <img style={{width:'140px',height:'92px'}} src={record.thumb} className={styles.touxiang} />,
        },
        {
            title: '资讯标题',
            dataIndex: 'title',
            key: 'title',
            align: 'center',
            render:  (x, row) => <Navigate to={`/officenews/detail?id=${row.newsId}`}>{row.title}</Navigate>,
        },
        {
            title: '发布状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
            render: (x, row) => <><span>{row.status === 1 ? '是' :'否'}</span></>
        },
        {
            title: '创建时间',
            dataIndex: 'createDate',
            key: 'createDate',
            align: 'center',
            render: (x, row) => <><span>{row.createDate?`${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}`:''}</span></>,
        },
        {
            title: '操作',
            dataIndex: 'handle',
            key: 'handle',
            align: 'center',
            render: (x, row) => (
                <>
                    <span style={{ color: '#FF925C', cursor: 'pointer' }} onClick={publishNew(row)}>
                        {row.status === 1 ? '取消发布' :'发布'}<Icon type="form" className={styles.edit} />
                    </span>
                    <span style={{ color: '#FF925C', cursor: 'pointer', marginLeft: '20px' }} onClick={toEditResource(row.newsId)}>
                        编辑<Icon type="form" className={styles.edit} />
                    </span>
                    <span style={{ color: '#FF925C', cursor: 'pointer', marginLeft: '20px' }} onClick={deleteRow(row)}>
                        删除<Icon type="form" className={styles.edit} />
                    </span>
                    <span style={{ color: '#FF925C', cursor: 'pointer', marginLeft: '20px' }} onClick={topNew(row)}>
                        {row.weight === 1 ? '取消置顶' :'置顶'}<Icon type="form" className={styles.edit} />
                    </span>
                </>
            ),
        },
    ];

    const { getFieldDecorator } = props.form

    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log('selectedRowKeys:', selectedRowKeys, 'selectedRows: ', selectedRows);
          setTaNoticeList(selectedRows)
        },
      };
 
    return (

        <>
            <div>
                <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
                    <Form.Item>
                        {getFieldDecorator('title')(
                            <Input
                                prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                placeholder="标题名称"
                            />,
                        )}
                    </Form.Item>
                    <Form.Item>
                        {getFieldDecorator('status')(

                            <Select style={{ width: '180px' }} placeholder="发布状态">
                                 <Option value="">全部</Option>
                                <Option value="0">已发布</Option>
                                <Option value="1">未发布</Option>

                            </Select>,

                        )}
                    </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={toEditResource()}>新增</Button>

                <Table id='noticeTable' rowKey={r => r.newsId} dataSource={data.records} columns={columns} pagination={false} />

                <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
                    <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={e => changePageNum(e)} current={data.current} />
                </div>
            </div>
        </>
    )
}

const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader