// import { useUuid } from '@/hooks/useUuid';
import { ProCard } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import { Button } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
// import Canvas from '../canvas/Canvas';
import { currJson1 } from '@/testData/fabricGroup1';
import { bgImageData } from '@/testData/testSvg';
import { fabric } from 'fabric';
import { ColumnDrawer } from './ColumnDrawer';

export const ModelCategoryColumns = [
  {
    title: '模型id',
    dataIndex: 'modelId',
  },
  {
    title: '模型状态',
    dataIndex: 'label',
  },
  {
    title: '模型名称',
    dataIndex: 'des',
  },
];
const ImageMapEditor: React.FC = () => {
  const intl = useIntl();
  const canvasRef = useRef(null);
  const itemsRef = useRef(null);
  const [cvs, setCanvas] = useState(null);
  const [descriptors, setDescriptors] = useState<Record<string, any>>({});
  const [category_fk_id_open, set_category_fk_id_open] = useState(false);
  const [currentModelUserProperty, setCurrentModelUserProperty] = useState<Record<string, any>>({});

  const [changeId, setChangeId] = useState<string[]>([]);

  const [clipPathData, setClipPathData] = useState({
    width: 1200, // 宽
    height: 900, // 高
  });
  const [jsonData, setJsonData] = useState<Record<string, any>>({});

  /*test */
  // const { fetchUuid } = useUuid();

  function changeModelStatus() {
    setChangeId(['2', '3']);
  }

  const handle_category_fk_id = (id: any) => {
    if (category_fk_id_open) {
      set_category_fk_id_open(false);
    }
  };

  useEffect(() => {
    const canvasObject = new fabric.Canvas(canvasRef.current);
    canvasObject.setBackgroundImage(bgImageData.src, canvasObject.renderAll.bind(canvasObject), {
      width: clipPathData.width,
      height: clipPathData.height,
      originX: 'left',
      originY: 'top',
    });
    canvasObject.loadFromJSON(JSON.stringify(currJson1), () => {
      canvasObject.renderAll();
      // const groupObjectList = canvasObject.getObjects()

      // const groupObject = canvasObject.getObjects()[0];

      // 选中组合对象
      // console.log(groupObject, 'groupObject', canvasObject.getObjects());
      // 注册事件监听器
      canvasObject.on('mouse:up', (event) => {
        // 获取事件的目标对象
        const targetObject = event.target;
        // 检查目标对象是否为组合对象
        if (targetObject && targetObject?.userProperty) {
          console.log('Group selected:', targetObject);
          setCurrentModelUserProperty(targetObject.userProperty);
          set_category_fk_id_open(true);
          // canvasObject.setActiveObject(groupObject);
          // canvasObject.requestRenderAll();
          // 在这里可以执行你想要的操作
          // 添加缩放动画
          // targetObject.animate('scaleX', '+=0.1', {
          //   duration: 500, // 动画持续时间，单位毫秒
          //   onChange: canvasObject.renderAll.bind(canvasObject), // 在动画过程中实时渲染画布
          //   onComplete: () => {
          //     console.log('Animation complete!');
          //     // 在动画完成后执行其他操作
          //   },
          // });
          // targetObject.animate('scaleY', '+=0.1', {
          //   duration: 500, // 动画持续时间，单位毫秒
          //   onChange: canvasObject.renderAll.bind(canvasObject), // 在动画过程中实时渲染画布
          //   onComplete: () => {
          //     console.log('Animation complete!');
          //     // 在动画完成后执行其他操作
          //   },
          // });
        }
      });

      
    // 设置目标的速度和方向
    const velocity = {
      // scaleX: 0.1, // 0 ~ 1
      // scaleY: 0.1, // 0 ~ 1
      opacity: 0.1, // 0 ~ 1
    };


      function animate() {
        canvasObject
          .getObjects()
          .concat()
          .forEach(function (obj) {
            obj.opacity += velocity.opacity;

            if( obj.opacity <= 0.5 ||  obj.opacity >= 1){
              velocity.opacity = -velocity.opacity;
            }
            // obj.rotate(obj.get('angle') + 1);
            // 位移   
            // obj.left += velocity.x;
            // obj.top += velocity.y;
            // // 碰撞检测
            // if (obj.left <= 0 || obj.left + obj.width >= clipPathData.width) {
            //   velocity.x = -velocity.x; // 水平方向反弹
            // }
  
            // if (obj.top <= 0 || obj.top + obj.height >= clipPathData.height) {
            //   velocity.y = -velocity.y; // 垂直方向反弹
            // }x
            //   if (obj.left > 900 || obj.left < -100 || obj.top > 500) {
            //     newCanvas.remove(obj);
            //   }
            //   else {
            //   }
          });
          canvasObject.renderAll();
        fabric.util.requestAnimFrame(animate);
      }
  

      if (changeId && changeId.length) {
        canvasObject
          .getObjects().forEach(item=>{
            if(changeId.includes(item?.userProperty?.id) ){
              const groupObject = item
               // 选中组合对象
        // canvasObject.setActiveObject(groupObject); // 可以改变 selectable 值
        canvasObject.requestRenderAll();
        // 获取组合对象中的子对象
        const objectsInGroup = groupObject.getObjects();
        // 遍历子对象找到要修改的子对象
        const objectToModify = objectsInGroup.find((obj) => obj.get('type') === 'circle');
        const objectToModify2 = objectsInGroup.find((obj) => obj.get('type') === 'i-text');
        //
        if (groupObject?.userProperty) {
          groupObject.set({
            userProperty: {
              ...groupObject?.userProperty,
              status: '1',
            },
          });
        }

        // 修改子对象的属性
        if (objectToModify) {
          objectToModify.set({
            fill: 'rgba(248,9,3,0.94)',
            stroke: 'rgba(255,243,47,1)',
            // height: 60,
            // 添加其他属性...
          });
          // 重新渲染Canvas
          canvasObject.renderAll();
        }
        if (objectToModify2) {
          objectToModify2.set({
            text: '警告',
          });
          // 重新渲染Canvas
          canvasObject.renderAll();
        }
            }
          })
        // 获取组合对象（选中目标对象）
        // const groupObject = canvasObject
        //   .getObjects()
        //   .find((item) => item?.userProperty?.id === changeId);
        // console.log(groupObject, 'groupObject', canvasObject.getObjects());
       
      }

      // 获取组合对象中的属性
      //   const properties = groupObject.getObjects().map(obj => {
      // 	return {
      // 	  type: obj.get('type'),
      // 	  width: obj.get('width'),
      // 	  height: obj.get('height'),
      // 	  fill: obj.get('fill'),
      // 	  left: obj.get('left'),
      // 	  top: obj.get('top')
      // 	  // 添加其他属性...
      // 	};
      //   });

      //   console.log('Properties of the selected group:', properties);
    });
    return () => {
      canvasObject.dispose();
    };
  }, [changeId]);

  useEffect(() => {
    // TODO_3 需要加个loading效果
    import('./Descriptors.json').then((descriptors) => {
      setDescriptors(descriptors);
    });
    // console.log(fetchUuid(), 'fetchUuid');
  }, []);

  return (
    <ProCard
      gutter={24}
      extra={
        <>
          <Button type="primary" onClick={changeModelStatus}>
            切换状态
          </Button>
        </>
      }
    >
      {/* <ProCard colSpan={4}>
        <ImageMapItems ref={itemsRef} canvasRef={canvasRef} descriptors={descriptors} />
      </ProCard> */}
      <ProCard colSpan={24} style={{ padding: 0, margin: 0 }} bodyStyle={{ padding: 0, margin: 0 }}>
        <canvas
          ref={canvasRef}
          {...clipPathData}
          style={{ border: '1px dashed #eee' }}
        ></canvas>
      </ProCard>

      <ColumnDrawer
        handleDrawer={handle_category_fk_id}
        isShowDetail={category_fk_id_open}
        columns={ModelCategoryColumns}
        currentRow={currentModelUserProperty}
      />
    </ProCard>
    // 属性预览
  );
};

export default ImageMapEditor;
