package com.ruoyi.web.modules.account.service.impl;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.modules.account.constant.PlatformAdminConstants;
import com.ruoyi.web.modules.account.domain.PlatformAdminQuery;
import com.ruoyi.web.modules.account.domain.PlatformAdminRow;
import com.ruoyi.web.modules.account.dto.PlatformAdminCreateDTO;
import com.ruoyi.web.modules.account.dto.PlatformAdminUpdateDTO;
import com.ruoyi.web.modules.account.mapper.PlatformAdminMapper;
import com.ruoyi.web.modules.account.service.IPlatformAdminService;
import com.ruoyi.web.modules.account.support.PlatformAdminSupport;
import com.ruoyi.web.modules.account.vo.PlatformAdminDetailVO;
import com.ruoyi.web.modules.account.vo.PlatformAdminListVO;
import com.ruoyi.web.modules.account.vo.PlatformAdminRoleOptionVO;

/**
 * 平台管理员 Service 实现
 */
@Service
public class PlatformAdminServiceImpl implements IPlatformAdminService
{
    @Autowired
    private PlatformAdminMapper platformAdminMapper;

    @Autowired
    private PlatformAdminSupport platformAdminSupport;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserPostMapper sysUserPostMapper;

    @Override
    public List<PlatformAdminListVO> selectAdminList(PlatformAdminQuery query)
    {
        if (query == null)
        {
            query = new PlatformAdminQuery();
        }
        List<PlatformAdminRow> rows = platformAdminMapper.selectList(query);
        List<PlatformAdminListVO> result = new ArrayList<>();
        for (PlatformAdminRow row : rows)
        {
            result.add(toListVo(row));
        }
        return result;
    }

    @Override
    public PlatformAdminDetailVO selectAdminDetail(Long userId)
    {
        PlatformAdminRow row = platformAdminMapper.selectByUserId(userId, platformAdminSupport.listRoleKeys());
        if (row == null)
        {
            throw new ServiceException(PlatformAdminConstants.MSG_NOT_FOUND);
        }
        PlatformAdminDetailVO vo = new PlatformAdminDetailVO();
        vo.setUserId(row.getUserId());
        vo.setAdminName(platformAdminSupport.resolveAdminName(row.getNickName(), row.getUserName()));
        vo.setUserName(row.getUserName());
        vo.setPhonenumber(row.getPhonenumber());
        vo.setEmail(row.getEmail());
        vo.setAvatar(row.getAvatar());
        vo.setRoleNames(row.getRoleNames());
        vo.setCreateTime(row.getCreateTime());
        List<PlatformAdminRoleOptionVO> platformRoles = platformAdminMapper.selectPlatformRolesByUserId(userId,
                platformAdminSupport.listRoleKeys());
        vo.setRoleIds(platformAdminSupport.toPlatformRoleIdArray(platformRoles));
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createAdmin(PlatformAdminCreateDTO dto, String operator)
    {
        platformAdminSupport.validateCreate(dto);
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(PlatformAdminConstants.DEFAULT_DEPT_ID);
        sysUser.setUserName(dto.getUserName());
        sysUser.setNickName(dto.getAdminName());
        sysUser.setPhonenumber(dto.getPhonenumber());
        sysUser.setEmail(dto.getEmail());
        sysUser.setAvatar(dto.getAvatar());
        sysUser.setPassword(SecurityUtils.encryptPassword(dto.getPassword()));
        sysUser.setStatus(PlatformAdminConstants.STATUS_NORMAL);
        sysUser.setCreateBy(operator);
        sysUser.setRoleIds(dto.getRoleIds());
        if (!sysUserService.checkUserNameUnique(sysUser))
        {
            throw new ServiceException(PlatformAdminConstants.MSG_USERNAME_EXISTS);
        }
        if (!sysUserService.checkPhoneUnique(sysUser))
        {
            throw new ServiceException(PlatformAdminConstants.MSG_PHONE_EXISTS);
        }
        sysUserService.insertUser(sysUser);
        return sysUser.getUserId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAdmin(PlatformAdminUpdateDTO dto, Long currentUserId, String operator)
    {
        platformAdminSupport.validateUpdate(dto);
        platformAdminSupport.assertInListScope(dto.getUserId());
        SysUser existing = sysUserService.selectUserById(dto.getUserId());
        if (existing == null || !"0".equals(existing.getDelFlag()))
        {
            throw new ServiceException(PlatformAdminConstants.MSG_NOT_FOUND);
        }
        platformAdminSupport.assertEditableRoles(dto.getUserId(), dto.getRoleIds(), currentUserId);
        SysUser sysUser = new SysUser();
        sysUser.setUserId(dto.getUserId());
        sysUser.setUserName(existing.getUserName());
        sysUser.setNickName(dto.getAdminName());
        sysUser.setPhonenumber(dto.getPhonenumber());
        sysUser.setEmail(dto.getEmail());
        sysUser.setAvatar(dto.getAvatar());
        sysUser.setUpdateBy(operator);
        if (!sysUserService.checkPhoneUnique(sysUser))
        {
            throw new ServiceException(PlatformAdminConstants.MSG_PHONE_EXISTS);
        }
        sysUser.setRoleIds(platformAdminSupport.mergeRoleIdsOnUpdate(dto.getUserId(), dto.getRoleIds()));
        sysUserService.updateUser(sysUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAdmin(Long[] userIds, Long currentUserId)
    {
        List<SysUser> usersToDelete = new ArrayList<>();
        for (Long userId : userIds)
        {
            SysUser user = sysUserService.selectUserById(userId);
            if (user != null)
            {
                usersToDelete.add(user);
            }
        }
        platformAdminSupport.assertDeletable(userIds, currentUserId, usersToDelete);
        for (Long userId : userIds)
        {
            sysUserRoleMapper.deleteUserRoleByUserId(userId);
            sysUserPostMapper.deleteUserPostByUserId(userId);
            sysUserMapper.deleteUserById(userId);
        }
    }

    @Override
    public List<PlatformAdminRoleOptionVO> selectRoleOptions()
    {
        return platformAdminMapper.selectRoleOptions(platformAdminSupport.assignableRoleKeys());
    }

    private PlatformAdminListVO toListVo(PlatformAdminRow row)
    {
        PlatformAdminListVO vo = new PlatformAdminListVO();
        vo.setUserId(row.getUserId());
        vo.setAdminName(platformAdminSupport.resolveAdminName(row.getNickName(), row.getUserName()));
        vo.setUserName(row.getUserName());
        vo.setPhonenumber(row.getPhonenumber());
        vo.setEmail(StringUtils.isEmpty(row.getEmail()) ? "—" : row.getEmail());
        vo.setRoleNames(row.getRoleNames());
        vo.setCreateTime(row.getCreateTime());
        return vo;
    }
}
