import type { AppState } from "./types";
import { localStorage } from "@/utils/storage";
import { defineStore } from "pinia";
import { getLanguage } from "@/lang/index";
import { allMenuApi, allButtonApi } from "@/api/auth";
import { reactive } from "vue";
import { convertAsyncRoutes, homeRoute, notFoundRoute } from '@/router/route';
import useUserStore from './user';

// 后台返回数据格式
const routesArr = reactive([
  // 首页
  {
    path: "/home",
    meta: {
      label: "首页",
      icon: "",
    },
    children: [
      {
        path: "/home",
        meta: {
          label: "首页",
          icon: "",
        },
      },
    ],
  },
  // 基础管理
  {
    path: "/basics",
    meta: {
      label: "基础管理",
      icon: "",
    },
    children: [
      // 基础资料维护
      {
        path: "/basics/basicsManagement",
        meta: {
          label: "基础资料",
          icon: "",
        },
        children: [
          {
            path: "/basics/basicsManagement/materialInfo",
            meta: {
              label: "物料信息",
              icon: "",
            },
          },
          {
            path: "/basics/wareHouseLocation",
            meta: {
              label: "库位信息",
              icon: "",
            },
          },
          {
            path: "/basics/supplierManagement",
            meta: {
              label: "供应商管理",
              icon: "",
            },
          },
          {
            path: "/basics/customManagement",
            meta: {
              label: "客户管理",
              icon: "",
            },
          }
        ],
      },
      // 立库基础信息维护
      {
        path: "/basics/stockManagement",
        meta: {
          label: "立库基础信息",
          icon: "",
        },
        children: [
          {
            path: "/basics/wareAreaInfo",
            meta: {
              label: "库区信息",
              icon: "",
            },
          },
          {
            path: "/basics/lanewayInfo",
            meta: {
              label: "巷道信息",
              icon: "",
            },
          },
          {
            path: "/basics/locationInfo",
            meta: {
              label: "货位信息",
              icon: "",
            },
          },
          {
            path: "/basics/locationStausInfo",
            meta: {
              label: "货位状态管理",
              icon: "",
            },
          },
          {
            path: "/basics/curingWareHouse",
            meta: {
              label: "熟化库配置",
              icon: "",
            },
          },
        ],
      },
    ],
  },
  // 操作管理
  {
    path: "/material",
    meta: {
      label: "操作管理",
      icon: "",
    },
    children: [
      // 查询
      {
        path: "/material/messageQuery",
        meta: {
          label: "信息查询",
          icon: "",
        },
        children: [
          {
            path: "/material/messageQuery/supplierQuery",
            meta: {
              label: "供应商查询",
              icon: "",
            },
          },
          {
            path: "/material/messageQuery/materialQuery",
            meta: {
              label: "物料查询",
              icon: "",
            },
          },
          {
            path: "/material/messageQuery/wareHouseLocationQuery",
            meta: {
              label: "库位查询",
              icon: "",
            },
          },
          {
            path: "/material/messageQuery/materialReceiveRequestQuery",
            meta: {
              label: "采购单据查询",
              icon: "",
            },
          },
          {
            path: "/material/messageQuery/materialShipRequestQuery",
            meta: {
              label: "发货单据查询",
              icon: "",
            },
          },
          {
            path: "/material/messageQuery/materialReceiveActQuery",
            meta: {
              label: "抬头文本查询",
              icon: "",
            },
          },
          // 到货PO查询
          {
            path: "/material/messageQuery/POQuery",
            meta: {
              label: "到货PO查询",
              icon: "",
            },
          },
          // Box信息查询
          {
            path: "/material/messageQuery/materialBoxQuery",
            meta: {
              label: "Box信息查询",
              icon: "",
            },
          },
          // Box历史信息查询
          {
            path: "/material/messageQuery/materialBoxHistoryQuery",
            meta: {
              label: "Box历史信息查询",
              icon: "",
            },
          },
          // Box出入库查询
          {
            path: "/material/messageQuery/materialBoxStockedQuery",
            meta: {
              label: "Box出入库查询",
              icon: "",
            },
          },
          // 品质待检看板
          {
            path: "/material/messageQuery/materialQualityInspectedQuery",
            meta: {
              label: "品质待检看板",
              icon: "",
            },
          },
          // 待入库看板
          {
            path: "/material/messageQuery/materialPreStockedQuery",
            meta: {
              label: "待入库看板",
              icon: "",
            },
          },
          // 寿命管理看板
          {
            path: "/material/messageQuery/newMaterialLife",
            meta: {
              label: "寿命管理看板",
              icon: "",
            },
          },
          // 拣配未出库看板
          {
            path: "/material/messageQuery/reservedPreStockOut",
            meta: {
              label: "拣配未出库看板",
              icon: "",
            },
          },
          // 库存查询
          {
            path: "/material/messageQuery/newInventoryView",
            meta: {
              label: "库存查询",
              icon: "",
            },
          },
        ],
      },
      // 单据管理
      {
        path: "/material/orderManagement",
        meta: {
          label: "单据管理",
          icon: "",
        },
        children: [
          {
            path: "/material/orderManagement/POManagement",
            meta: {
              label: "采购单据管理",
              icon: "",
            },
          },
          {
            path: "/material/orderManagement/shipRequestManagement",
            meta: {
              label: "发货单据管理",
              icon: "",
            },
          },
        ],
      },
      // 创建Box
      {
        path: "/material/createBox",
        meta: {
          label: "创建Box",
          icon: "",
        },
        children: [
          {
            path: "/material/createBox/createBoxByPO",
            meta: {
              label: "创建Box",
              icon: "",
            },
          },
          {
            path: "/material/createBox/createBoxByLabel",
            meta: {
              label: "扫描标签创建Box",
              icon: "",
            },
          },
          {
            path: "/material/createBox/modifyActInfo",
            meta: {
              label: "抬头文本解绑Box",
              icon: "",
            },
          },
          {
            path: "/material/createBox/modifyReceiveActNo",
            meta: {
              label: "删除抬头文本",
              icon: "",
            },
          },
        ],
      },
      // 物料入库
      {
        path: "/material/stockIn",
        meta: {
          label: "物料入库",
          icon: "",
        },
        children: [
          {
            path: "/material/stockIn/normalStockIn",
            meta: {
              label: "PO入库",
              icon: "",
            },
          },
          {
            path: "/material/stockIn/refundStockIn",
            meta: {
              label: "非PO入库",
              icon: "",
            },
          },
        ],
      },
      // 物料质检
      {
        path: "/material/OQA",
        meta: {
          label: "物料质检",
          icon: "",
        },
        children: [
          {
            path: "/material/OQA/noValueOQA",
            meta: {
              label: "质检手工判断",
              icon: "",
            },
          },
        ],
      },
      // 物料在库
      {
        path: "/material/stocked",
        meta: {
          label: "物料在库",
          icon: "",
        },
        children: [
          {
            path: "/material/stocked/locationMove",
            meta: {
              label: "库位移动",
              icon: "",
            },
          },
          {
            path: "/material/stocked/mergeBox",
            meta: {
              label: "Box合并",
              icon: "",
            },
          },
          {
            path: "/material/stocked/splitBox",
            meta: {
              label: "Box拆分",
              icon: "",
            },
          },
          {
            path: "/material/stocked/holdAndRelease",
            meta: {
              label: "Hold/Release",
              icon: "",
            },
          },
          {
            path: "/material/stocked/makeUndo",
            meta: {
              label: "物料冲销",
              icon: "",
            },
          },
          {
            path: "/material/stocked/preScrap",
            meta: {
              label: "物料预报废",
              icon: "",
            },
          },
          {
            path: "/material/stocked/scrap",
            meta: {
              label: "物料报废",
              icon: "",
            },
          },
        ],
      },
      // 物料出库
      {
        path: "/material/stockOut",
        meta: {
          label: "物料出库",
          icon: "",
        },
        children: [
          {
            path: "/material/stockOut/shipRequestReserve",
            meta: {
              label: "预约拣配",
              icon: "",
            },
          },
          {
            path: "/material/stockOut/shipRequestConfirm",
            meta: {
              label: "确认拣配",
              icon: "",
            },
          },
          {
            path: "/material/stockOut/manualStockOut",
            meta: {
              label: "出库",
              icon: "",
            },
          },
          {
            path: "/material/stockOut/POReturn",
            meta: {
              label: "入库PO返厂",
              icon: "",
            },
          },
          {
            path: "/material/stockOut/RMAReturn",
            meta: {
              label: "退货PO返厂",
              icon: "",
            },
          },
        ],
      },
    ],
  },

  // 立库作业
  {
    path: "/buildWareHouse",
    meta: {
      label: "立库作业",
      icon: "",
    },
    children: [
      {
        path: "/buildWareHouse/peopleTransport",
        meta: {
          label: "人工搬送",
          icon: "",
        },
      },
      {
        path: "/buildWareHouse/agvTransport",
        meta: {
          label: "AGV搬送",
          icon: "",
        },
      },
      {
        path: "/buildWareHouse/emptyTrayTransport",
        meta: {
          label: "空托盘搬送",
          icon: "",
        },
      },
      {
        path: "/buildWareHouse/agvOut",
        meta: {
          label: "AGV出库",
          icon: "",
        },
      }, {
        path: "/buildWareHouse/peopleOut",
        meta: {
          label: "人工出库",
          icon: "",
        },
      }, {
        path: "/buildWareHouse/emptyTrayOut",
        meta: {
          label: "空托盘出库",
          icon: "",
        },
      }, {
        path: "/buildWareHouse/LibaryPriority",
        meta: {
          label: "优先级调整",
          icon: "",
        },
      }

    ],
  },
  // 标签管理
  {
    path: "/label",
    meta: {
      label: "标签管理",
      icon: "",
    },
    children: [
      {
        path: "/label/preStockedBoxLabelPrint",
        meta: {
          label: "待入库Box标签打印",
          icon: "",
        },
      },
      {
        path: "/label/multi_BoxLabelPrint",
        meta: {
          label: "批量打印Box标签",
          icon: "",
        },
      },
      {
        path: "/label/reprint_BoxLabel",
        meta: {
          label: "重新打印Box标签",
          icon: "",
        },
      },
      {
        path: "/label/locationLabelPrint",
        meta: {
          label: "库位标签打印",
          icon: "",
        },
      },
      {
        path: "/label/PalletLabelPrint",
        meta: {
          label: "Pallet标签打印",
          icon: "",
        },
      },
    ],
  },
  // 材料管理
  {
    path: "/material",
    meta: {
      label: "材料管理",
      icon: "",
    },
    children: [
      // 查询
      {
        path: "/material/messageQuery",
        meta: {
          label: "信息查询",
          icon: "",
        },
        children: [
          {
            path: "/material/messageQuery/supplierQuery",
            meta: {
              label: "供应商查询",
              icon: "",
            },
          },
          {
            path: "/material/messageQuery/materialQuery",
            meta: {
              label: "物料查询",
              icon: "",
            },
          },
          {
            path: "/material/messageQuery/wareHouseLocationQuery",
            meta: {
              label: "库位查询",
              icon: "",
            },
          },
          {
            path: "/material/messageQuery/materialReceiveRequestQuery",
            meta: {
              label: "采购单据查询",
              icon: "",
            },
          },
          {
            path: "/material/messageQuery/materialShipRequestQuery",
            meta: {
              label: "发货单据查询",
              icon: "",
            },
          },
          {
            path: "/material/messageQuery/materialReceiveActQuery",
            meta: {
              label: "抬头文本查询",
              icon: "",
            },
          },
          // 到货PO查询
          {
            path: "/material/messageQuery/POQuery",
            meta: {
              label: "到货PO查询",
              icon: "",
            },
          },
          // Box信息查询
          {
            path: "/material/messageQuery/materialBoxQuery",
            meta: {
              label: "Box信息查询",
              icon: "",
            },
          },
          // Box历史信息查询
          {
            path: "/material/messageQuery/materialBoxHistoryQuery",
            meta: {
              label: "Box历史信息查询",
              icon: "",
            },
          },
          // Box出入库查询
          {
            path: "/material/messageQuery/materialBoxStockedQuery",
            meta: {
              label: "Box出入库查询",
              icon: "",
            },
          },
          // 品质待检看板
          {
            path: "/material/messageQuery/materialQualityInspectedQuery",
            meta: {
              label: "品质待检看板",
              icon: "",
            },
          },
          // 待入库看板
          {
            path: "/material/messageQuery/materialPreStockedQuery",
            meta: {
              label: "待入库看板",
              icon: "",
            },
          },
          // 寿命管理看板
          {
            path: "/material/messageQuery/newMaterialLife",
            meta: {
              label: "寿命管理看板",
              icon: "",
            },
          },
          // 拣配未出库看板
          {
            path: "/material/messageQuery/reservedPreStockOut",
            meta: {
              label: "拣配未出库看板",
              icon: "",
            },
          },
          // 库存查询
          {
            path: "/material/messageQuery/newInventoryView",
            meta: {
              label: "库存查询",
              icon: "",
            },
          },
        ],
      },
      // 单据管理
      {
        path: "/material/orderManagement",
        meta: {
          label: "单据管理",
          icon: "",
        },
        children: [
          {
            path: "/material/orderManagement/POManagement",
            meta: {
              label: "采购单据管理",
              icon: "",
            },
          },
          {
            path: "/material/orderManagement/shipRequestManagement",
            meta: {
              label: "发货单据管理",
              icon: "",
            },
          },
        ],
      },
      // 创建Box
      {
        path: "/material/createBox",
        meta: {
          label: "创建Box",
          icon: "",
        },
        children: [
          {
            path: "/material/createBox/createBoxByPO",
            meta: {
              label: "创建Box",
              icon: "",
            },
          },
          {
            path: "/material/createBox/createBoxByLabel",
            meta: {
              label: "扫描标签创建Box",
              icon: "",
            },
          },
          {
            path: "/material/createBox/modifyActInfo",
            meta: {
              label: "抬头文本解绑Box",
              icon: "",
            },
          },
          {
            path: "/material/createBox/modifyReceiveActNo",
            meta: {
              label: "删除抬头文本",
              icon: "",
            },
          },
        ],
      },
      // 物料入库
      {
        path: "/material/stockIn",
        meta: {
          label: "物料入库",
          icon: "",
        },
        children: [
          {
            path: "/material/stockIn/normalStockIn",
            meta: {
              label: "PO入库",
              icon: "",
            },
          },
          {
            path: "/material/stockIn/refundStockIn",
            meta: {
              label: "非PO入库",
              icon: "",
            },
          },
        ],
      },
      // 物料质检
      {
        path: "/material/OQA",
        meta: {
          label: "物料质检",
          icon: "",
        },
        children: [
          {
            path: "/material/OQA/noValueOQA",
            meta: {
              label: "质检手工判断",
              icon: "",
            },
          },
        ],
      },
      // 物料在库
      {
        path: "/material/stocked",
        meta: {
          label: "物料在库",
          icon: "",
        },
        children: [
          {
            path: "/stocked/locationMove",
            meta: {
              label: "库位移动",
              icon: "",
            },
          },
          {
            path: "/material/stocked/mergeBox",
            meta: {
              label: "Box合并",
              icon: "",
            },
          },
          {
            path: "/material/stocked/splitBox",
            meta: {
              label: "Box拆分",
              icon: "",
            },
          },
          {
            path: "/material/stocked/holdAndRelease",
            meta: {
              label: "Hold/Release",
              icon: "",
            },
          },
          {
            path: "/material/stocked/makeUndo",
            meta: {
              label: "物料冲销",
              icon: "",
            },
          },
          {
            path: "/material/stocked/preScrap",
            meta: {
              label: "物料预报废",
              icon: "",
            },
          },
          {
            path: "/material/stocked/scrap",
            meta: {
              label: "物料报废",
              icon: "",
            },
          },
        ],
      },
      // 物料出库
      {
        path: "/material/stockOut",
        meta: {
          label: "物料出库",
          icon: "",
        },
        children: [
          {
            path: "/material/stockOut/shipRequestReserve",
            meta: {
              label: "预约拣配",
              icon: "",
            },
          },
          {
            path: "/material/stockOut/shipRequestConfirm",
            meta: {
              label: "确认拣配",
              icon: "",
            },
          },
          {
            path: "/material/stockOut/manualStockOut",
            meta: {
              label: "出库",
              icon: "",
            },
          },
          {
            path: "/material/stockOut/POReturn",
            meta: {
              label: "入库PO返厂",
              icon: "",
            },
          },
          {
            path: "/material/stockOut/RMAReturn",
            meta: {
              label: "退货PO返厂",
              icon: "",
            },
          },
        ],
      },
    ],
  },
  // 成品管理
  {
    path: "/product",
    meta: {
      label: "成品管理",
      icon: "",
    },
    children: [
      {
        path: "/product/productQuery",
        meta: {
          label: "信息查询",
          icon: "",
        },
        children: [
          {
            path: "/product/productQuery/productShipRequestQuery",
            meta: {
              label: "发货单据查询",
              icon: "",
            },
          },
          {
            path: "/product/productQuery/PalletInventoryView",
            meta: {
              label: "Pallet库存查询",
              icon: "",
            },
          },
          {
            path: "/product/productQuery/periodInOutQuery",
            meta: {
              label: "期间In/Out查询",
              icon: "",
            },
          },
          {
            path: "/product/productQuery/reservedShippedQuery",
            meta: {
              label: "已拣配待发货查询",
              icon: "",
            },
          },
          {
            path: "/product/productQuery/productPreStockedQuery",
            meta: {
              label: "待入库看板",
              icon: "",
            },
          },
          {
            path: "/product/productQuery/PalletBoxStockedQuery",
            meta: {
              label: "Pallet出入库查询",
              icon: "",
            },
          },
        ],
      },
      {
        path: "/product/print",
        meta: {
          label: "成品入库",
          icon: "",
        },
        children: [
          {
            path: "/label/preStockedBoxLabelPrint",
            meta: {
              label: "待入库Box标签打印",
              icon: "",
            },
          },
          {
            path: "/label/multi_BoxLabelPrint",
            meta: {
              label: "批量打印Box标签",
              icon: "",
            },
          },
          {
            path: "/label/reprint_BoxLabel",
            meta: {
              label: "重新打印Box标签",
              icon: "",
            },
          },
          {
            path: "/label/locationLabelPrint",
            meta: {
              label: "库位标签打印",
              icon: "",
            },
          },
          {
            path: "/label/PalletLabelPrint",
            meta: {
              label: "Pallet标签打印",
              icon: "",
            },
          },
        ],
      },
    ],
  },
  // 盘点管理
  {
    path: "/check",
    meta: {
      label: "盘点管理",
      icon: "",
    },
    children: [
      {
        path: "/check/checkWork",
        meta: {
          label: "盘点工作",
          icon: "",
        },
        children: [
          {
            path: "/check/buildSheet",
            meta: {
              label: "创建盘点单",
              icon: "",
            },
          },
          {
            path: "/check/checkWork/scanSheet",
            meta: {
              label: "盘点扫描",
              icon: "",
            },
          },
          {
            path: "/check/confirmSheet",
            meta: {
              label: "盘点结果",
              icon: "",
            },
          },
          {
            path: "/check/auditSheet",
            meta: {
              label: "盘点审核",
              icon: "",
            },
          },
        ],
      },
    ],
  },
  // 系统设置
  {
    path: "/system",
    meta: {
      label: "系统设置",
      icon: "",
    },
    children: [
      {
        path: "/system/site",
        meta: {
          label: "工厂管理",
          icon: "",
        },
      },
      {
        path: "/system/user",
        meta: {
          label: "用户管理",
          icon: "",
        },
      },
      {
        path: "/system/role",
        meta: {
          label: "角色管理",
          icon: "",
        },
      },
      {
        path: "/system/resource",
        meta: {
          label: "菜单管理",
          icon: "",
        },
      },
    ],
  },
]);

