import { Action, getModule, Module, VuexModule } from 'vuex-module-decorators';
import request from '@/utils/request';
import store from '@/store';
import { User } from '@/store/modules/session';
import { url } from '@/utils/url';

export interface UserInfo {
  factoryCode: string;
  factoryName: string;
  factoryType?: any;
  warehouseCode?: any;
  warehouseName?: any;
  warehouseType?: any;
  loginName: string;
  userName: string;
  sapFactoryCode?: any;
  locationCode?: any;
  workareaCode?: any;
}

@Module({
  dynamic: true,
  store,
  namespaced: true,
  name: 'auth',
})
class AuthService extends VuexModule {
  @Action
  async getUserInfo({ loginName }: { loginName: User['loginName'] }): Promise<UserInfo> {
    const r: any = await request.post(url.auth.userInfo, {
      loginName,
    });
    if (r.code !== '1') {
      throw new Error(r.msg);
    } else {
      return r.list[0];
    }
  }

  @Action
  async checkPassword({
    rfPwd,
    factoryCode,
    loginName,
  }: {
    rfPwd: string;
    factoryCode: User['factoryCode'];
    loginName: User['loginName'];
  }) {
    const r: any = await request.post(url.auth.pwd.check, {
      rfPwd,
      factoryCode,
      loginName,
    });
    if (r.code !== '1') {
      throw new Error(r.msg);
    } else {
      return r;
    }
  }
}

export const auth = getModule(AuthService);
