data.ts 2.72 KB
import { forEach } from '/@/utils/helper/treeHelper';
import type { UserInfo } from '/#/store';
import { defineStore } from 'pinia';
import { store } from '/@/store';
import { RoleEnum } from '/@/enums/roleEnum';
import { exchangeTab } from '@/store/modules/user';

import {
  getApiData,
  getChartData,
  getSalesData,
  getCustomerSalesData,
} from '/@/api/project/global';
import { formatToDate } from '/@/utils/dateUtil';
import { watch } from 'vue';

interface UserState {
  userInfo: Nullable<UserInfo>;
  token?: string;
  roleList: RoleEnum[];
  sessionTimeout?: boolean;
  lastUpdateTime: number;
}

export const useDataStore = defineStore({
  id: 'app-data',
  state: (): UserState => ({
    // user info
    data: {},
    // token
    chartData: {},
    //销售额完成情况
    salesData: {},
    //每个客户销售额
    customerChartData1: {},
  }),
  getters: {
    getData(state) {
      return state.data;
    },
    getChartData(state) {
      return state.chartData;
    },
    getSalesData(state) {
      return state.salesData;
    },
    getCustomerChartData1(state) {
      return state.customerChartData1;
    },
  },
  actions: {
    setData(info) {
      this.data = info ? info : '';
    },
    setChartData(data) {
      this.chartData = data;
    },
    setSalesData(info) {
      this.salesData = info ? info : '';
    },
    setCustomerChartData1(data) {
      this.customerChartData1 = data;
    },

    async getFetchData(): Promise<any> {
      try {
        const data = await getApiData();
        this.data = data;
      } catch (error) {
        return Promise.reject(error);
      }
    },
    async getFetchData2(): Promise<any> {
      try {
        const data = await getSalesData();
        this.salesData = data;
      } catch (error) {
        return Promise.reject(error);
      }
    },
    async getFetchChartData(): Promise<any> {
      try {
        const data = await getChartData();
        const x = [],
          y = [];
        data.forEach((value) => {
          x.push(formatToDate(value.dateTime));
          y.push(value.orderCount);
        });
        this.chartData = { x, y };
      } catch (error) {
        return Promise.reject(error);
      }
    },
    async getCustomerSalesData1(): Promise<any> {
      try {
        const data = await getCustomerSalesData();

        const x = [],
          y = [],
          z = [];
        for (const key in data) {
          x.push(key);
          y.push(data[key].salesAmount);
          z.push(data[key].target);
        }
        this.customerChartData1 = { x, y, z };
      } catch (error) {
        return Promise.reject(error);
      }
    },
  },
});

// Need to be used outside the setup
export function useDataStoreWithOut() {
  return useDataStore(store);
}