account.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { computed, toRefs, shallowReadonly } from 'vue'
  2. import { queryTaAccounts } from '@/services/api/account'
  3. import { useLoginStore } from './login'
  4. import { VueStore } from '../base'
  5. import eventBus from '@/services/bus'
  6. interface StoreState {
  7. loading: boolean;
  8. accountList: Ermcp.TaAccountsRsp[]; // 资金账户列表
  9. currentAccountId: number; // 当前资金账户ID
  10. }
  11. /**
  12. * 账号存储类
  13. */
  14. const store = new (class extends VueStore<StoreState> {
  15. constructor() {
  16. const state: StoreState = {
  17. loading: false,
  18. accountList: [],
  19. currentAccountId: 0,
  20. }
  21. super(state)
  22. // 接收资金变动通知
  23. eventBus.$on('MoneyChangedNotify', () => {
  24. this.actions.getAccountList()
  25. })
  26. }
  27. /** 当前资金账户信息 */
  28. private currentAccountInfo = computed(() => {
  29. return this.state.accountList.find((e) => e.accountid === this.state.currentAccountId)
  30. })
  31. getters = {
  32. currentAccountInfo: this.currentAccountInfo
  33. }
  34. actions = {
  35. /** 获取资金账户列表 */
  36. getAccountList: () => {
  37. const { getLoginId } = useLoginStore()
  38. this.state.loading = true
  39. return queryTaAccounts({
  40. data: {
  41. loginID: getLoginId()
  42. },
  43. success: (res) => {
  44. const dataList = res.data
  45. if (dataList.length) {
  46. this.state.accountList = dataList
  47. // 查找当前选中的资金账户
  48. const account = dataList.find((e) => e.accountid === this.state.currentAccountId)
  49. if (account) {
  50. this.state.loading = false
  51. } else {
  52. // 如果不存在,默认选中第一个账户
  53. this.state.currentAccountId = dataList[0].accountid
  54. }
  55. } else {
  56. this.state.loading = false
  57. this.actions.reset()
  58. }
  59. },
  60. fail: () => {
  61. this.state.loading = false
  62. }
  63. })
  64. },
  65. /** 重置数据 */
  66. reset: () => {
  67. this.state.accountList = []
  68. this.state.currentAccountId = 0
  69. }
  70. }
  71. })
  72. export function useAccountStore() {
  73. return shallowReadonly({
  74. ...toRefs(store.state),
  75. ...store.getters,
  76. ...store.actions,
  77. ...store.methods,
  78. })
  79. }