/* eslint-disable jsx-a11y/media-has-caption */
/* eslint-disable react/no-danger */
import { DownOutlined, HomeOutlined, UpOutlined } from '@ant-design/icons';
import { Affix, BackTop, PageHeader, Input, Space, Descriptions, Upload } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import './index.css';
import { getArticleDetail } from './service';

const Front: React.FC<{}> = (prop: any) => {
  const [title, setTitle] = useState<string>('');
  const [htmlStr, setHtmlStr] = useState<string>('');
  const [item, setItem] = useState<any>({});
  const [param, setParam] = useState<string>('');
  const [fileList, setFileList] = useState<any>();
  const componentRef: any = useRef();
  const [allTextNodes1, setAllTextNodes] = useState<any[]>([]);
  const [ranges1, setRanges1] = useState<any[]>([]);
  const [currentIndex, setCurrentIndex] = useState<number>(0);
  useEffect(() => {
    getArticleDetail({ id: prop.match.params.id }).then((res) => {
      if (res.retcode) {
        setItem(res.data)
        setTitle(res.data.title);
        setHtmlStr(res.data.content);
        let arr: any = [];
        if (res.data.fileUrls) {
          arr = JSON.parse(res.data.fileUrls);
        }
        setFileList(arr)
        const article = document.getElementById("search");
        //@ts-ignore
        const treeWalker = document.createTreeWalker(article, NodeFilter.SHOW_TEXT);
        const allTextNodes = [];
        let currentNode = treeWalker.nextNode();
        while (currentNode) {
          allTextNodes.push(currentNode);
          currentNode = treeWalker.nextNode();
        }
        setAllTextNodes(allTextNodes)
      }
    });
  }, []);

  const getFlatArr = (list: any[]) => {
    return list.reduce((pre, item) => {
      return pre.concat(item)
    }, [])
  }

  return (
    <div style={{ minWidth: 1050 }}>
      <BackTop />
      <Affix offsetTop={0}>
        <div className="site-page-header">
          <PageHeader
            style={{ margin: '0 auto', padding: '10px 0', width: 1000 }}
            backIcon={<HomeOutlined style={{ fontSize: 28, color: '#fff' }} />}
            onBack={() => history.goBack()}
            title={' '}
          />
        </div>
      </Affix>
      <div
        style={{
          margin: '30px auto',
          width: 1000,
          fontSize: 28,
          fontWeight: 'bold',
          textAlign: 'center',
        }}
      >
        {title}
      </div>
      <Affix style={{ margin: '0 auto', width: 'fit-content' }} offsetTop={10}>
        <div>
          <Input
            style={{ width: 482, height: 35, borderRadius: 100, backgroundColor: '#f6f6f6' }}
            suffix={<Space><DownOutlined style={{ fontSize: 18 }} onClick={() => {
              //@ts-ignore
              if (!CSS.highlights) {
                console.log(111)
                return;
              }
              // 清除上个高亮
              //@ts-ignore
              CSS.highlights.clear();
              // 为空判断
              if (!param) {
                return;
              }
              let index = 0;
              const arr = [];
              const arr1 = [];
              let flag = true;
              for (let i = 0; i < ranges1.length; i++) {
                const element = ranges1[i];
                if (element.length && flag && i > currentIndex) {
                  index = i
                  arr.push(element)
                  arr1.push([])
                  setCurrentIndex(i)
                  flag = false
                } else {
                  arr.push([])
                  arr1.push(element)
                }
              }
              if (index == 0) {
                arr[0] = ranges1[0]
                setCurrentIndex(0)
              }
              // 注册高亮
              //@ts-ignore
              const searchResultsHighlight = new Highlight(...arr1.flat());
              //@ts-ignore
              CSS.highlights.set("search-results", searchResultsHighlight);
              //@ts-ignore
              const searchResultsHighlight1 = new Highlight(...arr.flat());
              //@ts-ignore
              CSS.highlights.set("current-search-results", searchResultsHighlight1);
              const range = arr.flat()
              if (range && range.length > 0) {
                range[0].commonAncestorContainer.parentElement.scrollIntoView({
                  block: "center",
                })
              }
            }} /><UpOutlined style={{ fontSize: 18 }} onClick={() => {
              //@ts-ignore
              if (!CSS.highlights) {
                console.log(111)
                return;
              }
              // 清除上个高亮
              //@ts-ignore
              CSS.highlights.clear();
              // 为空判断
              if (!param) {
                return;
              }
              let index = 0;
              const arr = [];
              const arr1 = [];
              let flag = true;
              for (let i = ranges1.length - 1; i >= 0; i--) {
                const element = ranges1[i];
                if (element.length && flag && i < currentIndex) {
                  index = i
                  arr.push(element)
                  arr1.push([])
                  setCurrentIndex(i)
                  flag = false
                } else {
                  arr.push([])
                  arr1.push(element)
                }
              }
              if (index == 0) {
                arr[ranges1.length - 1] = ranges1[ranges1.length - 1]
                setCurrentIndex(ranges1.length - 1)
              }
              // 注册高亮
              //@ts-ignore
              const searchResultsHighlight = new Highlight(...arr1.flat());
              //@ts-ignore
              CSS.highlights.set("search-results", searchResultsHighlight);
              //@ts-ignore
              const searchResultsHighlight1 = new Highlight(...arr.flat());
              //@ts-ignore
              CSS.highlights.set("current-search-results", searchResultsHighlight1);
              const range = arr.flat()
              if (range && range.length > 0) {
                range[0].commonAncestorContainer.parentElement.scrollIntoView({
                  block: "center",
                })
              }
            }} /></Space>}
            onChange={(e: any) => {
              const value = e.currentTarget.value
              setParam(value)
              //@ts-ignore
              if (!CSS.highlights) {
                console.log(111)
                return;
              }
              // 清除上个高亮
              //@ts-ignore
              CSS.highlights.clear();
              setRanges1([])
              // 为空判断
              if (!value) {
                return;
              }
              // 查找所有文本节点是否包含搜索词
              const ranges = allTextNodes1
                .map((el) => {
                  return { el, text: el.textContent.toLowerCase() };
                })
                .map(({ text, el }) => {
                  const indices: any[] = [];
                  let startPos = 0;
                  while (startPos < text.length) {
                    const index = text.indexOf(value, startPos);
                    if (index === -1) break;
                    indices.push(index);
                    startPos = index + value.length;
                  }

                  // 根据搜索词的位置创建选区
                  return indices.map((index) => {
                    const range = new Range();
                    range.setStart(el, index);
                    range.setEnd(el, index + value.length);
                    return range;
                  });
                });
              const newRanges = getFlatArr(ranges).map((e: any) => [e]);
              setRanges1(newRanges)
              
              
              // 创建高亮对象
              const arr = [];
              const arr1 = [];
              let flag = true;
              for (let i = 0; i < newRanges.length; i++) {
                const element = newRanges[i];
                if (element.length && flag) {
                  arr.push(element)
                  arr1.push([])
                  setCurrentIndex(i)
                  flag = false
                } else {
                  arr.push([])
                  arr1.push(element)
                }
              }

              //@ts-ignore
              const searchResultsHighlight1 = new Highlight(...arr.flat());
              //@ts-ignore
              CSS.highlights.set("current-search-results", searchResultsHighlight1);

              const range = arr.flat()
              if (range && range.length > 0) {
                range[0].commonAncestorContainer.parentElement.scrollIntoView({
                  block: "center",
                })
              }
                

              // 注册高亮
              //@ts-ignore
              const searchResultsHighlight = new Highlight(...arr1.flat());
              //@ts-ignore
              CSS.highlights.set("search-results", searchResultsHighlight);
              
            }}
            onPressEnter={(e) => {
              const value = e.currentTarget.value
              //@ts-ignore
              if (!CSS.highlights) {
                console.log(111)
                return;
              }
              // 清除上个高亮
              //@ts-ignore
              CSS.highlights.clear();
              // 为空判断
              if (!value) {
                return;
              }
              let index = 0;
              const arr = [];
              const arr1 = [];
              let flag = true;
              for (let i = 0; i < ranges1.length; i++) {
                const element = ranges1[i];
                if (element.length && flag && i > currentIndex) {
                  index = i
                  arr.push(element)
                  arr1.push([])
                  setCurrentIndex(i)
                  flag = false
                } else {
                  arr.push([])
                  arr1.push(element)
                }
              }
              if (index == 0) {
                arr[0] = ranges1[0]
                setCurrentIndex(0)
              }
              // 注册高亮
              //@ts-ignore
              const searchResultsHighlight = new Highlight(...arr1.flat());
              //@ts-ignore
              CSS.highlights.set("search-results", searchResultsHighlight);
              //@ts-ignore
              const searchResultsHighlight1 = new Highlight(...arr.flat());
              //@ts-ignore
              CSS.highlights.set("current-search-results", searchResultsHighlight1);
              const range = arr.flat()
              if (range && range.length > 0) {
                range[0].commonAncestorContainer.parentElement.scrollIntoView({
                  block: "center",
                })
              }
            }}
            allowClear
          />
        </div>
      </Affix>
      <div
        style={{
          margin: '30px auto',
          width: 1000,
          fontSize: 24
        }}
      >
        <Descriptions title="" bordered>
          <Descriptions.Item label="类型">{item.categoryName}</Descriptions.Item>
          <Descriptions.Item label="级别">{item.levelName}</Descriptions.Item>
          <Descriptions.Item label="文号版本">{item.version}</Descriptions.Item>
          <Descriptions.Item label="实施日期">{item.implementationDate}</Descriptions.Item>
          <Descriptions.Item label="状态" span={2}>{item.currentStatus == 1 ? '现行' : '废止'}</Descriptions.Item>
          <Descriptions.Item label="附件" span={3}>
            <div>
              <Upload
                action="#"
                // listType="picture-card"
                fileList={fileList}
                showUploadList={{showDownloadIcon: true, showRemoveIcon: false}}
              />
            </div>
          </Descriptions.Item>
        </Descriptions>
      </div>
      <div id='search' ref={componentRef}>
        <div style={{ margin: '0 auto', width: 1000 }}>
          <div
            className="inner-html"
            style={{ padding: '0 24px' }}
            dangerouslySetInnerHTML={{ __html: htmlStr }}
          />
        </div>
      </div>
    </div>
  );
};

export default Front;
