import { create } from "zustand";
import {
  editAgentWebsite as _editAgentWebsite,
  editAgentWebsite,
} from "@/service/agent";
import { TComponentItem } from "@/types/agent";
import { isSuccess } from "@/utils";

function safeSwap(arr: any[], index1: number, index2: number) {
  if (
    index1 >= 0 &&
    index1 < arr.length &&
    index2 >= 0 &&
    index2 < arr.length
  ) {
    [arr[index1], arr[index2]] = [arr[index2], arr[index1]];
  }
  return arr;
}

export interface ComponentState {
  agentId: string;
  maxIndex: number; // 最大组件索引
  insertIndex: number; // 插入组件的索引
  components: TComponentItem[] | []; // 后期是否需要改成链表方便中间插入删除等操作？？
  currentComponent: TComponentItem | null;
  loading: boolean;
  setLoading: (loading: boolean) => void
  setComponentList: (list: TComponentItem[], agentId: string) => void;
  delComponent: (c: TComponentItem) => Promise<boolean>;
  saveComponent: (c: TComponentItem) => Promise<boolean>;
  insertComponent: (c: TComponentItem[]) => Promise<TComponentItem[] | null>;
  swapTwoComponent: (c: TComponentItem, direction: number) => Promise<void>;
  setCurrentComponent: (
    component: TComponentItem | null
  ) => TComponentItem | null;
  setInsertIndex: (index: number) => void;
}

// 索引位置最大值
const getMaxIndex = (components: TComponentItem[]) => {
  return components.reduce((acc, cur) => {
    return Math.max(acc, cur.data.index ?? 1);
  }, 0);
};
// 根据索引位置 index 值 从小到大 排序
export const sortComponentsByIndex = (a: TComponentItem, b: TComponentItem) => {
  if (a.data.index === b.data.index) return 0;
  if (a.data.index === undefined || b.data.index === undefined) {
    return 0;
  }
  return a.data.index - b.data.index;
};

export const useComponentStore = create<ComponentState>((set, get) => ({
  loading: false,
  agentId: "",
  components: [],
  currentComponent: null,
  maxIndex: 1,
  insertIndex: -1,
  setLoading: (loading) =>{
    set({loading})
  },
  setComponentList: (list: TComponentItem[], agentId: string) => {
    let sorted = list.sort(sortComponentsByIndex);
    set({ agentId, components: sorted, maxIndex: getMaxIndex(sorted) });
  },
  insertComponent: async (list: TComponentItem[]) => {

    const insertIndex = get().insertIndex;
    let _components = get().components.sort(sortComponentsByIndex);
    console.log("current components list:", _components);
    const _componentsLen = _components.length;

    console.log("insertIndex:", insertIndex);

    if (insertIndex === -1) {
      console.log("顶部插入");
      // 顶部插入, 原组件列表所有 index + list.length
      _components = _components.map((item: TComponentItem) => {
        item.data.index = item.data.index + list.length;
        return item;
      });
      _components = [...list, ..._components];
    } else if (insertIndex === _componentsLen - 1) {
      console.log("底部插入");
      // 底部插入, 所有新插入的组件 index 需要加上已存在组件列表长度
      list = list.map((c) => {
        c.data.index = c.data.index + _componentsLen;
        return c;
      });
      _components = [..._components, ...list];
    } else {
      // 中间插入,
      console.log("中间插入", insertIndex);
      const restIndex = insertIndex + 1;
      list = list.map((c) => {
        c.data.index = c.data.index + restIndex;
        return c;
      });
      console.log("中间插入", list);

      let rest = _components.slice(restIndex).map((item) => {
        if (item.data.index) {
          item.data.index = item.data.index + list.length;
        }
        console.log(item.data.index, item.data);
        return item;
      });

      _components = [..._components.slice(0, restIndex), ...list, ...rest];
      console.log(_components, 111);
    }

    set({ components: _components });

    return _components;
  },
  saveComponent: async (c: TComponentItem) => {
    console.log("saveComponent", c);

    if (c.data.id === undefined) {
      console.log("没有 id 无法编辑该组件");
      return false;
    }
    set({loading: true})
    const insertIndex = get().insertIndex;
    const agentId = get().agentId;
    const components = [...get().components];
    console.log(c.data.id, insertIndex);

    const edit = components.find((item) => item.data.id === c.data.id);

    if (edit) {
      edit.data = c.data;
      edit.enabled = c.enabled;
    }

    // 简单更新组件
    console.log("a: ", components);
    console.log("b: ", get().components);

    // 普通更新或新建
    const { status } = await editAgentWebsite(agentId, {
      components: components,
    });
    set({loading: false})
    if (isSuccess(status)) {
      set({
        components,
      });
      return true;
    }
    return false;
  },
  setInsertIndex: (index) => {
    console.log(index, " setInsertIndex");
    set({ insertIndex: index });
  },
  setCurrentComponent: (component: TComponentItem | null) => {
    set({ currentComponent: component });

    return component;
  },
  delComponent: async (c) => {
    const { components, agentId } = get();
    // todo: 此处是否需要过滤一些没有 id 的脏数据组件
    if (!c.data.id || !agentId) {
      return false;
    }

    set({loading: true})

    const filtered = components
      .filter((item: TComponentItem) => item?.data.id !== c.data.id)
      .sort(sortComponentsByIndex)
      .map((item: TComponentItem, index) => {
        return {
          ...item,
          data: {
            ...item.data,
            index: index,
          }
        };
      });
    const { status } = await editAgentWebsite(agentId, {
      components: filtered,
    });
    set({loading: false})

    if (isSuccess(status)) {
      set({ components: filtered });
      return true;
    }
    return false;
  },

  calcMaxIndex: (components?: TComponentItem[]) => {
    set((state) => {
      return { maxIndex: getMaxIndex(components ?? state.components) };
    });
  },
  resortComponent: () => {
    set((state) => {
      let _comp = state.components;

      let r = [..._comp].sort(sortComponentsByIndex);
      console.log(r);
      return {
        components: r,
        loading: false,
      };
    });
  },
  // 交换两个组件上下位置
  swapTwoComponent: async (c: TComponentItem, direction: number) => {
    const cur = { ...c };
    const components = get().components;
    const arrIndex = components.findIndex((item) => item.data.id === c.data.id);
    let destComponent: TComponentItem | null = null;
    if (direction === 0) {
      destComponent = components[arrIndex - 1];
    } else if (direction === 1) {
      destComponent = components[arrIndex + 1];
    }

    const tmpList = [...components];

    if (destComponent) {
      destComponent = { ...destComponent };
      const destComponentIndex = components.findIndex(
        (item) => item.data.id === destComponent?.data.id
      );
      const i = cur.data.index;
      cur.data.index = destComponent.data.index;
      destComponent.data.index = i;
      const r = safeSwap(
        tmpList,
        arrIndex,
        destComponentIndex
      ) as TComponentItem[];
      await editAgentWebsite(get().agentId, { components: r });
      set({ components: r });
    }
  },
}));

// 获取组件列表中某个组件
export const getComponentById = (id: number) => {
  return useComponentStore((state) => {
    return state.components.find((c) => c.id === id);
  });
};
// 当前 component 便捷hook
export const useCurrentComponent = () => {
  return useComponentStore((state) => state.currentComponent);
};
