import { ExclamationCircleOutlined, TagOutlined } from '@ant-design/icons';
import { List, Modal, Typography, Popconfirm, Row, Col, Popover, Button } from 'antd';
import { usePageInfoVersionList } from 'editorSrc/api/pageInfoVersionList';
import React, { useEffect } from 'react';
import styled from 'styled-components';
import { history } from 'umi';

interface IVersionListProps {}

const VersionList: React.FC<IVersionListProps> = (props) => {
  const { data } = usePageInfoVersionList();

  useEffect(() => {
    /**
     * 修改URL参数，跳转版本后，被加入history，导致goback 无法回到装饰首页
     * 监听 goback ,直接跳回装饰首页
     */
    window.onpopstate = function (event) {
      // alert();
      const from = history.location.query?.from as string;
      if (from) {
        history.push(from);
      }
    };
  }, []);

  const content = (
    <Box>
      <List
        size="small"
        dataSource={data?.items}
        renderItem={(item) => {
          const id = item?._id.slice(13)
          return (
            <List.Item>
              <Row style={{ width: '100%' }}>
                <Col span={8}>{id}</Col>
                <Col span={10}>{`${item?.created_at}`}</Col>
                <Col span={6}>
                  <Popconfirm
                    title="当前页面会替换为历史版本，是否继续?"
                    onConfirm={() => {
                      history.push({
                        pathname: history.location.pathname,
                        query: {
                          ...history.location.query,
                          cacheVersion: item._id,
                        },
                      });
                    }}
                  >
                    <Typography.Link>还原到该版本</Typography.Link>
                  </Popconfirm>
                </Col>
              </Row>
            </List.Item>
          );
        }}
      />
    </Box>
  );

  return (
    <Popover
      placement="bottom"
      title={`版本记录(${data?.items?.length || 0}/20)`}
      content={content}
      trigger="click"
    >
      <Button type="primary" ghost style={{ marginRight: '12px' }}>
        <TagOutlined />
        版本记录
      </Button>
    </Popover>
  );
};

const Box = styled.div`
  /* padding: 0 32px; */
  height: 200px;
  width: 380px;
  overflow-y: scroll;
`;

export default VersionList;
