import { typeCast } from 'hpsfir-ts-extends';
import { UserAdminVo, UserClinetVo, UpdateProfileVo } from '@model/vo';
import { AutoWrite, Service } from 'hpsfir-ioc';
import { Log, Logger } from 'hpsfir-log';
import { BaseSnowflakeService, BaseUserService, BaseRoleAdminVo, BaseUserAuthVo } from 'hpsfir-managebase';
import { AfterOrmConn, HpsfirOrmContext, Transaction, HpsfirOrmQuery } from 'hpsfir-orm';
import { BeforeControllerStart, HpsfirControllerError } from 'hpsfir-controller';
import { ROLE_E } from '@model/enum';
import dayjs from 'dayjs';
import { BaseUserAdminVo, BasePageQueryVo, BasePageVo } from 'hpsfir-managebase/lib/model/vo';
import { UserMetaSpe } from '@/model/special';

@Service()
export class UserService {

  @AutoWrite()
  private baseUserService!: BaseUserService;

  @Log(Symbol(UserService.name))
  private logger!: Logger;

  @AutoWrite()
  private baseSnowflakeService!: BaseSnowflakeService;


  public roleIdMap?: any;

  // 初始化用户
  @AfterOrmConn(10)
  private async initUser() {
    try {
      const roles: BaseRoleAdminVo[] = [
        {
          // 管理员管理所有店铺
          key: ROLE_E.ADMIN,
          name: '管理员',
        },
        {
          key: ROLE_E.USER,
          name: '用户',
        },
      ];

      const nowRoles = (await this.baseUserService.listRoles({})) || [];
      for (const role of roles) {
        if (nowRoles.find((item: any) => item.key === role.key)) {
          continue;
        }
        await this.baseUserService.addRole(role);
      }
      await this.getRolesId();

      const adminUser = (await this.baseUserService.listUsers({ username: 'admin' }) || []).find((item) => item.username === 'admin');
      this.logger.info('adminUser', adminUser);
      if (!adminUser) {
        const po = await this.baseUserService.addUser({
          username: 'admin',
          password: 'admin1234qwer!',
          roleIds: [this.roleIdMap?.[ROLE_E.ADMIN]],
        });
        this.logger.info('add adminUser success', po);
      }
    } catch (error) {
      this.logger.error('初始化用户失败', error);
    }
  }

  // 获取角色列表id
  private async getRolesId() {
    try {
      const roles = (await this.baseUserService.listRoles({})) || [];
      this.roleIdMap = {};
      for (const role of roles) {
        if (Object.values(ROLE_E).includes(role.key as ROLE_E)) {
          this.roleIdMap[role.key] = role.id;
          this.roleIdMap[String(role.id)] = role.key;
        }
      }
    } catch (error) {
      this.logger.error('获取角色列表id错误', error);
    }
  }


  // 服务端登录
  @Transaction()
  public async loginByBack(
    userId: number,
    ctx?: HpsfirOrmContext,
  ) {
    let baseUserVo = await this.baseUserService.findUser({
      id: userId,
    }, ctx);
    this.logger.info('登录客户', userId, baseUserVo);

    if (!baseUserVo) {
      this.logger.error('!登录客户，用户不存在', userId);
      throw new HpsfirControllerError(401);
    }


    const token = await this.baseUserService.generateToken(baseUserVo.id!, dayjs().add(7, 'day')
      .toDate(), ctx);

    const userClientVo = typeCast<UserClinetVo>(baseUserVo);
    userClientVo.token = token.token;
    return userClientVo;
  }

  /**
   * 查询用户（分页）
   */
  public async pageUsers(
    conditions: Partial<UserAdminVo>,
    pageQuery: BasePageQueryVo,
    ctx?: HpsfirOrmContext,
  ): Promise<BasePageVo<UserAdminVo>> {
    const baseConditions: Partial<BaseUserAdminVo> = {
      phone: conditions.phone,
      roleIds: conditions.roleKeys?.map((key: string) => this.roleIdMap?.[key]).filter((id: any) => id),
    };

    // 调用baseUserService的pageUsers方法
    const result = await this.baseUserService.pageUsers(
      baseConditions,
      pageQuery,
      ctx,
    );

    // 转换结果
    const userAdminVos: UserAdminVo[] = result.data.map((user: BaseUserAdminVo) => {
      const userVo = new UserAdminVo();
      userVo.id = user.id;
      // 确保phone不为undefined
      userVo.phone = user.phone || 0;
      userVo.username = user.username || '用户';
      userVo.meta = user.meta || {};
      userVo.createTime = user.createTime;
      // 从用户角色ID获取角色key
      userVo.roleKeys = (user.roleIds || []).map((roleId) => {
        const roleKey = Object.keys(this.roleIdMap || {}).find((key) => this.roleIdMap[key] === roleId);
        return roleKey || '';
      }).filter((key) => key);

      return userVo;
    }).filter((user) => user.roleKeys.includes(ROLE_E.USER) || user.roleKeys.includes(ROLE_E.ADMIN));


    return {
      data: userAdminVos,
      total: result.total,
    };
  }

