/*
 * @Author: zhoux zhouxia@supervision.ltd
 * @Date: 2023-12-12 10:57:54
 * @LastEditors: zhoux zhouxia@supervision.ltd
 * @LastEditTime: 2023-12-29 15:44:16
 * @FilePath: \general-ai-platform-web\src\pages\FabricView\Room\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { currJson } from '@/testData/fabricRoomList';
import { bgImageData } from '@/testData/fabricRoomSvg';
import { ProCard } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import { Button } from 'antd';
import { fabric } from 'fabric';
import React, { useEffect, useRef, useState } from 'react';
import { ColumnDrawer } from './components/ColumnDrawer';
import ModelTipBox from './components/ModelTipBox';
import LoadingSpin from '@/components/Loading/loadingSpin';

export const ModelCategoryColumns = [
  {
    title: '设备ID',
    dataIndex: 'id',
  },
  {
    title: '设备名称',
    dataIndex: 'deviceName',
  },
  {
    title: '设备代码',
    dataIndex: 'deviceCode',
  },
  {
    title: '设备位置',
    dataIndex: 'deviceLocation',
  },
  {
    title: '设备代码',
    dataIndex: 'deviceCode',
  },
  {
    title: '设备名称',
    dataIndex: 'deviceName',
  },
  {
    title: '设备代码',
    dataIndex: 'deviceCode',
  },
  {
    title: '设备名称',
    dataIndex: 'deviceName',
  },
];

const FabricViewRoom: 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 [isLoading, setisLoading] = useState<boolean>(true);

  const [changeId, setChangeId] = useState<string[]>([]);
  const [currentTargetObject, setCurrentTargetObject] = useState<any>(null);

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

  function changeZoom(isPlus: boolean) {
    const rate = isPlus ? 1.1 : 0.9;
    // plus minus
    const currentZoom = cvs.getZoom();
    const newZoom = currentZoom * rate; // 缩小 10%
    cvs.setZoom(newZoom);
  }

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

  function closeSelectedModel(targetCvs?: any) {
    let finalCvs = cvs;
    if (targetCvs) {
      finalCvs = targetCvs;
    }
    finalCvs.getObjects().forEach((item) => {
      // if (changeId.includes(item?.userProperty?.id)) {
      const groupObject = item;
      // 选中组合对象
      // canvasObject.setActiveObject(groupObject); // 可以改变 selectable 值
      finalCvs.requestRenderAll();
      // 获取组合对象中的子对象
      const objectsInGroup = groupObject.getObjects();
      groupObject.item(0).item(1).set({
        fill: '#DCDCDC',
      });
      groupObject.item(1).set({
        fill: 'rgb(0,0,0)',
      });
      finalCvs.renderAll();
      // 遍历子对象找到要修改的子对象

      // }
    });
  }
  // 筛选显示告警状态
  function changeStatusSelected(selecteds: string[]) {
    console.log(cvs.getObjects(), 'changeStatusSelected_selected', selecteds);
    if(selecteds.length){
      cvs.getObjects().map((element) => {
        element.set({
          visible: selecteds.includes(element?.userProperty?.status),
        });
      });
    } else {
      cvs.getObjects().map((element) => {
        element.set({
          visible: true,
        });
      });
    }

    cvs.renderAll();
  }

  // 初始化加载画布&渲染模型
  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(currJson), () => {
      canvasObject.renderAll();
      // const groupObjectList = canvasObject.getObjects()

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

      // 选中组合对象
      // console.log(groupObject, 'groupObject', canvasObject.getObjects());
      // 注册事件监听器
      canvasObject.on('mouse:down', (event) => {
        // 获取事件的目标对象
        const targetObject = event.target;
        // set_category_fk_id_open(false);
        // 检查目标对象是否为组合对象
        if (targetObject && targetObject?.userProperty) {
          // canvasObject.setActiveObject(targetObject);
          setChangeId([targetObject?.userProperty?.id]);
          // console.log('mouse:up:', targetObject);
          setCurrentModelUserProperty(targetObject.userProperty);
          set_category_fk_id_open(true);
        }
        // 检查目标对象是否为组合对象
        if (targetObject) {
          setCurrentTargetObject(targetObject);
          closeSelectedModel(canvasObject);
          canvasObject.bringToFront(targetObject);

          // console.log('mouse:down:', );
          targetObject.item(0).item(1).set({
            fill: 'blue',
          });
          targetObject.item(1).set({
            fill: 'blue',
          });
        }
        canvasObject.renderAll();
      });
    });
    setCanvas(canvasObject);
    // setTimeout(()=>{
      setisLoading(false)
    // },1000)
    return () => {
      canvasObject.dispose();
    };
  }, []);

  useEffect(() => {
    // import('./Descriptors.json').then((descriptors) => {
    //   setDescriptors(descriptors);
    // });
    // console.log(fetchUuid(), 'fetchUuid');
    if (changeId && changeId.length && !category_fk_id_open) {
      closeSelectedModel();
    }
  }, [changeId, category_fk_id_open]);

  return (
    <div>
      <LoadingSpin spinning={isLoading}></LoadingSpin>
      <ProCard
        gutter={24}
        extra={
          <>
            <Button type="primary" style={{ marginRight: 20 }} onClick={() => changeZoom(false)}>
              缩小
            </Button>
            <Button type="primary" onClick={() => changeZoom(true)}>
              扩大
            </Button>
          </>
        }
      >
    
        <ProCard
          colSpan={24}
          style={{ padding: 0, margin: 0 }}
          bodyStyle={{ padding: 0, margin: 0 }}
        >
          <canvas ref={canvasRef} {...clipPathData} style={{ border: '1px dashed #eee' }}></canvas>
          <div style={{ position: 'absolute', bottom: 0, right: 0 }}>
            <ModelTipBox
              changeStatusSelected={(selected: string[]) => changeStatusSelected(selected)}
            ></ModelTipBox>
          </div>
          <ColumnDrawer
            handleDrawer={handle_category_fk_id}
            isShowDetail={category_fk_id_open}
            columns={ModelCategoryColumns}
            currentRow={currentModelUserProperty}
            clipPathData={clipPathData}
            canvasObject={cvs}
          />
        </ProCard>
      </ProCard>
    </div>
  );
};

export default FabricViewRoom;
