package com.cpop.core.strategy.login;

import com.cpop.common.constant.Constants;
import com.cpop.common.utils.StringUtils;
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.MallStaffLoginInfo;
import com.cpop.core.base.enums.InitRoleEnum;
import com.cpop.core.base.enums.SourceType;
import com.cpop.core.base.enums.UserType;
import com.cpop.core.base.exception.CpopAuthenticationException;
import com.cpop.core.base.table.SysUser;
import com.mybatisflex.core.row.DbChain;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.row.RowUtil;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author DB
 * @createTime 2023/11/08 10:12
 * @description 商城员工登陆策略
 */
@Component
public class MallLoginStrategy implements LoginStrategy{

    /**
     * @descriptions 获取登陆用户信息
     * @author DB
     * @date 2023/11/08 9:34
     * @param sysUser 系统用户
     * @param credentials 登陆相关凭着
     * @return: com.cpop.core.base.entity.LoginUser
     */
    @Override
    public LoginUser getLoginUserInfo(SysUser sysUser, Map<String, Object> credentials) {
        //构建登陆员工信息
        MallStaffLoginInfo staffLoginInfo = BeanUtils.mapToClass(sysUser, MallStaffLoginInfo.class);
        staffLoginInfo.setUserId(sysUser.getId());
        //构建员工
        if (!staffLoginInfo.getUserName().equals(Constants.SUPER_ADMIN)) {
            Row row = DbChain.table("cp_mall_staff")
                    .select("cms.id", "cms.name", "cms.user_id","cms.source_type")
                    .select("cmrb.role_id", "cmrb.brand_id")
                    .from("cp_mall_staff").as("cms")
                    .leftJoin("cp_mall_role_brand").as("cmrb").on("cmrb.id = cms.role_brand_id")
                    .where("cms.user_id = ?", staffLoginInfo.getUserId())
                    .and("cms.is_delete = 0")
                    .one();
            if (row == null) {
                throw new CpopAuthenticationException("获取登陆用户信息失败,请核实!");
            }
            staffLoginInfo.setRoleId(row.getString("roleId"));
            staffLoginInfo.setName(row.getString("name"));
            staffLoginInfo.setId(row.getString("id"));
            staffLoginInfo.setBrandId(row.getString("brandId"));
            staffLoginInfo.setSourceType(SourceType.valueOf(row.getString("sourceType")));
        } else {
            //超级管理员
            staffLoginInfo.setId(Constants.SUPER_ADMIN_ID).setName(Constants.SUPER_ADMIN).setSourceType(SourceType.COMMON);
        }
        LoginUser loginUser = new LoginUser(staffLoginInfo, staffLoginInfo.getId(), getPermissionSet(sysUser.getUserName(), staffLoginInfo.getRoleId()));
        loginUser.setUserId(sysUser.getId())
                .setUserType(UserType.MALL_USER)
                .setUserName(sysUser.getUserName())
                .setLoginTime(System.currentTimeMillis())
                .setStatus(sysUser.getStatus());
        return loginUser;
    }

    /**
     * @descriptions 获取权限列表
     * @author DB
     * @date 2023/11/08 9:37
     * @param username 用户名
     * @param roleId 角色id
     * @return: java.util.Set<java.lang.String>
     */
    private Set<String> getPermissionSet(String username, String roleId) {
        //获取权限
        Set<String> permissionSet = new HashSet<>();
        if (Constants.SUPER_ADMIN.equals(username) || StringUtils.equals(InitRoleEnum.SUPER_MALL_ROLE.getId(), roleId)) {
            permissionSet.add(Constants.ALL_PERMISSION);
        } else {
            //查询员工信息
            List<Row> list = DbChain.table("cp_sys_menu")
                    .select("pom.permission")
                    .from("cp_sys_menu").as("pom")
                    .leftJoin("cp_sys_role_menu").as("porm").on("porm.menu_id = pom.id")
                    .where("pom.type in (1,2)")
                    .and("porm.role_id = ?", roleId)
                    .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());
            }
        }
        return permissionSet;
    }
}
