/**
 * 服务器地址模块
 */
import { Module, VuexModule, Mutation, Action, getModule } from 'vuex-module-decorators';
import { stringify } from 'query-string';
import store, { persistedKey } from '@/store';
import http from '@/utils/request';
import { url } from '@/utils/url';

// 是否有已持久化的数据，只有当 storage 里有 key 时恢复 state
// 否则会出现操作 state 的方法的 state 为 undefined 的情况
const getHasPersisted = () => {
  try {
    const hasPersisted = JSON.parse(uni.getStorageSync(persistedKey)).server != null;
    if (hasPersisted) {
      (http as any).config.baseURL = JSON.parse(uni.getStorageSync(persistedKey)).server.address;
    }
    return hasPersisted;
  } catch {
    return false;
  }
};

@Module({
  dynamic: true,
  store,
  namespaced: true,
  name: 'server',
  preserveState: getHasPersisted(),
})
class Server extends VuexModule {
  // 服务器地址
  private address: string | null = null;

  // 测试服务器是否可用
  @Action({ rawError: true })
  async isServerAlive({ host, port }: { host: string; port: number | null }) {
    const oldBaseUrl = (http as any).config.baseURL;
    (http as any).config.baseURL = port ? host + ':' + port : host;
    try {
      const result = await http.post(
        url.wmspda.system.test,
        stringify({
          ipText: host,
          portText: port,
        }),
      );
      return Boolean(result);
    } finally {
      (http as any).config.baseURL = oldBaseUrl;
    }
  }

  // 获取服务器地址
  get serverAddress() {
    return this.address;
  }

  // 服务器地址是否已设置
  get isServerAddressSet() {
    return !(this.address == null || this.address === '');
  }

  // 设置服务器地址
  @Mutation
  setServerAddress({ address }: { address: string }) {
    (http as any).config.baseURL = address;
    this.address = address;
  }
}

export const server = getModule(Server);
