package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.dz.domain.DzAgent;
import com.ruoyi.dz.domain.DzCards;
import com.ruoyi.dz.service.IDzAgentService;
import com.ruoyi.dz.service.IDzCardsService;
import com.ruoyi.dz.service.IDzSchoolService;
import com.ruoyi.dz.service.IDzClassesService;
import com.ruoyi.enums.CardType;
import com.ruoyi.enums.UserTypeEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private IDzCardsService cardsService;
    @Autowired
    private IDzSchoolService schoolService;
    @Autowired
    private IDzClassesService classesService;
    @Autowired
    private IDzAgentService agentService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        // 批量查询 password2 并设置到用户对象中
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> userIds = list.stream()
                    .map(SysUser::getUserId)
                    .filter(userId -> userId != null)
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(userIds)) {
                Map<Long, String> password2Map = userService.selectPassword2ByUserIds(userIds);
                for (SysUser sysUser : list) {
                    if (sysUser.getUserId() != null && password2Map.containsKey(sysUser.getUserId())) {
                        sysUser.setPassword2(password2Map.get(sysUser.getUserId()));
                    }
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/listCard")
    public TableDataInfo listCard(SysUser user)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (UserTypeEnum.isAgent(sysUser.getUserType())) {
            user.setAgentId(sysUser.getUserTypeId());
        } else if (UserTypeEnum.isInstitution(sysUser.getUserType())) {
            user.setDeptId(sysUser.getDeptId());
            user.setInviteDeptId(sysUser.getDeptId());
        } else if(!UserTypeEnum.isSys(sysUser.getUserType())) {
            user.setDeptId(sysUser.getDeptId());
        }
        //只显示普通用户
        user.setUsercardType(String.valueOf(CardType.Common.getVal()));
        startPage();
        List<SysUser> list = userService.selectCardUserList(user);
        // 先获取分页信息，再处理数据
        TableDataInfo dataTable = getDataTable(list);
        // 处理用户信息（填充学校名称、班级名称等）
        list = processUserInfo(list);
        dataTable.setRows(list);
        return dataTable;
    }

    private List<SysUser> processUserInfo(List<SysUser> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            // 批量查询 password2 并设置到用户对象中
            List<Long> userIds = list.stream()
                    .map(SysUser::getUserId)
                    .filter(userId -> userId != null)
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(userIds)) {
                Map<Long, String> password2Map = userService.selectPassword2ByUserIds(userIds);
                for (SysUser sysUser : list) {
                    if (sysUser.getUserId() != null && password2Map.containsKey(sysUser.getUserId())) {
                        sysUser.setPassword2(password2Map.get(sysUser.getUserId()));
                    }
                }
            }

            // 获取邀请码列表（邀请码是String类型，需要转换为Long类型的用户ID）
            List<Long> inviteCodeUserIds = list.stream()
                    .map(SysUser::getInviteCode)
                    .filter(inviteCode -> StringUtils.isNotEmpty(inviteCode))
                    .map(inviteCode -> {
                        try {
                            return Long.parseLong(inviteCode);
                        } catch (NumberFormatException e) {
                            return null;
                        }
                    })
                    .distinct().collect(Collectors.toList());
            List<Long> cardIds = list.stream().map(SysUser::getCardId).filter(cardId -> cardId != null)
                    .distinct().collect(Collectors.toList());

            // 根据邀请码（即用户ID）查询对应的代理商信息
            Map<Long, DzAgent> agentMap = new java.util.HashMap<>();
            if (CollectionUtils.isNotEmpty(inviteCodeUserIds)) {
                List<DzAgent> agentList = agentService.selectDzAgentByAgentIds(inviteCodeUserIds);
                if (CollectionUtils.isNotEmpty(agentList)) {
                    agentMap = agentList.stream().collect(Collectors.toMap(DzAgent::getAgentId,agent -> agent,(existing, replacement) -> existing));
                }
            }

            // 如果cardIds为空，直接返回，不进行后续处理
            if (CollectionUtils.isEmpty(cardIds)) {
                // 即使没有cardIds，也要设置代理商名称
                for (SysUser user : list) {
                    //设置卡类型
                    user.setUsercardType(String.valueOf(CardType.getNewVal(CardType.Common.getVal())));
                    if (user.getInviteCode() != null && !user.getInviteCode().isEmpty()) {
                        try {
                            Long inviteCodeUserId = Long.parseLong(user.getInviteCode());
                            DzAgent agent = agentMap.get(inviteCodeUserId);
                            if (agent != null && agent.getName() != null) {
                                user.setAgentName(agent.getName());
                                user.setDeptName(null!=agent.getDept()?agent.getDept().getDeptName():StringUtils.EMPTY);
                            }
                        } catch (NumberFormatException e) {
                            // 邀请码不是有效的数字，忽略
                        }
                    }
                }
                return list;
            }

            List<DzCards> cards = cardsService.selectCardsByCardIds(cardIds);
            //将里面的campusId与schoolId汇总为一个list后，通过schoolService查询所有学校的信息List<DzSchool>
            List<Long> schoolIds = cards.stream().map(DzCards::getSchoolId).filter(schoolId -> schoolId != null).collect(Collectors.toList());
            List<Long> campusIds = cards.stream().map(DzCards::getCampusId).filter(campusId -> campusId != null).collect(Collectors.toList());
            // 合并schoolId和campusId，并去重
            List<Long> allIds = new java.util.ArrayList<>(schoolIds);
            allIds.addAll(campusIds);
            List<Long> distinctIds = allIds.stream().distinct().collect(Collectors.toList());
            Map<Long, String> schoolMap = new java.util.HashMap<>();
            if (CollectionUtils.isNotEmpty(distinctIds)) {
                List<com.ruoyi.dz.domain.DzSchool> schoolList = schoolService.selectDzSchoolListByIds(distinctIds);
                if (CollectionUtils.isNotEmpty(schoolList)) {
                    schoolMap = schoolList.stream()
                            .collect(Collectors.toMap(dzSchool -> dzSchool.getId(), dzSchool -> dzSchool.getName()));
                }
            }

            //将里面的classId与campusClassId汇总为一个list后，通过classesService查询所有班级的信息List<DzClasses>
            List<Long> classIds = cards.stream().map(DzCards::getClassId).filter(classId -> classId != null).collect(Collectors.toList());
            List<Long> campusClassIds = cards.stream().map(DzCards::getCampusClassId).filter(campusClassId -> campusClassId != null).collect(Collectors.toList());
            // 合并classId和campusClassId，并去重
            List<Long> allClassIds = new java.util.ArrayList<>(classIds);
            allClassIds.addAll(campusClassIds);
            List<Long> distinctClassIds = allClassIds.stream().distinct().collect(Collectors.toList());
            Map<Long, String> classMap = new java.util.HashMap<>();
            if (CollectionUtils.isNotEmpty(distinctClassIds)) {
                List<com.ruoyi.dz.domain.DzClasses> classList = classesService.selectDzClassesListByIds(distinctClassIds);
                if (CollectionUtils.isNotEmpty(classList)) {
                    classMap = classList.stream()
                            .collect(Collectors.toMap(dzClass -> dzClass.getClassId(), dzClass -> dzClass.getName()));
                }
            }

            // 创建cardId到DzCards的映射，方便后续查找
            Map<Long, DzCards> cardMap = new java.util.HashMap<>();
            if (CollectionUtils.isNotEmpty(cards)) {
                cardMap = cards.stream()
                        .collect(Collectors.toMap(DzCards::getCardId, card -> card, (existing, replacement) -> existing));
            }

            // 遍历用户列表，设置学校名称和班级名称
            for (SysUser user : list) {
                // 设置代理商名称（从dept对象中获取）
                if (user.getDept() != null && user.getDept().getDeptName() != null) {
                    user.setDeptName(user.getDept().getDeptName());
                }
                // 设置代理商名称（从邀请码对应的代理商获取）
                if (user.getInviteCode() != null && !user.getInviteCode().isEmpty()) {
                    try {
                        Long inviteCodeUserId = Long.parseLong(user.getInviteCode());
                        DzAgent agent = agentMap.get(inviteCodeUserId);
                        if (agent != null && agent.getName() != null) {
                            user.setAgentName(agent.getName());
                            user.setDeptName(null!=agent.getDept()?agent.getDept().getDeptName():StringUtils.EMPTY);
                        }
                    } catch (NumberFormatException e) {
                        // 邀请码不是有效的数字，忽略
                    }
                }
                if (user.getCardId() != null) {
                    DzCards card = cardMap.get(user.getCardId());
                    if (card != null) {
                        user.setCardNo(card.getCardNo());
                        //设置卡类型
                        user.setUsercardType(String.valueOf(CardType.getNewVal(card.getType())));
                        // 设置注册学校名称（schoolId对应的学校名称）
                        if (card.getSchoolId() != null) {
                            user.setSchoolName(schoolMap.get(card.getSchoolId()));
                        }
                        // 设置学校班级名称（classId对应的班级名称）
                        if (card.getClassId() != null) {
                            user.setSchoolClassName(classMap.get(card.getClassId()));
                        }
                        // 设置培训校区名称（campusId对应的学校名称）
                        if (card.getCampusId() != null) {
                            user.setCampusName(schoolMap.get(card.getCampusId()));
                        }
                        // 设置校区班级名称（campusClassId对应的班级名称）
                        if (card.getCampusClassId() != null) {
                            user.setCampusClassName(classMap.get(card.getCampusClassId()));
                        }
                    }else {
                        user.setUsercardType(String.valueOf(CardType.getNewVal(CardType.Common.getVal())));
                    }
                }else {
                    user.setUsercardType(String.valueOf(CardType.getNewVal(CardType.Common.getVal())));
                }
            }

        }
        return list;
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        list = processUserInfo(list);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(userId))
        {
            userService.checkUserDataScope(userId);
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword2(SecurityUtils.encryptPassword2(user.getPassword()));
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return AjaxResult.success(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        if (StringUtils.isEmpty(user.getPassword()))
        {
            return AjaxResult.error("密码不能为空");
        }
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword2(SecurityUtils.encryptPassword2(user.getPassword()));
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 清空用户定向信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/clearDirectedStudy/{userId}")
    public AjaxResult clearDirectedStudy(@PathVariable("userId") Long userId)
    {
        userService.checkUserDataScope(userId);
        return toAjax(userService.clearDirectedStudy(userId));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        roleService.checkRoleDataScope(roleIds);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取机构树列表
     */
    // @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }

    /**
     * 获取省份列表（去重）
     */
    @GetMapping("/locations")
    public AjaxResult getLocations()
    {
        List<String> locations = userService.selectDistinctLocations();
        return success(locations);
    }
}