const useAppStore = defineStore({
  id: "app",
  state: (): AppState => ({
    menuMode: localStorage.get("menuMode") ? JSON.parse(localStorage.get("menuMode")) : "vertical",
    sidebar: {
      opened: true,
    },
    language: getLanguage(),
    size: localStorage.get("size") || "default",
    buttons: [],
    currentPath: "",
    menuList: [], //接口返回的菜单列表
    routes: [], // 基于菜单列表生成路由
    firstMenu: "",
    secondMenu: [],
  }),
  getters: {
    getRoutes(state) {
      return state.routes
    },
    getMenu(state) {
      return state.menuList
    }
  },
  actions: {
    changeMenuMode(mode: string) {
      localStorage.set("menuMode", mode);
      this.menuMode = mode;
    },
    toggleSidebar() {
      this.sidebar.opened = !this.sidebar.opened;
    },
    setLanguage(language: string) {
      this.language = language;
      localStorage.set("language", language);
    },
    setFirstMenu(id: any) {
      this.firstMenu = id;
    },
    setSecondMenu(SecondMenu: any) {
      this.secondMenu = SecondMenu;
    },
    // getAllMenu() {
    //   // 获取所有菜单
    //   return new Promise(async (resolve, reject) => {
    //     allMenuApi({
    //       platform: 1,
    //     })
    //       .then((res) => {
    //         this.routes = res.data;
    //         localStorage.set("menus", this.routes);
    //         resolve(res.data);
    //       })
    //       .catch((error) => {
    //         reject(error);
    //       });
    //   });
    // },
    getAllButton(path: any) {
      // 获取所有菜单
      const routes = localStorage.get("menus");
      const id = this.getPathId(routes, path);
      return new Promise((resolve, reject) => {
        allButtonApi({
          dataId: id,
        })
          .then((res) => {
            this.buttons = res.data;
            resolve(res.data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    getPathId(routes: any, path: any): any {
      for (let i = 0; i < routes.length; i++) {
        const item = routes[i];
        if (path === item.relObj.url) {
          return item.relObj.dataId;
        } else {
          if (item.children && item.children.length > 0) {
            return this.getPathId(item.children, path);
          }
        }
      }
    },

    /**
     * 获取菜单
     * */
    getMenuList() {
      return allMenuApi({
        queryId: "GetHierarchicalMenuOfPermissionList",
        version: "sdk001",
        params: {
          USERID: useUserStore().getUserId(),
          PLATFORM:"PC"
        }
      })
        .then((res) => {
          this.menuList = res.data.menuList;
          return res.data.menuList
        })
        .catch((error) => {

        });
    },
    /**
     * 生成路由表
     * */
    generateRoutes(menuList: any) {
      return new Promise(resolve => {
        const asyncRoutes = convertAsyncRoutes(menuList) || [];
        const firstVisibleRoute: any = this.execFirstRoute(asyncRoutes)
        if (firstVisibleRoute) {
          // 设置home路由重定向
          homeRoute.redirect = firstVisibleRoute.path;
          asyncRoutes.push(homeRoute);
        }
        // 添加404兜底路由
        asyncRoutes.push(notFoundRoute);
        this.routes = asyncRoutes
        console.log('roote',this.routes)
        resolve(asyncRoutes);
      });
    },
    execFirstRoute(routes: any) {
      let flag: boolean = false
      routes.map((m: any) => {
        if (m.children && m.children.length > 0) {
          if (!flag) {
            flag = this.execFirstRoute(m.children)
          }
        } else {
          if (!flag && m.meta.leafFlag) {
            flag = m
          }
        }
      })
      return flag
    }
  },
});

export default useAppStore;
