package com.cpop.core.service.impl;

import com.cpop.common.constant.Constants;
import com.cpop.common.utils.bean.BeanUtils;
import com.cpop.core.base.entity.LoginUser;
import com.cpop.core.base.entity.Permission;
import com.cpop.core.base.entity.loginInfo.OamStaffLoginInfo;
import com.cpop.core.base.enums.UserType;
import com.cpop.core.base.table.SysUser;
import com.cpop.core.service.CoreService;
import com.cpop.core.utils.MessageUtils;
import com.mybatisflex.core.row.DbChain;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.row.RowUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author DB
 * @createTime 2023/09/11 10:56
 * @description oam员工登陆信息
 */
@Service("oamStaffDetailsService")
public class OamStaffDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private CoreService coreService;

    /**
     * @descriptions 加载员工信息
     * @author DB
     * @date 2023/09/11 10:57
     * @param username 用户名
     * @return org.springframework.security.core.user.details.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //统一获取系统用户信息
        SysUser sysUser = coreService.getSysUserByUsername(username, UserType.OAM_USER);
        if (sysUser == null) {
            throw new UsernameNotFoundException(MessageUtils.message("i18n_alert_accountOrPwdError"));
        }
        //构建登陆员工信息
        OamStaffLoginInfo staffLoginInfo = BeanUtils.mapToClass(sysUser, OamStaffLoginInfo.class);
        staffLoginInfo.setUserId(sysUser.getId());
        //员工
        if (!staffLoginInfo.getUserName().equals(Constants.SUPER_ADMIN)) {
            Row row = DbChain.table("cp_oam_staff")
                    .select()
                    .where("user_id = ?", staffLoginInfo.getUserId())
                    .one();
            staffLoginInfo.setDeptId(row.getString("deptId"));
            staffLoginInfo.setRoleId(row.getString("roleId"));
            staffLoginInfo.setName(row.getString("name"));
            staffLoginInfo.setStaffType(row.getInt("staffType"));
            staffLoginInfo.setId(row.getString("id"));
        }
        //获取权限
        Set<String> permissionSet = new HashSet<>();
        if (Constants.SUPER_ADMIN.equals(username)) {
            permissionSet.add(Constants.ALL_PERMISSION);
            staffLoginInfo.setName(Constants.SUPER_ADMIN);
        }
        else {
        //查询员工信息
            List<Row> list = DbChain.table("oam_menu")
                    .select("pom.permission")
                    .from("cp_oam_menu").as("pom")
                    .leftJoin("cp_oam_role_menu").as("porm").on("porm.menu_id = pom.id")
                    .where("pom.type in (1,2)")
                    .and("porm.role_id = ?", staffLoginInfo.getRoleId())
                    .and("pom.permission is not null")
                    .list();
            if (list.isEmpty()) {
                permissionSet = new HashSet<>();
            } else {
                List<Permission> permissions = RowUtil.toEntityList(list, Permission.class);
                permissionSet = permissions.stream().map(Permission::getPermission).collect(Collectors.toSet());
            }
        }
        LoginUser loginUser = new LoginUser(sysUser.getId(), staffLoginInfo, permissionSet);
        loginUser.setUserName(username)
                .setLoginTime(System.currentTimeMillis())
                .setStatus(sysUser.getStatus());
        return loginUser;
    }

}
