import type { DragEndEvent } from '@dnd-kit/core';
import { DndContext, PointerSensor, useSensor } from '@dnd-kit/core';
import {
  arrayMove,
  horizontalListSortingStrategy,
  SortableContext,
  useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Tabs, Table, Tooltip, Empty, Tag, Image, Space, Timeline, Tree } from 'antd';
import { configurationConnect, } from '@/services/SearchVehicle/searchVehicle';
import React, { useState, useRef, useEffect } from 'react';
import './index.less'
const { DirectoryTree } = Tree;

interface DraggableTabPaneProps extends React.HTMLAttributes<HTMLDivElement> {
  'data-node-key': string;
}

const DraggableTabNode = ({ className, ...props }: DraggableTabPaneProps) => {

  const { attributes, listeners, setNodeRef, transform, transition } = useSortable({
    id: props['data-node-key'],
  });

  const style: React.CSSProperties = {
    ...props.style,
    transform: CSS.Transform.toString(transform),
    transition,
    cursor: 'move',
  };

  return React.cloneElement(props.children as React.ReactElement, {
    ref: setNodeRef,
    style,
    ...attributes,
    ...listeners,
  });
};
let columnsDefault = [] as any;


const Contrast: React.FC = (props: any) => {


  const newTabIndex = useRef(0);
  const tabletRef = useRef(null) as any;
  const Contrast = useRef(null) as any;

  const [items, setItems] = useState([]);
  const [options, setOptions] = useState([]);
  const [columns, setcolumns] = useState(columnsDefault);
  const [data, setData] = useState([]);
  const [activeKey, setActiveKey] = useState();
  const [offsetWidth, setOffsetWidth] = useState(0) as any;
  const [translateX, setTranslateX] = useState<any>(0);

  const sensor = useSensor(PointerSensor, { activationConstraint: { distance: 10 } });
  const [pageSize, setPageSize] = useState<any>(10);




  useEffect(() => {
    init() // 初始化
    window.addEventListener('resize', handleResize) // 窗口变化
    return () => {
      window.removeEventListener('resize', handleResize, false)
    }
  }, []);

  // 画面大小变化
  const handleResize = () => {
    let width = Contrast.current.offsetWidth - 160 - 100 - 260 - 68 - 62
    width = props.FunctionTags ? width : width + 100
    setOffsetWidth(width)
  }

  const hasString = (arr: any, target: any, parent: any) => {
    return arr.some((str: any) =>
      str.name === target && str?.category?.parent?.id === parent
    );
  }
  // 提取相同的对象
  const extractObjectsWithSameName = (arr: any) => {
    let arrObj = []
    let otherObj = []

    for (let index = 0; index < arr.length; index++) {
      const element = arr[index];
      if (hasString(arrObj, element.name, element?.category?.parent?.id)) {
        otherObj.push(element)
      } else {
        arrObj.push(element)
      }
    }
    for (let index = 0; index < arrObj.length; index++) {
      const element1 = arrObj[index];
      element1[`note_${element1?.vehicleModel?.name}`] = element1?.note
      element1[`image_${element1?.vehicleModel?.name}`] = element1?.image


      for (let index = 0; index < otherObj.length; index++) {
        const element2 = otherObj[index];

        if (element2.name === element1.name) {
          element1[`note_${element2?.vehicleModel?.name}`] = element2.note
          element1[`image_${element2?.vehicleModel?.name}`] = element2.image

        }
      }
    }

    return arrObj
  }

  useEffect(() => {
    if (props.data) {
      let listData = props.data
      let key = Object.keys(listData)
      let itemData = [] as any
      let colData = [] as any
      let rowData = [] as any
      let width = Contrast.current.offsetWidth - 160 - 100 - 260 - 68 - 62
      width = props.FunctionTags ? width : width + 100

      setOffsetWidth(width)

      for (let index = 0; index < key.length; index++) {
        itemData.push({
          key: index + 1,
          label: key[index],
          option: listData[key[index]]
        })

        colData.push({
          align: 'center',
          title: '功能定义',
          dataIndex: `note_${key[index]}`,
          width: width / items.length < 300 ? 300 : width / items.length,
          key: `note_${key[index]}`,
          className: 'nodeTd scrollbarNone',
          ellipsis: {
            showTitle: false,
          },
          render: (address: any, item: any) => (
            <span style={{ whiteSpace: 'pre-line' }}>{address}</span>
          ),
        })
        rowData = [...rowData, ...listData[key[index]]?.function]
      }
      console.log(rowData);
      let newdata = extractObjectsWithSameName(rowData) as any
      console.log(newdata);

      setItems(itemData)
      setcolumns([...columnsDefault, ...colData])
      setData(newdata)
    }
  }, [props.data]);


  const changeColumns = () => {
    let colData = [] as any
    let width = Contrast.current.offsetWidth - 160 - 100 - 260 - 68 - 62
    width = props.FunctionTags ? width : width + 100

    setOffsetWidth(width)


    for (let index = 0; index < items.length; index++) {
      const element = items[index] as any;
      colData.push({
        align: 'center',
        title: '功能定义',
        dataIndex: `note_${element.label}`,
        width: width / items.length < 300 ? 300 : width / items.length,
        key: `note_${element.label}`,
        className: 'nodeTd scrollbarNone',
        ellipsis: {
          showTitle: false,
        },
        render: (address: any, item: any) => (
          <>
            <span style={{ whiteSpace: 'pre-line' }}>{address}   <span>
              {item[`image_${element.label}`] ? <Space align="end"> <Image
                width={100}
                src={item[`image_${element.label}`]}
              /></Space> : ''}
            </span></span>
          </>
        ),
      })
    }
    setcolumns([...columnsDefault, ...colData])
  }

  // 更新table宽度
  useEffect(() => {
    changeColumns()  // 改变Columns
  }, [items]);



  // 初始化
  const init = () => {



    columnsDefault = [
      { align: 'center', fixed: 'left', title: "序号", width: 68, render: (text, record, index) => `${index + 1}`, },
      {
        align: 'center',
        title: '功能类别',
        width: 260,
        key: 'name',
        fixed: 'left',
        render: (item: any) => {
          // return <div style={{ width: 100, display: 'inline-block' }}>
          //   <Timeline>
          //     <Timeline.Item> <Tag color="#f50">{item?.category?.parent?.parent?.parent?.name}</Tag></Timeline.Item>
          //     <Timeline.Item><Tag color="#2db7f5">{item?.category?.parent?.parent?.name}</Tag></Timeline.Item>
          //     <Timeline.Item> <Tag color="#87d068">{item?.category?.parent?.name}</Tag></Timeline.Item>
          //   </Timeline>
          // </div>
          return <div >
            <DirectoryTree
              multiple
              defaultExpandAll
              treeData={[
                {
                  title: item?.category?.parent?.parent?.parent?.name,
                  key: '0-0',
                  children: [
                    {
                      title: item?.category?.parent?.parent?.name,
                      key: '0-0-0',
                      children: [
                        {
                          title: item?.category?.parent?.name,
                          key: '0-0-1',
                          isLeaf: true
                        },
                      ],
                    },
                  ],
                },
              ]}
            />
          </div>
        },
      },
      {
        align: 'center',
        title: '功能项',
        width: 160,
        key: 'name',
        fixed: 'left',
        render: (item: any) => {
          return <div>{item?.category?.name}</div>
        },
      },
    ];

    // 是否显示功能标签
    if (props.FunctionTags) {
      columnsDefault.push({
        align: 'center',
        title: '功能标签',
        width: 100,
        key: 'label',
        fixed: 'left',
        render: (item: any) => {
          return <div> {item?.ftag?.name}</div>
        }
      })
    }

    handleResize()
    configurationConnect({}).then((res: any) => {
      console.log(res);
      setOptions(res)
    })


  }
  const onDragEnd = ({ active, over }: DragEndEvent) => {
    console.log(active);
    console.log(over);
    if (active.id !== over?.id) {
      setItems((prev) => {
        const activeIndex = prev.findIndex((i: any) => i.key === active.id);
        const overIndex = prev.findIndex((i: any) => i.key === over?.id);
        return arrayMove(prev, activeIndex, overIndex);
      });
    }
  };

  // 下一个 
  const next = (item: any, item2: any) => {
    console.log(item, item2);
    if (item2 && item) {
      setItems((prev) => {
        const activeIndex = prev.findIndex((i: any) => i.key === item.key);
        const overIndex = prev.findIndex((i: any) => i.key === item2?.key);
        return arrayMove(prev, activeIndex, overIndex);
      });
    }

  };

  // 上一个 
  const prev = (item: any, item2: any) => {
    console.log(item, item2);
    if (item2 && item) {
      setItems((prev) => {
        const activeIndex = prev.findIndex((i: any) => i.key === item.key);
        const overIndex = prev.findIndex((i: any) => i.key === item2?.key);
        return arrayMove(prev, activeIndex, overIndex);
      });
    }

  };

  const onChange = (newActiveKey: any) => {
    setActiveKey(newActiveKey);
  };

  const add = () => {
    const newActiveKey = `newTab${newTabIndex.current++}`;
    const newPanes = [...items];
    newPanes.push({ label: 'New Tab', key: newActiveKey });
    setItems(newPanes);
    setActiveKey(newActiveKey);
  };

  const remove = (targetKey: any) => {
    let newActiveKey = activeKey;
    let lastIndex = -1;
    items.forEach((item, i) => {
      if (item.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const newPanes = items.filter((item) => item.key !== targetKey);
    if (newPanes.length && newActiveKey === targetKey) {
      if (lastIndex >= 0) {
        newActiveKey = newPanes[lastIndex].key;
      } else {
        newActiveKey = newPanes[0].key;
      }
    }
    setItems(newPanes);
    setActiveKey(newActiveKey);
  };

  const onEdit = (
    targetKey: React.MouseEvent | React.KeyboardEvent | string,
    action: 'add' | 'remove',
  ) => {
    if (action === 'add') {
      add();
    } else {
      remove(targetKey);
    }
  };

  // 递归生成对比的标题
  const RecursiveTitle = (children: any, num: any) => {
    let left = num ? num : 0
    return (
      <>
        {children?.map((child: any, i: any) => {
          if (child.children.length > 0) {
            // 如果子元素是React元素，递归调用RecursiveCell组件处理
            left = 1;
            return <div className='child'>
              <div className='name' key={i}>{child.label}</div>
              <div style={{ paddingLeft: 20 * left }}>{RecursiveTitle(child.children, left)}</div>
            </div>;
          } else {
            // 如果子元素是文本节点或其他非React元素，直接返回
            left = 0;

            return <Tooltip title={child.label}>
              <div className="cell" key={i}>{child.label}</div>
            </Tooltip>
          }
        })}
      </>
    );
  };

  // 递归生成对比的内容
  const RecursiveBox = (children: any) => {

    return (
      <>
        {children?.map((child: any, i: any) => {
          if (child.children.length > 0) {
            // 如果子元素是React元素，递归调用RecursiveCell组件处理
            return <div style={{ paddingTop: '48px' }}>{RecursiveBox(child.children)}</div>
          } else {
            // 如果子元素是文本节点或其他非React元素，直接返回
            return <Tooltip title={child.note}>
              <div className="cell" key={i}>{child.note}</div>
            </Tooltip>
          }
        })}
      </>
    );
  };
  const eventsScroll = () => {
    // 2. 正常设值，同步两个DIV的滚动幅度
    let tableScrollLeft = tabletRef.current.querySelector('.ant-table-body')?.scrollLeft
    setTranslateX(tableScrollLeft)
  }


  return (
    <div id="Contrast" ref={Contrast} style={{ marginBottom: 20, background: '#fff', padding: 20 }}>
      <div className='top'>
        {/* <div className='screen'>
          <div className='title'>共<span className='price'>{items.length}</span>款车型</div>
          <div>
            <Checkbox onChange={onChange}>隐藏相同参数</Checkbox>
          </div>
          <div>
            <Checkbox onChange={onChange}>高亮不同参数</Checkbox>
          </div>
        </div> */}
        <div style={{ height: 40 }}>
          <div style={{ marginLeft: props.FunctionTags ? 588 : 488, overflow: 'hidden' }}>
            <div className='taps' style={{ transform: `translateX(-${translateX}px)`, }}>
              <Tabs
                type="editable-card"
                hideAdd
                // tabBarStyle={{background:'#f9f9f9'}}
                onChange={onChange}
                activeKey={activeKey}
                items={items}
                onEdit={onEdit}
                renderTabBar={(tabBarProps, DefaultTabBar) => (
                  <DndContext sensors={[sensor]} onDragEnd={onDragEnd}>
                    <SortableContext items={items.map((i) => i.key)} strategy={horizontalListSortingStrategy}>
                      <DefaultTabBar {...tabBarProps}>
                        {(node) => (
                          < DraggableTabNode {...node.props} key={node.key}>
                            <div className='tapsWidth'>
                              <Tooltip placement="topLeft" title={'拖动对比'}>
                                <div style={{ width: (offsetWidth / items.length < 300 ? 300 : offsetWidth / items.length) }}>{node}</div>
                              </Tooltip>
                            </div>
                          </DraggableTabNode>
                        )}
                      </DefaultTabBar>
                    </SortableContext>
                  </DndContext >
                  // {item?.option?.level}_{item?.option?.type}
                )}
              />
            </div>
          </div>
        </div>
      </div>
      <div style={{ display: items.length > 0 ? 'block' : 'none', width: offsetWidth + (props.FunctionTags ? 588 : 488) + 3 }} onScrollCapture={eventsScroll} >
        <Table ref={tabletRef} rowKey="id" columns={columns} dataSource={data} bordered scroll={{ y: 480, }}
          pagination={{
            showSizeChanger: true,
            pageSize: pageSize,
            total: data.length,
            onChange: (page: any, pageSize: any) => setPageSize(pageSize),
          }} />
      </div>
      <Empty style={{ display: items.length > 0 ? 'none' : "block" }} />
    </div >
  );
};

export default Contrast;