import React, { useEffect, useMemo, useRef } from 'react';
import { connect,history } from 'umi';
import moment from 'moment';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { queryTable } from '@/utils/request';
import {Space} from 'antd'

const PostData = (props) => {
  const tableRef = useRef()

  const changeQueryParam = (params) => {
    const dt = params.date
    const startDate = dt ? dt[0] : undefined
    const endDate = dt ? dt[1] : undefined

    return {
      ...params,
      startDate: startDate ? moment(startDate).format('YYYY-MM-DD') : undefined,
      endDate: endDate ? moment(endDate).format('YYYY-MM-DD') : undefined,
      date: undefined,
    }
  }

  const typeDict = useMemo(() => {
    return (props.typeList || []).reduce((acc, item) => {
      return {
        ...acc,
        [item.typeId]: { text: item.name },
      };
    }, {});
  }, [props.typeList]);

  const columns = [
    {
      title: '日期',
      key: 'date',
      hideInTable: true,
      valueType: 'dateRange',
    },
    {
      title: '名称',
      key: 'name',
      hideInTable: true,
    },
    {
      title: '排名',
      key: 'topN',
      hideInSearch: true,
      render: (_, $, index) => index + 1,
    },
    {
      title: '科普知识',
      key: 'postId',
      dataIndex: 'postId',
      hideInSearch: true,
      render: (_, row) => (
        <div>
          <h3>{row.name}</h3>
          <p>
            <small>{`作者: ${row.author}`}</small>
          </p>
          <p>
            <small>{row.isVideo ? '视频' : '图文'}</small>
          </p>
        </div>
      ),
    },
    {
      title: '分类',
      key: 'typeId',
      dataIndex: 'typeId',
      valueType: 'select',
      valueEnum: typeDict,
    },
    {
      title: '阅读人数',
      key: 'uv',
      dataIndex: 'uv',
      hideInSearch: true,
      sorter: true,
      render: (text, row) => (
        <Space size="middle">
          {text?<a onClick={() =>  history.push(`/report/student?postId=${row.postId}`)}>{text}</a>:0}
        </Space>
      ),
    },
    {
      title: '浏览量',
      key: 'pv',
      dataIndex: 'pv',
      hideInSearch: true,
      sorter: true,
    },
    {
      title: '收藏量',
      key: 'savedNum',
      dataIndex: 'savedNum',
      hideInSearch: true,
      sorter: true,
    },
  ];

  useEffect(() => {
    if (!props.typeList || !props.typeList.length) {
      props.dispatch({
        type: 'post/getTypeList',
        payload: { pageSize: 999 },
      });
    }
  }, [props]);

  return (
    <PageContainer>
      <ProTable
        actionRef={tableRef}
        columns={columns}
        request={queryTable('/statis/post-data')}
        rowKey="postId"
        search={{
          labelWidth: '4em',
        }}
        options={false}
        beforeSearchSubmit={changeQueryParam}
      />
    </PageContainer>
  );
};

export default connect((s) => ({
  typeList: s.post.typeList,
}))(PostData);