  /**
   * 查询单个用户
   */
  public async findUser(
    userId: number,
    ctx?: HpsfirOrmContext,
  ): Promise<UserAdminVo | undefined> {
    // 调用基础服务查询用户
    const baseUserVo = await this.baseUserService.findUser({
      id: userId,
    }, ctx);

    if (!baseUserVo) {
      return undefined;
    }

    // 转换为 UserAdminVo
    const userVo = new UserAdminVo();
    userVo.id = baseUserVo.id;
    // 确保phone不为undefined
    userVo.phone = baseUserVo.phone || 0;
    userVo.username = baseUserVo.username || '用户';
    userVo.meta = baseUserVo.meta || {};
    userVo.createTime = baseUserVo.createTime;
    // 从用户角色ID获取角色key
    userVo.roleKeys = (baseUserVo.roleIds || []).map((roleId) => {
      const roleKey = Object.keys(this.roleIdMap || {}).find((key) => this.roleIdMap[key] === roleId);
      return roleKey || '';
    }).filter((key) => key);

    return userVo;
  }

  /**
   * 添加用户
   */
  @Transaction()
  public async addUser(
    userVo: UserAdminVo,
    ctx?: HpsfirOrmContext,
  ) {
    // 基本信息校验
    if (!userVo.phone && !userVo.username) {
      throw new HpsfirControllerError(400, '手机号或用户名不能为空');
    }

    if (!userVo.password) {
      // 如果没有提供密码，生成随机密码
      userVo.password = String(this.baseSnowflakeService.generateId());
    }

    // 转换为BaseUserAdminVo
    const baseUserVo: BaseUserAdminVo = {
      username: userVo.username,
      phone: userVo.phone,
      password: userVo.password,
      meta: userVo.meta || {},
      roleIds: [],
    };

    // 设置角色ID
    if (userVo.roleKeys && userVo.roleKeys.length > 0) {
      baseUserVo.roleIds = userVo.roleKeys.map((key: string) => this.roleIdMap?.[key]).filter((id: any) => id);
    } else {
      // 默认设置为普通用户角色
      baseUserVo.roleIds = [this.roleIdMap?.[ROLE_E.USER]];
    }

    try {
      // 调用基础服务添加用户
      const result = await this.baseUserService.addUser(baseUserVo, ctx);

      return result;
    } catch (error) {
      this.logger.error('添加用户失败', error);
      throw new HpsfirControllerError(500, '添加用户失败');
    }
  }

  /**
   * 更新用户
   */
  @Transaction()
  public async updateUser(
    userVo: UserAdminVo,
    ctx?: HpsfirOrmContext,
  ): Promise<void> {
    if (!userVo.id) {
      throw new HpsfirControllerError(400, '用户ID不能为空');
    }

    // 转换为BaseUserAdminVo
    const baseUserVo: BaseUserAdminVo = {
      id: userVo.id,
      username: userVo.username,
      phone: userVo.phone,
      meta: userVo.meta || {},
      roleIds: userVo.roleIds || [],
    };

    // 如果提供了密码，则更新密码
    if (userVo.password) {
      baseUserVo.password = userVo.password;
    }

    // 设置角色ID
    if (userVo.roleKeys && userVo.roleKeys.length > 0) {
      baseUserVo.roleIds = userVo.roleKeys.map((key: string) => this.roleIdMap?.[key]).filter((id: any) => id);
    }

    try {
      // 调用基础服务更新用户
      await this.baseUserService.updateUser(baseUserVo, ctx);
    } catch (error) {
      this.logger.error('更新用户失败', error);
      throw new HpsfirControllerError(500, '更新用户失败');
    }
  }

  /**
   * 删除用户
   */
  @Transaction()
  public async deleteUser(
    userId: number,
    ctx?: HpsfirOrmContext,
  ): Promise<void> {
    if (!userId) {
      throw new HpsfirControllerError(400, '用户ID不能为空');
    }

    try {
      // 调用基础服务删除用户
      await this.baseUserService.deleteUser(userId, ctx);
    } catch (error) {
      this.logger.error('删除用户失败', error);
      throw new HpsfirControllerError(500, '删除用户失败');
    }
  }

  /**
   * 更新用户个人信息
   */
  @Transaction()
  public async updateProfile(
    updateProfileVo: UpdateProfileVo,
    currentUser: BaseUserAuthVo,
    ctx?: HpsfirOrmContext,
  ): Promise<void> {
    if (!currentUser || !currentUser.id) {
      throw new HpsfirControllerError(401, '用户未登录');
    }

    try {
      // 获取当前用户信息
      const baseUserVo = await this.baseUserService.findUser({
        id: currentUser.id,
      }, ctx);

      if (!baseUserVo) {
        throw new HpsfirControllerError(404, '用户不存在');
      }

      // 更新用户元数据
      const currentMeta = (baseUserVo.meta as UserMetaSpe) || new UserMetaSpe();

      if (updateProfileVo.nickname !== undefined) {
        currentMeta.name = updateProfileVo.nickname;
      }

      if (updateProfileVo.avatar !== undefined) {
        currentMeta.avatar = updateProfileVo.avatar;
      }

      // 构建更新参数
      const updateUserVo: BaseUserAdminVo = {
        id: currentUser.id,
        meta: currentMeta,
        username: baseUserVo.username,
        phone: baseUserVo.phone,
        roleIds: baseUserVo.roleIds || [],
      };

      // 调用基础服务更新用户
      await this.baseUserService.updateUser(updateUserVo, ctx);

      this.logger.info('用户更新个人信息成功', { userId: currentUser.id, updateData: updateProfileVo });
    } catch (error) {
      this.logger.error('更新个人信息失败', error);
      if (error instanceof HpsfirControllerError) {
        throw error;
      }
      throw new HpsfirControllerError(500, '更新个人信息失败');
    }
  }

}
