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 captions from '../components/captions';
import inlineCode from '../components/inlineCode';
import validate from '../components/validate';
import codeValue from '../components/code';
import copy from '../components/copy';
import exec from '../components/exec';
import heardTitle from '../components/heardTitle';
import videoActive from '../components/videoActive';
import a from '../components/a';

const components: any = {
  d,
  t,
  i,
  captions,
  inlineCode,
  validate,
  videoActive,
  codeValue,
  copy,
  exec,
  heardTitle,
  a
};

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

const plugin = (): any => {
  return (tree: any) => {


    visit(tree, (node: any, _index: any, _parent: any) => {

      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,
          };
          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.properties.className = 'tag-d-video-text'
        node.value = undefined;
        node.children = node.children || [];
        node.data = {
          hName: node.properties?.tag,
          hProperties: node.properties,

        }
      }
      // if (node.type === 'heading' && node.depth === 2) {
      //   node.children = node.children || [];
      //   node.properties = {
      //     className: 'heardVideoText'
      //   }
      //   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',
          title: node?.title
        }
        node.children = node.children || [];
        node.data = {
          hName: 'a',
          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()
            }
            node.data = {
              hName: 'videoActive',
              hProperties: item,
            };
          } else {
            node.data = {
              hName: 'videoActive',
              hProperties: node.properties,
            };
          }
        } 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
          }
          node.data = {
            hName: 'copy',
            hProperties: node.properties
          };
        } else if (node.properties?.ext?.includes('exec')) {
          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: 'exec',
            hProperties: node.properties
          };
        } else {
          node.data = {
            hName: 'codeValue',
            hProperties: node.properties
          };
        }
      }
      if (node.type === 'image') {
        node.properties = {
          className: 'imgWidth'
        }
        node.children = node?.children || [];
        node.data = {
          hName: 'img',
          hProperties: node?.properties,
        };
      }
      if (node.type === 'section') {
        node?.children[0]?.children?.forEach((nodeItem: any, nodeIndex: number) => {
          if (nodeItem.type === 'captions') {
            if (!nodeItem?.value.endsWith(',') && nodeIndex !== node?.children.length - 1 && nodeItem?.value) {
              nodeItem.value = nodeItem?.value + ','
            }
          }
        })
        for (let i = node?.children[0]?.children?.length - 1; i > -1; i--) {
          if (node?.children[0]?.children[i]?.value && node?.children[0]?.children[i]?.type === 'captions') {
            if (!node?.children[0]?.children[i]?.value.endsWith('。') && node?.children[0]?.children[i]?.value.endsWith(',')) {
              let str = node?.children[0]?.children[i]?.value.slice(0, -1)
              node.children[0].children[i].value = str + '。'
            } else if (!node?.children[0]?.children[i]?.value.endsWith('。') && !node?.children[0]?.children[i]?.value.endsWith(',')) {
              node.children[0].children[i].value = node?.children[0]?.children[i]?.value + '。'
            }
            break
          }
        }
        node.children = node.children || [];
        const classValue = {
          className: 'subtitleList'
        }

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

const Transformer = unified()
  .use(plugin)
  .use(rehype, { allowDangerousHtml: true })
  .use(react, {
    createElement: React.createElement,
    components: components,
  });

export default Transformer;
