import { ConnectTableEntity } from "src/entities/ConnectTableEntity";
import {
  PollingEntity,
  PollingTreeItemEntity,
} from "src/entities/PollingEntity";
import { store } from "quasar/wrappers";
import { ModeEntity, ModeTreeItemEntity } from "src/entities/ModeEntity";
import { WindowOpenNotifyEntity } from "src/entities/MultimediaWindowEntity";
import { PlanEntity, PlanTreeItemEntity } from "src/entities/PlanEntity";
import {
  SignalSourceEntity,
  SignalSourceTreeItemEntity,
} from "src/entities/SignalSourceEntity";
import { InjectionKey, reactive } from "vue";
import {
  createStore,
  Store as VuexStore,
  useStore as vuexUseStore,
} from "vuex";

import { EDeviceAttribute } from "src/entities/EDeviceAttribute";

// import example from './module-example'
// import { ExampleStateInterface } from './module-example/state';

/*
 * If not building with SSR mode, you can
 * directly export the Store instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Store instance.
 */

export class CustomDefines {
  is_custom_isv = false;
  function_output_board = false;
  function_center_control = false;
  function_mirroring_output = false;
  function_magic_wall = false;
  function_fusion = false;
}

export interface IWuJieEventBus {
  $on(event: string, fn: Function): IWuJieEventBus;
  /** 任何$emit都会导致监听函数触发，第一个参数为事件名，后续的参数为$emit的参数 */
  $onAll(fn: (event: string, ...args: Array<any>) => any): IWuJieEventBus;
  $once(event: string, fn: Function): void;
  $off(event: string, fn: Function): IWuJieEventBus;
  $offAll(fn: Function): IWuJieEventBus;
  $emit(event: string, ...args: Array<any>): IWuJieEventBus;
  $clear(): IWuJieEventBus;
}
export interface IWuJieInterface {
  props: any;
  bus: IWuJieEventBus;
}
class test_monitor {
  w = 0.0;
  h = 0.0;
  currentx = 0.0;
  currenty = 0.0;
  centerx = 0.0;
  centery = 0.0;
  angle = 0;
  id = 0;
  constructor(id: number, w: number, h: number) {
    this.currentx = 0.0;
    this.currenty = 0.0;
    this.angle = 0;
    this.centerx = 0;
    this.centery = 0;
    this.id = id;
    this.w = w;
    this.h = h;

  }
}
export interface StateInterface {
  // Define your own store structure, using submodules if needed
  // example: ExampleStateInterface;
  // Declared as unknown to avoid linting issue. Best to strongly type as per the line above.
  initialized: boolean;
  advanced_debug: boolean;
  factory_mode: boolean;
  signal_source_tree: SignalSourceTreeItemEntity[];
  polling_tree: PollingTreeItemEntity[];
  mode_tree: ModeTreeItemEntity[];
  plan_tree: PlanTreeItemEntity[];
  wall_row: number;
  wall_col: number;
  device_screen_width: number;
  device_screen_height: number;
  device_screen_refresh_rate: number;
  device_screen_connect_state: boolean;
  windows: WindowOpenNotifyEntity[];
  windows_sort: string[];
  device_ip_address: string;
  power_on_plan: string;
  fan_temp: number;
  selected_window: string;
  current_left_tab: string;
  selected_signal_source: string;
  selected_polling: string;
  current_running_plan: string;
  connect_list: ConnectTableEntity[];

  modes: ModeEntity[];
  plans: PlanEntity[];
  pollings: PollingEntity[];
  signal_sources: SignalSourceEntity[];
  landspace: boolean;
  device_attribute: number;
  power_state: boolean;
  product_name: string;
  show_monitor_list: test_monitor[];
  custom_defines: CustomDefines;
  fusion_configuration: object;
  isLedPlayer: () => boolean;
  isSpecialVideo: () => boolean;

  $wujie: IWuJieInterface | null;
  //
  selected_projector: string;
  EnableBlending: boolean;
}

// provide typings for `this.$store`
declare module "@vue/runtime-core" {
  interface ComponentCustomProperties {
    $store: VuexStore<StateInterface>;
  }
}

