package cn.cslg.pas.service;

import cn.cslg.pas.domain.AdminUser;
import cn.cslg.pas.common.utils.Response;
import cn.cslg.pas.common.utils.ResponseEnum;
import cn.cslg.pas.common.model.vo.AdminUserLoginVO;
import cn.cslg.pas.common.utils.StpAdminUtil;
import cn.hutool.crypto.SecureUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 管理员 服务类
 * </p>
 *
 * @author 王岩
 * @since 2022-03-25
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class AdminService {

    private final AdminUserService adminUserService;

    public String doLogin(AdminUserLoginVO params) {
        AdminUser adminUser = adminUserService.getAdminUserByUsername(params.getUsername());
        if (adminUser == null) {
            return Response.error(ResponseEnum.USERNAME_ERROR);
        }
        boolean isPassword = SecureUtil.md5(params.getPassword()).equals(adminUser.getPassword());
        if (!isPassword) {
            return Response.error(ResponseEnum.PASSWORD_ERROR);
        }
        StpAdminUtil.login(adminUser.getId());
        return Response.success(StpAdminUtil.getTokenValue());
    }

    public String changePassword(String oldPassword, String newPassword) {
        Integer adminId = StpAdminUtil.getLoginIdAsInt();
        AdminUser adminUser = adminUserService.getById(adminId);
        boolean isPassword = SecureUtil.md5(oldPassword).equals(adminUser.getPassword());
        if (!isPassword) {
            return Response.error("旧密码错误");
        }
        adminUser.setPassword(SecureUtil.md5(newPassword));
        adminUser.updateById();
        return Response.success(true);
    }

    public AdminUser getUserinfo() {
        Integer adminId = StpAdminUtil.getLoginIdAsInt();
        AdminUser adminUser = adminUserService.getById(adminId);
        adminUser.setPassword(null);
        return adminUser;
    }
}
