package com.ruoyi.dk.kit;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.component.tenant.helper.TenantHelper;
import com.ruoyi.dk.domain.Customer;
import com.ruoyi.dk.executor.ExecutorConstant;
import com.ruoyi.dk.service.CustomerService;
import com.ruoyi.component.core.constant.Constants;
import com.ruoyi.component.core.domain.model.LoginUser;
import com.ruoyi.component.core.enums.UserType;
import com.ruoyi.component.core.exception.base.BaseException;
import com.ruoyi.component.satoken.utils.LoginHelper;
import com.ruoyi.component.core.util.MessageUtils;
import com.ruoyi.component.core.util.ServletUtils;
import com.ruoyi.system.service.SysLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Collections;

@Component
@Slf4j
public class DkLoginKit {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private SysLoginService sysLoginService;

    public String login(String mobile,String password) {
        Customer customer = customerService.getCustomerByName(mobile);
        if(customer == null){
            log.info("登录用户：{} 不存在.", mobile);
            throw new BaseException(MessageUtils.message("login.user.not",mobile));
        }
        if(!BCrypt.checkpw(password, customer.getPassword())){
            throw new BaseException(MessageUtils.message("login.user.fail"));
        }
        if (customer.getStatus() == 1) {
            log.info("登录用户：{} 已被停用.", mobile);
            throw new BaseException(MessageUtils.message("login.user.stop",mobile));
        }
        ExecutorConstant.SYNC_EXECUTOR.execute(() -> {
            updateCustomer(customer);
        });
        return login(customer);
    }

    private void updateCustomer(Customer customer){
        Customer update  = new Customer();
        update.setId(customer.getId());
        update.setLastLoginIp(ServletUtils.getClientIP());
        update.setLastLoginTime(LocalDateTime.now());
        customerService.updateById(update);
    }

    private String login(Customer user){
        LoginUser loginUser = new LoginUser();
        loginUser.setDeptId(null);
        loginUser.setDeptName(null);
        loginUser.setMenuPermission(Collections.emptySet());
        loginUser.setRolePermission(Collections.emptySet());
        loginUser.setUsername(user.getPhoneNumber());
        loginUser.setRoles(Collections.emptyList());
        loginUser.setRoleId(null);
        loginUser.setUserId(user.getId());
        loginUser.setUserType(UserType.APP_USER.getUserType());
        loginUser.setTenantId(user.getTenantId());
        LoginHelper.login(loginUser);
        sysLoginService.recordLogininfor(loginUser.getUsername(), UserType.APP_USER.getUserType(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
        return StpUtil.getTokenValue();
    }

}