class _TreeHelper {
  public static findNode(node: any, key: string, value: string): any {
    if (node && node.children && key && value != null && value != undefined) {
      if (node[key] == value) {
        return node;
      }

      for (let child of <any[]>node.children) {
        if (child && child[key] == value) {
          return child;
        } else {
          let _r = _TreeHelper.findNode(child, key, value);
          if (_r) {
            return _r;
          }
        }
      }
    }
  }

  public static findNodeParent(node: any, key: string, value: string): any {
    if (node && node.children && key && value != null && value != undefined) {
      for (let child of <any[]>node.children) {
        if (child && child[key] == value) {
          return node;
        } else {
          let _r = _TreeHelper.findNodeParent(child, key, value);
          if (_r) {
            return _r;
          }
        }
      }
    }
  }

  public static addTreeItem(
    tree: any,
    defaultItem: () => any,
    createTreeItem: (
      uuid: string,
      parent: string,
      name: string,
      is_group: boolean
    ) => any,
    playload?: any
  ) {
    if (tree && playload) {
      const parent = playload.parent ?? "";
      const is_group = playload.is_group ?? false;
      let item_data = playload.item_data ?? defaultItem();
      let node = _TreeHelper.findNode(tree[0], "uuid", item_data.uuid);
      if (node) {
        return;
      }

      node = _TreeHelper.findNode(tree[0], "uuid", parent);
      if (node) {
        const node_item = createTreeItem(
          item_data.uuid,
          parent,
          item_data.name,
          is_group
        );
        node_item.item_data = item_data;
        (<any[]>node.children).push(node_item);
      }
    }
  }

  public static setTreeItem(
    tree: any,
    defaultItem: () => any,
    copy: (left: any, right: any) => void,
    playload?: any
  ) {
    if (tree && playload) {
      let item_data = playload.item_data ?? defaultItem();
      let node = _TreeHelper.findNode(tree[0], "uuid", item_data.uuid);
      if (node) {
        copy(node.item_data, item_data);
        node.name = item_data.name;
      }
    }
  }

  public static deleteTreeItem(tree: any, playload?: any) {
    if (tree && playload && playload.uuid) {
      let parent = _TreeHelper.findNodeParent(tree[0], "uuid", playload.uuid);
      if (parent) {
        let node_index = (<any[]>parent.children).findIndex(
          (item) => item && item.uuid == playload.uuid
        );
        if (node_index != -1) {
          (<any[]>parent.children).splice(node_index, 1);
        }
      }
    }
  }

  public static findGroupsByParent(parent: string, array: any[]) {
    return array.filter((item) => {
      return item && item.parent_uuid == parent;
    });
  }

  public static findItemsByParent(parent: string, array: any[]) {
    return array.filter((item) => {
      return item && item.group_uuid == parent;
    });
  }

  public static buildGroup(
    parent: any,
    createTreeItem: (
      uuid?: string,
      parent?: string,
      name?: string,
      is_group?: boolean,
      item_data?: any,
      children?: any[]
    ) => any,
    group_array: any[],
    item_array: any[]
  ) {
    if (parent) {
      for (let item of _TreeHelper.findGroupsByParent(
        parent.uuid,
        group_array
      )) {
        const node_item = createTreeItem(
          item.uuid,
          parent.uuid,
          item.name,
          true
        );
        node_item.item_data = item;
        parent.children.push(node_item);
        _TreeHelper.buildGroup(
          node_item,
          createTreeItem,
          group_array,
          item_array
        );
      }

      for (let item of _TreeHelper.findItemsByParent(parent.uuid, item_array)) {
        const node_item = createTreeItem(
          item.uuid,
          parent.uuid,
          item.name,
          false,
          item
        );
        parent.children.push(node_item);
      }
    }
  }

  public static buildTree(
    tree: any,
    group_name: string,
    items_name: string,
    root_text: string,
    createTreeItem: (
      uuid?: string,
      parent?: string,
      name?: string,
      is_group?: boolean,
      item_data?: any,
      children?: any[]
    ) => any,
    playload?: any
  ) {
    if (
      tree &&
      playload &&
      playload.response &&
      playload.options &&
      playload.options.$t
    ) {
      const $t = playload.options.$t;
      const groups = playload.response[group_name] ?? [];
      const items = playload.response[items_name] ?? [];

      const root = createTreeItem("", "", $t.t(root_text ?? "root"), true, {
        uuid: "",
        name: "",
        parent_uuid: "",
        group_uuid: "",
      });

      tree.splice(0, tree.length);
      tree.push(root);

      _TreeHelper.buildGroup(root, createTreeItem, groups, items);
    } else {
      console.error(playload);
    }
  }
}

