import { defineStore } from 'pinia';

import { getEnfMineTree } from '/@/api/sys/menu';
import { getUserMinePermissionData } from '/@/components/Form/src/jeecg/components/MineCascader/mineData.api';
import { findNode, findPath, listToTree } from '/@/utils/helper/treeHelper';
import { isEmpty, isNil } from 'lodash';

export interface MineDepartment {
  /** 唯一标识 */
  id: string;
  /** 部门名称 */
  departName: string;
  /** 父部门ID */
  parentId: string | null;
  /** 是否为叶子节点 */
  isLeaf: boolean;
  /** 子部门列表 */
  childDepart: MineDepartment[];
  /** 传真，用作矿井编号 */
  fax: string | null;
}

export interface MineState {
  mine?: MineDepartment;
  /** 当前选中的矿井ID，可能为空 */
  mineId?: MineDepartment['id'];
  /** 当前选中的矿井编号，可能为空 */
  mineCode?: MineDepartment['fax'];
  /** 当前选中的矿井在组织树中的访问路径 */
  minePath: MineDepartment[];
  /** 矿井组织树 */
  mineTree: MineDepartment[];
}

const DEFAULT_CONFIG = {
  id: 'id',
  pid: 'parentId',
  children: 'childDepart',
};

export const useMineStore = defineStore({
  id: 'mine-store',
  state: (): MineState => ({
    mine: undefined,
    mineId: undefined,
    mineCode: undefined,
    minePath: [],
    mineTree: [],
  }),
  getters: {
    getMine(): MineState['mine'] {
      return this.mine;
    },
    getMineId(): MineState['mineId'] {
      return this.getMine?.id;
    },
    getMineCode(): MineState['mineCode'] {
      return this.getMine?.fax;
    },
    getMineTree(): MineState['mineTree'] {
      return this.mineTree;
    },
    getMinePath(): MineState['minePath'] {
      return this.minePath;
    },
  },
  actions: {
    /** 设置当前选中的矿井，并更新path项 */
    setMine(mine?: MineDepartment) {
      if (isNil(mine) || isEmpty(mine)) return;
      this.mine = mine;
      const path = findPath(this.getMineTree, (item) => item.id === mine.id, DEFAULT_CONFIG);
      this.setMinePath(path);
    },
    /** 根据传入的id设置当前选中的矿井，更新id、code、path三项 */
    setMineById(id: string = '') {
      const node = findNode(this.getMineTree, (item) => item.id === id, DEFAULT_CONFIG);
      this.setMine(node);
    },
    /** 根据传入的code设置当前选中的矿井，更新id、code、path三项 */
    setMineByCode(code: string = '') {
      const node = findNode(this.getMineTree, (item) => item.fax === code, DEFAULT_CONFIG);
      this.setMine(node);
    },
    setMinePath(path: any[] = []) {
      this.minePath = path;
    },
    setMineTree(tree: any[] = []) {
      this.mineTree = tree;
    },
    async fetchMineTree() {
      const r1 = await getEnfMineTree();
      const r2 = await getUserMinePermissionData({});
      r1.forEach((e) => (e.isLeaf = false));
      r2.forEach((e) => (e.isLeaf = true));
      const tree = listToTree([...r1, ...r2], DEFAULT_CONFIG);
      // 使用查找方法而不是选中r2中第一个“叶节点”是因为:
      // r2返回的矿名不具备权限控制，r1返回的父节点才有权限控制

      this.setMineTree(tree);

      if (this.getMine) return;

      const leaf = findNode(tree, (item) => item.isLeaf, DEFAULT_CONFIG);
      this.setMine(leaf);
    },
  },
});
