import {useAppDispatch, useAppSelector} from "../../redux/configureStore";
import {selectEdges, selectNodes} from "../pages/MainPage/slice/selectors";
import {mainActions} from "../pages/MainPage/slice";
import {CARD_TYPE} from "../components/WorkFlow/constants";
import {useCallback} from "react";
import {DEFINE_TYPE} from "../pages/IndexDefine/constants";

export function useWorkFlow() {
  const dispatch = useAppDispatch();
  // 获取当前流程的节点信息
  const getNodesState = useAppSelector(selectNodes);

  // 更新节点
  // const updateNodesState = (nodes)=>{
  //   console.log("nodeState",nodes)
  //   dispatch(mainActions.updateNodes(nodes));
  //   return nodes
  // }
  // 更新节点--支持内部更新
  const updateNodesState = useCallback((prev)=>{
    const isFunc = typeof prev === 'function';
    const isArray = Array.isArray(prev);
    if (isFunc){
      const marge = prev(getNodesState)
      dispatch(mainActions.updateNodes(marge));
      return marge
    }
    if (isArray){
      dispatch(mainActions.updateNodes(prev));
      return prev
    }

  },[getNodesState]);

  // 获取当前流程的关联信息
  const getEdgesState = useAppSelector(selectEdges);

  // 更新连接
  const updateEdgesState = (edges)=>{
    dispatch(mainActions.updateEdges(edges));
    return edges
  }


  // 返回所有的字段，并附上父节点信息
  const getFields = (nodes)=>{
    const parentNodes = nodes.filter(item=>item.type==='table')
    const fields = nodes.filter(item=>item.type==='fields')
    return fields.map(node=>{
      const pItem = parentNodes.find(pItem=>node.parentId===pItem.id)
      return {
        tableName:pItem?.data?.label,
        id:node?.id,
        isKey:node?.data?.isKey,
        datetime:node?.data?.type==='datetime',
        comment:node?.data?.description,
        dataType:node?.data?.type,
        fieldName:node?.data?.label,
        bizName: node?.data?.label,
      }
    })
  };

  // 主键、度量、日期、维度分类字段
  const markFields = (array,map)=>{
    let newMap = {};
    let newList = [];
    for (const index in array) {
      const item = array[index]
      for (const key in map) {
        if (!newMap[key]){
          newMap[key]=[];
        }
        if (item[key]){
          newMap[key].push(item);
        }
      }
    }
    for (const key in newMap) {
      newList.push({
        value:key,
        title:map[key],
        extra:`共计：${newMap[key].length}`,
        data:newMap[key]
      })
    }
    return newList
  };

  // 数据集模型->节点回显
  const modalToNodes = (data,len,checkList=[])=>{
    const {id,name,dimensions,metrics} = data;
    const insertFields = [...metrics,...dimensions];

    let commonDims=[];
    let commonPeriods = [];
    metrics.forEach(metric=>{
      // 指标、维度回显配置
      const thisConfig = checkList.find(item=>item.id===id);
      const checked = thisConfig && thisConfig.metrics.includes(metric.id);

      if (checked){
        // 汇总所有的统计周期
        const isPeriod = commonPeriods.includes(metric.statisticsPeriod);
        if (metric.statisticsPeriod && !isPeriod){
          commonPeriods.push(metric.statisticsPeriod);
        }

        // 计算公共维度
        const cellDims = metric.drillDownDimensions.map(item=>item.dimensionId)
        if (commonDims.length===0){
          commonDims = cellDims
        }else {
          commonDims = commonDims.reduce((acc, curr) => {
            if (cellDims.includes(curr) && !acc.includes(curr)) {
              acc.push(curr);
            }
            return acc;
          }, []);
        }
      }
    })

    // 插入所有Field节点
    const fieldInfo = insertFields.map((v, i) => {

      const checked = (checkList||[]).findIndex(
        item=> item.id===id && (item.metrics.includes(v.id) || item.dimensions.includes(v.id))
      )
      const checkable = !DEFINE_TYPE[v.type]
        ? commonDims.includes(v.id) // 公共维度判断维度可勾选
        : true;                 // 统计周期判断指标可勾选
      return {
        id: v.bizName,
        type: 'fields',
        position: {x: 0, y: i * 40},
        data: {
          id:v.id,
          label: v.name,
          description: v.description,
          type: v.type,
          isKey: v.type==="identify",
          checkable,
          checked:checked>=0,
          dimensions:(v.drillDownDimensions || []).map(item=>item.dimensionId),
          period:v?.statisticsPeriod,
          commonPeriods,
        },
        dragHandle:'dragHandle',
        parentId: `${id}`,
        extent: 'parent',
      }
    })
    // 插入Table节点
    const tableInfo = {
      id:`${id}`,
      type: 'table',
      data: {
        condition:CARD_TYPE.MODAL,
        height: fieldInfo.length * 40,
        label: name,
      },
      position: {x: (len-1)*600, y: 50},
    }
    return [tableInfo,...fieldInfo]
  }

  // 清除WorkFlow
  const clear = ()=>{
    dispatch(mainActions.updateNodes([]));
    dispatch(mainActions.updateEdges([]));
  };

  // 模拟数据
  const mockNodes=()=>{
    const rand = Math.random();
    updateNodesState(
        [
          ...getNodesState,
          {
            id: "tableName"+rand,
            type: 'table',
            data:{
              db:"db1",
              sourceId:"sourceId",
              label: "label",
              height:300
              //description: tableName,
            },
            position: { x: 50, y: 50 }
          },
          {
            id: "fields"+rand,
            type: 'fields',
            data:{
              db:"db2",
              sourceId:"sourceId2",
              label: "fields",
              description: "fieldsName",
              isKey:true,
              type: "INT"
            },
            draggable: false,
            parentId: "tableName"+rand,
            position: {x: 0, y: 0},
            extent: 'parent',
          }
        ]
    )
  }

  return {
    getNodesState,
    getEdgesState,
    updateNodesState,
    updateEdgesState,
    getFields,
    markFields,
    modalToNodes,
    clear,
    mockNodes
  }
}