// provide typings for `useStore` helper
export const storeKey: InjectionKey<VuexStore<StateInterface>> =
  Symbol("vuex-key");

import window_color_list from "./window_color_list.js";
import { EProductNames } from "src/entities/ProductNames";
export const NullSignalSource =
  "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";

export default store(function (/* { ssrContext } */) {
  const Store: VuexStore<StateInterface> = createStore<StateInterface>({
    modules: {
      // example
    },
    state: {
      // state
      initialized: false,
      advanced_debug: false,
      factory_mode: false,
      signal_source_tree: [],
      polling_tree: [],
      mode_tree: [],
      plan_tree: [],
      wall_col: 1,
      wall_row: 1,
      device_screen_width: 0,
      device_screen_height: 0,
      device_screen_refresh_rate: 0,
      device_screen_connect_state: true,
      windows: [],
      windows_sort: [],
      device_ip_address: "localhost",
      power_on_plan: "",
      fan_temp: 0,
      selected_window: "",
      current_left_tab: "signal_source",
      selected_signal_source: NullSignalSource,
      selected_polling: NullSignalSource,
      current_running_plan: "",
      connect_list: [],
      modes: [],
      plans: [],
      pollings: [],
      signal_sources: [],
      landspace: window.innerWidth > window.innerHeight,
      device_attribute: 0,
      power_state: false,
      fusion_configuration: {},
      product_name: EProductNames.LED_PLAYER,
      show_monitor_list: [],
      custom_defines: new CustomDefines(),
      selected_projector: "0/0",
      EnableBlending: false,
      isLedPlayer: () => {
        return (
          Store.state.product_name == EProductNames.LED_PLAYER ||
          Store.state.product_name == EProductNames.OLD_LED_PLAYER
        );
      },
      isSpecialVideo: () => {
        return Store.state.product_name == EProductNames.SPECIAL_VIDEO;
      },

      $wujie: null,
    },

    mutations: {
      setInitialized(state: StateInterface, playload?: any) {
        state.initialized = true;
      },
      setShowMonitorList(state: StateInterface, playload?: any) {
        state.show_monitor_list = playload
      },
      updateLandspace(state: StateInterface, playload?: any) {
        if (typeof playload == "boolean") {
          state.landspace = playload;
        }
      },
      setPowerState(state: StateInterface, playload: boolean) {
        state.power_state = playload;
      },
      setProductName(state: StateInterface, playload?: any) {
        if (
          playload == EProductNames.LED_PLAYER ||
          playload == EProductNames.SPECIAL_VIDEO ||
          playload == EProductNames.OLD_LED_PLAYER
        ) {
          state.product_name = playload;
        }
      },
      setDeviceAttribute(state: StateInterface, playload?: any) {
        const num = parseInt(playload);
        if (!isNaN(num) && num >= 0) {
          state.device_attribute = num;

          // parse custom attributes

          state.custom_defines.is_custom_isv =
            (state.device_attribute & EDeviceAttribute.CustomISV) != 0;
          state.custom_defines.function_output_board =
            (state.device_attribute & EDeviceAttribute.OutputBoard) != 0;
          state.custom_defines.function_center_control =
            (state.device_attribute & EDeviceAttribute.CenterControl) != 0;
          state.custom_defines.function_mirroring_output =
            (state.device_attribute & EDeviceAttribute.MirroringOutput) != 0;
          state.custom_defines.function_magic_wall =
            (state.device_attribute & EDeviceAttribute.ProductMagicWall) != 0;
          state.custom_defines.function_fusion =
            (state.device_attribute & EDeviceAttribute.ProductFusion) != 0;
        }
      },
      setAvancedDebug(state: StateInterface, playload?: any) {
        if (playload || playload == "true") {
          console.log("debug", playload);
          state.advanced_debug = playload;
        }
        state.advanced_debug = playload;
      },
      setFactoryMode(state: StateInterface, playload?: any) {
        if (playload || playload == "true") {
          console.log("factory", playload);
        }
        state.factory_mode = playload;
      },
      setArrayValue(state: StateInterface, playload?: any) {
        if (Array.isArray(playload.value)) {
          const arr: Array<any> = (<any>state)[playload.name];
          if (arr) {
            arr.splice(0, arr.length);
            for (const item of playload.value) {
              if (item) {
                arr.push(item);
              }
            }
          }
        }
      },
      setWindowPropertys(state: StateInterface, playload?: any[]) {
        if (playload && Array.isArray(playload)) {
          for (let item of playload) {
            const window = item.window;
            const property_name = item.property_name;
            const value = item.value;
            try {
              if (window && property_name) {
                window[property_name] = value;
              }
            } catch (e) {
              console.log(e);
            }
          }
        }
      },
      setWindowProperty(state: StateInterface, playload?: any) {
        const window = playload.window;
        const property_name = playload.property_name;
        const value = playload.value;
        if (window && property_name) {
          window[property_name] = value;
        }
      },
      setWindowClientProperty(state: StateInterface, playload?: any) {
        const window = playload.window;
        const property_name = playload.property_name;
        const value = playload.value;
        if (window && property_name) {
          window.client_propertys[property_name] = value;
        }
      },
      setWindows(state: StateInterface, playload?: WindowOpenNotifyEntity[]) {
        if (playload) {
          state.windows = playload;
          state.windows_sort = [];
          for (const item of state.windows) {
            state.windows_sort.push(item.uuid);
          }
          for (const window of state.windows) {
            if (window) {
              try {
                window.client_color = window_color_list.splice(
                  Math.round(Math.random() * window_color_list.length),
                  1
                )[0];
              } catch { }
            }
          }
        }
      },
      clearWindows(state: StateInterface, playload?: any) {
        state.windows = [];
        state.windows_sort = [];
      },
      pushWindow(state: StateInterface, playload?: WindowOpenNotifyEntity) {
        if (playload) {
          if (
            state.windows.find((e) => e && e.window_id == playload.window_id)
          ) {
            return;
          }
          try {
            playload.client_color = window_color_list.splice(
              Math.round(Math.random() * window_color_list.length - 1),
              1
            )[0];
          } catch { }
          state.windows.push(playload);
          state.windows_sort.push(playload.uuid);
        }
      },
      topWindow(state: StateInterface, playload?: number) {
        const window = state.windows.find(
          (element) => element && element.window_id == playload
        );
        if (window) {
          if (window) {
            const index = state.windows_sort.findIndex(
              (element) => element && element == window.uuid
            );
            if (index >= 0) {
              state.windows_sort.splice(index, 1);
              state.windows_sort.push(window.uuid);
            }
          }
        }
      },
      lowerWindow(state: StateInterface, playload?: number) {
        const window = state.windows.find(
          (element) => element && element.window_id == playload
        );
        if (window) {
          const index = state.windows_sort.findIndex(
            (element) => element && element == window.uuid
          );
          if (index >= 0) {
            state.windows_sort.splice(index, 1);
            state.windows_sort.unshift(window.uuid);
          }
        }
      },
      removeWindow(state: StateInterface, playload?: any) {
        const window_id = playload.window_id;
        if (window_id) {
          let index = state.windows.findIndex(
            (item) => item && item.window_id == window_id
          );
          if (index >= 0) {
            const window = state.windows[index];
            window_color_list.push(window.client_color);
            state.windows.splice(index, 1);

            let __index = state.windows_sort.findIndex(
              (element) => element && element == window.uuid
            );
            if (__index >= 0) {
              state.windows_sort.splice(__index, 1);
            }
          }
        } else {
          console.log("window_id???");
        }
      },
      cleanWindows(state: StateInterface, playload?: any) {
        state.windows.splice(0, state.windows.length);
      },
      editWindow(state: StateInterface, playload?: any) {
        const uuid = playload.uuid;
        const new_window = playload.new_window as WindowOpenNotifyEntity;
        if (uuid && new_window) {
          let index = state.windows.findIndex(
            (item) => item && item.uuid == uuid
          );
          if (index >= 0) {
            state.windows[index] = new_window;
          }
        }
      },
      setWallCol(state: StateInterface, playload?: any) {
        const num = parseInt(playload);
        if (!isNaN(num) && num > 0) {
          state.wall_col = num;
        }
      },
      setWallRow(state: StateInterface, playload?: any) {
        const num = parseInt(playload);
        if (!isNaN(num) && num > 0) {
          state.wall_row = num;
        }
      },
      setDeviceScreenWidth(state: StateInterface, playload?: any) {
        const num = parseInt(playload);
        if (!isNaN(num) && num > 0) {
          state.device_screen_width = num;
        }
      },
      setDeviceScreenHeight(state: StateInterface, playload?: any) {
        const num = parseInt(playload);
        if (!isNaN(num) && num > 0) {
          state.device_screen_height = num;
        }
      },
      setDeviceScreenRefreshRate(state: StateInterface, playload?: any) {
        const num = parseInt(playload);
        if (!isNaN(num) && num > 0) {
          state.device_screen_refresh_rate = num;
        }
      },
      setDeviceScreenConnectState(state: StateInterface, playload?: any) {
        try {
          state.device_screen_connect_state = JSON.parse(playload);
        } catch { }
      },
      // signal source
      setSignalSourceTree(
        state: StateInterface,
        playload?: SignalSourceTreeItemEntity[]
      ) {
        if (playload) {
          state.signal_source_tree = playload;
        }
      },
      setSelectedProjector(state: StateInterface, playload?: any) {
        state.selected_projector = playload;
      },
      setEnableBlending(state: StateInterface, playload?: any) {
        state.EnableBlending = playload;
      },
      clearSignalSourceTree(state: StateInterface, playload?: any) {
        state.signal_source_tree = [];
      },
      pushSignalSourceTreeItem(
        state: StateInterface,
        playload?: SignalSourceTreeItemEntity
      ) {
        if (playload) {
          state.signal_source_tree.push(playload);
        }
      },
      addSignalSourceTreeItem(state: StateInterface, playload?: any) {
        if (playload) {
          const parent = playload.parent ?? "";
          const is_group = playload.is_group ?? false;
          let item_data = playload.item_data ?? new SignalSourceEntity();
          if (item_data && item_data.local_file_flag) {
            return;
          }
          let node = _TreeHelper.findNode(
            state.signal_source_tree[0],
            "uuid",
            item_data.uuid
          );
          if (node) {
            return;
          }

          node = _TreeHelper.findNode(
            state.signal_source_tree[0],
            "uuid",
            parent
          );
          if (node) {
            const node_item = new SignalSourceTreeItemEntity(
              item_data.uuid,
              parent,
              item_data.name,
              is_group
            );
            node_item.item_data = item_data;
            (<any[]>node.children).push(node_item);
          }
        }
      },
      setSignalSourceTreeItem(state: StateInterface, playload?: any) {
        if (playload) {
          let item_data = playload.item_data ?? new SignalSourceEntity();
          let node = _TreeHelper.findNode(
            state.signal_source_tree[0],
            "uuid",
            item_data.uuid
          );
          if (node) {
            SignalSourceEntity.copy(node.item_data, item_data);
            node.name = item_data.name;
          }
        }
      },
      deleteSignalSourceTreeItem(state: StateInterface, playload?: any) {
        if (playload && playload.uuid) {
          let parent = _TreeHelper.findNodeParent(
            state.signal_source_tree[0],
            "uuid",
            playload.uuid
          );
          if (parent) {
            let node_index = (<any[]>parent.children).findIndex(
              (item) => item && item.uuid == playload.uuid
            );
            if (node_index != -1) {
              (<any[]>parent.children).splice(node_index, 1);
            }
          }
        }
      },
      buildSignalSourceTree(state: StateInterface, playload?: any) {
        const buildGroup = (
          parent: SignalSourceTreeItemEntity,
          group_array: any[],
          item_array: any[]
        ) => {
          if (parent) {
            for (let item of findGroupsByParent(parent.uuid, group_array)) {
              const node_item = new SignalSourceTreeItemEntity(
                item.uuid,
                parent.uuid,
                item.name,
                true
              );
              node_item.item_data = item;
              parent.children.push(node_item);
              buildGroup(node_item, group_array, item_array);
            }

            for (let item of findItemsByParent(parent.uuid, item_array)) {
              const node_item = new SignalSourceTreeItemEntity(
                item.uuid,
                parent.uuid,
                item.name,
                false,
                item
              );
              if (
                node_item &&
                node_item.item_data &&
                !node_item.item_data.local_file_flag
              ) {
                parent.children.push(node_item);
              }
            }
          }
        };

        const findGroupsByParent = (parent: string, array: any[]) => {
          return array.filter((item) => {
            return item && item.parent_uuid == parent;
          });
        };

        const findItemsByParent = (parent: string, array: any[]) => {
          return array.filter((item) => {
            return item && item.group_uuid == parent;
          });
        };

        if (
          playload &&
          playload.response &&
          playload.options &&
          playload.options.$t
        ) {
          const $t = playload.options.$t;
          const signal_source_groups =
            playload.response.signal_source_groups ?? [];
          const signal_sources = playload.response.signal_sources ?? [];

          const root = new SignalSourceTreeItemEntity(
            "",
            "",
            $t.t("signal source"),
            true,
            new SignalSourceEntity()
          );

          state.signal_source_tree.splice(0, state.signal_source_tree.length);
          state.signal_source_tree.push(root);

          buildGroup(root, signal_source_groups, signal_sources);
        } else {
          console.error(playload);
        }
      },
      //mode tree
      setModeTree(state: StateInterface, playload?: ModeTreeItemEntity[]) {
        if (playload) {
          state.mode_tree = playload;
        }
      },
      clearModeTree(state: StateInterface, playload?: any) {
        state.mode_tree = [];
      },
      pushModeTreeItem(state: StateInterface, playload?: ModeTreeItemEntity) {
        if (playload) {
          state.mode_tree.push(playload);
        }
      },
      addModeTreeItem(state: StateInterface, playload?: any) {
        _TreeHelper.addTreeItem(
          state.mode_tree,
          () => new ModeEntity(),
          (uuid: string, parent: string, name: string, is_group: boolean) =>
            new ModeTreeItemEntity(uuid, parent, name, is_group),
          playload
        );
      },
      setModeTreeItem(state: StateInterface, playload?: any) {
        _TreeHelper.setTreeItem(
          state.mode_tree,
          () => new ModeEntity(),
          (left: any, right: any) => ModeEntity.copy(left, right),
          playload
        );
      },
      deleteModeTreeItem(state: StateInterface, playload?: any) {
        _TreeHelper.deleteTreeItem(state.mode_tree, playload);
      },
      buildModeTree(state: StateInterface, playload?: any) {
        _TreeHelper.buildTree(
          state.mode_tree,
          "mode_groups",
          "modes",
          "mode",
          (
            uuid?: string,
            parent?: string,
            name?: string,
            is_group?: boolean,
            item_data?: any,
            children?: ModeTreeItemEntity[]
          ) =>
            new ModeTreeItemEntity(
              uuid,
              parent,
              name,
              is_group,
              item_data,
              children
            ),
          playload
        );
      },
      // plan tree
      setPlanTree(state: StateInterface, playload?: PlanTreeItemEntity[]) {
        if (playload) {
          state.plan_tree = playload;
        }
      },
      clearPlanTree(state: StateInterface, playload?: any) {
        state.plan_tree = [];
      },
      pushPlanTreeItem(state: StateInterface, playload?: PlanTreeItemEntity) {
        if (playload) {
          state.plan_tree.push(playload);
        }
      },
      addPlanTreeItem(state: StateInterface, playload?: any) {
        _TreeHelper.addTreeItem(
          state.plan_tree,
          () => new PlanEntity(),
          (uuid: string, parent: string, name: string, is_group: boolean) =>
            new PlanTreeItemEntity(uuid, parent, name, is_group),
          playload
        );
      },
      setPlanTreeItem(state: StateInterface, playload?: any) {
        _TreeHelper.setTreeItem(
          state.plan_tree,
          () => new PlanEntity(),
          (left: any, right: any) => PlanEntity.copy(left, right),
          playload
        );
      },
      deletePlanTreeItem(state: StateInterface, playload?: any) {
        _TreeHelper.deleteTreeItem(state.plan_tree, playload);
      },
      buildPlanTree(state: StateInterface, playload?: any) {
        _TreeHelper.buildTree(
          state.plan_tree,
          "plan_groups",
          "plans",
          "plan",
          (
            uuid?: string,
            parent?: string,
            name?: string,
            is_group?: boolean,
            item_data?: any,
            children?: PlanTreeItemEntity[]
          ) =>
            new PlanTreeItemEntity(
              uuid,
              parent,
              name,
              is_group,
              item_data,
              children
            ),
          playload
        );
      },
      // polling tree
      setPollingTree(
        state: StateInterface,
        playload?: PollingTreeItemEntity[]
      ) {
        if (playload) {
          state.polling_tree = playload;
        }
      },
      clearPollingTree(state: StateInterface, playload?: any) {
        state.polling_tree = [];
      },
      pushPollingTreeItem(
        state: StateInterface,
        playload?: PollingTreeItemEntity
      ) {
        if (playload) {
          state.polling_tree.push(playload);
        }
      },
      addPollingTreeItem(state: StateInterface, playload?: any) {
        _TreeHelper.addTreeItem(
          state.polling_tree,
          () => new PollingEntity(),
          (uuid: string, parent: string, name: string, is_group: boolean) =>
            new PollingTreeItemEntity(uuid, parent, name, is_group),
          playload
        );
      },
      setPollingTreeItem(state: StateInterface, playload?: any) {
        _TreeHelper.setTreeItem(
          state.polling_tree,
          () => new PollingEntity(),
          (left: any, right: any) => PollingEntity.copy(left, right),
          playload
        );
      },
      deletePollingTreeItem(state: StateInterface, playload?: any) {
        _TreeHelper.deleteTreeItem(state.polling_tree, playload);
      },
      buildPollingTree(state: StateInterface, playload?: any) {
        _TreeHelper.buildTree(
          state.polling_tree,
          "polling_groups",
          "pollings",
          "signal polling",
          (
            uuid?: string,
            parent?: string,
            name?: string,
            is_group?: boolean,
            item_data?: any,
            children?: PollingTreeItemEntity[]
          ) =>
            new PollingTreeItemEntity(
              uuid,
              parent,
              name,
              is_group,
              item_data,
              children
            ),
          playload
        );
      },
      // polling tree end
      setDeviceIpAddress(state: StateInterface, playload?: any) {
        if (playload) state.device_ip_address = playload;
      },
      setPowerOnPlan(state: StateInterface, playload?: any) {
        if (playload != null && playload != undefined)
          state.power_on_plan = playload;
      },
      setFanTemp(state: StateInterface, playload?: any) {
        const f = parseFloat(playload);
        if (!isNaN(f)) {
          state.fan_temp = f;
        }
      },
      setSelectedWindow(state: StateInterface, playload?: any) {
        state.selected_window = playload;
      },
      setCurrentLeftTab(state: StateInterface, playload?: any) {
        if (typeof playload == "string") {
          state.current_left_tab = playload;
        }
      },
      setSelectedSignalSource(state: StateInterface, playload?: any) {
        if (state.selected_signal_source == playload) {
          // state.selected_signal_source = NullSignalSource;
        } else {
          state.selected_signal_source = playload;
        }
      },
      setSelectedPolling(state: StateInterface, playload?: any) {
        if (state.selected_polling == playload) {
          state.selected_polling = NullSignalSource;
        } else {
          state.selected_polling = playload;
        }
      },
      setCurrentRunningPlan(state: StateInterface, playload?: any) {
        state.current_running_plan = playload;
      },
      setConnects(state: StateInterface, playload?: any) {
        state.connect_list = playload;
      },
      addConnectItem(state: StateInterface, playload?: any) {
        state.connect_list.push(playload);
      },
      cleanConnectItem(state: StateInterface, playload?: any) {
        const index = state.connect_list.findIndex(
          (element) => element && element.uuid == playload
        );
        if (index != -1) {
          state.connect_list.slice(index, 1);
        }
      },
      setWuJie(state: StateInterface, playload?: any) {
        state.$wujie = playload;
      },
    },
    getters: {
      GetTheCurrentlySelectedCamera(state) {
        let arr = state.selected_projector.split("/");
        return [Number(arr[0]), Number(arr[1])];
      },
    },
    // enable strict mode (adds overhead!)
    // for dev mode and --debug builds only
    strict: !!process.env.DEBUGGING,
  });

  return Store;
});

export function useStore() {
  return vuexUseStore(storeKey);
}
