import React from 'react';
import { unified } from 'unified';
import rehype from 'remark-rehype';
import react from 'rehype-react';
import { visit } from 'unist-util-visit';
import d from '../components/tag/d';
import t from '../components/tag/t';
import i from '../components/tag/i';
import inlineCode from '../components/inlineCode';

import codeValue from '../components/code';
import copy from '../components/copy';
import exec from '../components/exec';
import heardTitle from '../components/heardTitle';
import active from '../components/active';
import validate from '../components/validate';
import allActive from '../components/allActive';
import link from '../components/link';
import a from '../components/a'
import img from '../components/img'

const components = {
  d,
  t,
  i,
  inlineCode,
  validate,
  allActive,
  copy,
  codeValue,
  exec,
  heardTitle,
  active,
  link,
  a,
  img
};

const TYPES: Array<string> = ['d', 'p', 't', 'i', 'content', 'active'];

const plugin = (): any => {
  return (tree: any) => {
    visit(tree, (node: any, _index: any, _parent: any) => {
      if (node.type !== 'text') {
        const classValue = {
          position: JSON.stringify(node?.position),
          page: node?.page
        }
        node.data = {
          hProperties: classValue,
        };
      }


      if (TYPES.filter(it => it === node.type).length > 0) {
        if (node.type !== 'code') {
          const value = node.value;
          node.value = undefined;
          node.children = node.children || [];
          node.data = {
            hName: node.type,
            hProperties: node.properties,
            ...node.data
          };
          const text = {
            type: 'text',
            value: value,
          };
          node.children.push(text);
        }
      }
      let reg = /[\u4e00-\u9fa5]/g
      if (node.type === 'heading' && node.properties?.tag) {


        if (reg.test(node?.properties?.tag)) {
          node.properties.tag = 'div'
          node.value = undefined;
          node.children = node.children || [];
          node.data = {
            hName: node?.properties?.tag,
            hProperties: node?.properties,
          }
        } else {
          node.value = undefined;
          node.children = node.children || [];
          node.properties.className = 'tag-d-text'
          node.data = {
            hName: node?.properties?.tag,
            hProperties: node?.properties,
          }
        }
      }

      if (node.type === 'heading' && !reg.test(node?.properties?.tag)) {
        node.value = undefined;
        node.children = node.children || [];
        if (!node.properties) {
          node.properties = {
            className: 'otherHeading',
            position: JSON.stringify(node?.position),
            page: node?.page
          }
        }
        node.data = {
          hName: node.properties?.tag,
          hProperties: node.properties,
        }

      }

      // if (node.type === 'heading' && node.depth === 2 && !reg.test(node?.properties?.tag)) {
      //   node.children = node.children || [];
      //   node.properties = {
      //     className: 'heardText',
      //     position: node?.position,
      //     page: node?.page
      //   }
      //   node.data = {
      //     hName: 'heardTitle',
      //     hProperties: node.properties,
      //   }
      // }
      if (node.type === 'inlineCode') {
        node.children = node.children || [];
        let pattern = /'([^']+)'/;   // 匹配以 '[' 开头，以 ']' 结尾的子串
        let result
        if (node.properties?.ext?.match(pattern)?.length > 1) {
          result = node.properties?.ext?.match(pattern)[1];
        }
        if (node.properties?.ext) {
          node.properties.ext = result
        }
        node.data = {
          hName: node.type,
          hProperties: node.properties,

        };
      }
      if (node.type === 'link') {
        node.properties = {
          target: '_blank',
          position: node?.position,
          page: node?.page
        }
        node.children = node.children || [];

        if (/\.pdf$/i.test(node.url)) {
          node.data = {
            hName: 'link',
            hProperties: node.properties,
          };
        } else {
          node.data = {
            hName: 'a',
            hProperties: {
              ...node.properties,
              title: node?.title
            },

          };
        }
      }
      if (node.type === 'image') {
        node.properties = {
          className: 'imgWidth',
          position: node?.position,
          page: node?.page
        }
        node.children = node?.children || [];
        node.data = {
          hName: 'img',
          hProperties: node?.properties,

        };
      }
      if (node.type === 'code') {
        if (node.properties?.ext?.includes('active')) {
          const ext: string = node.properties?.ext
          if (ext?.startsWith('active')) {
            const item = {
              lang: node.lang,
              value: node?.value?.trim(),
              position: node?.position,
              page: node?.page,
              url: node?.properties?.url
            }
            node.data = {
              hName: 'active',
              hProperties: item
            };
          } else {
            node.data = {
              hName: 'active',
              hProperties: node.properties,

            };
          }
        } else if (node.properties?.ext?.includes('copy') && node.properties?.ext?.includes('exec')) {
          const arr = node.properties?.ext?.split(/\s+/);
          // let pattern = /'([^']+)'/;   // 匹配以 '[' 开头，以 ']' 结尾的子串
          let result
          if (arr.length > 1) {
            result = arr[2];
          }
          if (node?.properties?.ext) {
            node.properties.ext = result
          }
          let offset
          if (node?.position?.start?.offset) {
            offset = node?.position?.start?.offset
          }
          const classValue = {
            ext: result,
            id: offset?.toString(),
            position: node?.position,
            page: node?.page
          }
          node.data = {
            hName: 'allActive',
            hProperties: classValue,

          };
        } else if (node.properties?.ext?.includes('copy')) {
          let pattern = /'([^']+)'/;   // 匹配以 '[' 开头，以 ']' 结尾的子串
          let result

          if (node.properties?.ext?.match(pattern)?.length > 1) {
            result = node.properties?.ext?.match(pattern)[1];
          }
          if (node.properties?.ext) {
            node.properties.ext = result
          }
          let offset
          if (node?.position?.start?.offset) {
            offset = node?.position?.start?.offset
          }
          const classValue = {
            className: offset?.toString(),
            position: node?.position,
            page: node?.page
          }
          node.data = {
            hName: 'copy',
            hProperties: classValue,

          };

        } else if (node.properties?.ext?.includes('exec')) {


          const arr = node.properties?.ext?.split(/\s+/);
          // let pattern = /'([^']+)'/;   // 匹配以 '[' 开头，以 ']' 结尾的子串
          let result
          if (arr.length > 1) {
            result = arr[1];
          }
          let offset
          let posiTion

          if (node?.position?.start?.offset) {
            offset = node?.position?.start?.offset
          }
          if (node?.position) {
            posiTion = node?.position
          }
          if (node?.properties?.ext) {
            node.properties.ext = result
          }
          if (node?.properties?.offset) {
            node.properties.offset = offset
          }

          const classValue = {
            ext: result,
            className: offset?.toString(),
            position: posiTion,
            page: node?.page
          }

          node.data = {
            hName: 'exec',
            hProperties: classValue,

          };
        } else if (node.properties?.ext?.includes('validate')) {



          const arr = node.properties?.ext?.split(/\s+/);


          let result
          if (arr.length > 1) {
            result = arr[1];
          }
          let offset
          if (node?.position?.start?.offset) {
            offset = node?.position?.start?.offset
          }
          if (node?.properties?.ext) {
            node.properties.ext = result
          }
          if (node?.properties?.offset) {
            node.properties.offset = offset
          }
          const classValue = {
            ext: result,
            className: offset?.toString(),
            position: node?.position,
            page: node?.page
          }
          node.data = {
            hName: 'validate',
            hProperties: classValue,

          };
        } else {
          const classValue = {
            position: node?.position,
            page: node?.page
          }
          node.data = {
            hName: 'codeValue',
            hProperties: classValue,

          };
        }
      }
      if (node.type === 'section') {


        node.children = node.children || [];
        const classValue = {
          className: 'subtitleList',
          position: node?.position,
          page: node?.page
        }

        node.data = {
          hName: 'div',
          hProperties: classValue,

        };
      }
    });
  };
};

const TextTransformer = unified()
  .use(plugin)
  .use(rehype, { allowDangerousHtml: true })
  .use((): any => {
    return (tree: any) => {
      visit(tree, (node: any, _index: any, _parent: any) => {
        if (node.type === 'text' && _parent?.tagName === 'p' && !/^\s*$/.test(node.value)) {

          _parent.properties = {
            position: JSON.stringify(_parent?.position),
            style: 'white-space: pre-line; line-height: 26px;'
          }
        }
      })
    }
  })
  .use(react, {
    createElement: React.createElement,
    components: components,
  });

export default TextTransformer;
