package com.bonus.system.service.impl;

import com.bonus.common.core.constant.Constants;
import com.bonus.common.core.constant.UserConstants;
import com.bonus.common.core.domain.R;
import com.bonus.common.core.enums.UserPermanentEnum;
import com.bonus.common.core.enums.UserStatus;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.SpringUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.bean.BeanValidators;
import com.bonus.common.core.utils.encryption.Sm4Utils;
import com.bonus.common.core.utils.sms.SmsUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.domain.BaseEntity;
import com.bonus.common.datascope.annotation.DataScope;
import com.bonus.common.datascope.utils.CommonDataPermissionInfo;
import com.bonus.common.security.config.VerificationCodeConfig;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.RemoteFileService;
import com.bonus.system.api.domain.*;
import com.bonus.system.domain.SysUserPost;
import com.bonus.system.feign.SmartCanteenClient;
import com.bonus.system.mapper.*;
import com.bonus.system.service.ISysConfigService;
import com.bonus.system.service.ISysDeptService;
import com.bonus.system.service.ISysUserService;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author bonus
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    protected Validator validator;

    @Resource
    private VerificationCodeConfig verificationCodeConfig;

    @Autowired
    private JavaMailSender mailSender; // 自动注入JavaMailSender，用于发送邮件

    @Autowired
    RemoteFileService remoteFileService;

    @Resource
    private SmartCanteenClient smartCanteenClient;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        try {
            //临时获取开始时间和结束时间
            String beginTime = (String) user.getParams().get("beginTime");
            String endTime = (String) user.getParams().get("endTime");
            BaseEntity entity = CommonDataPermissionInfo.backMissionInfo(user.getParams().get("dataScope").toString());
            BeanUtils.copyProperties(entity, user);
            user.getParams().put("beginTime", beginTime);
            user.getParams().put("endTime", endTime);
        } catch (Exception e) {
            e.printStackTrace();

        }
        if (user.getUserName() != null) {
            String userName =user.getUserName().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_");
            user.setUserName(userName);
        }
        if (user.getPhonenumber() != null) {
            String phone =user.getPhonenumber().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_");
            user.setPhonenumber(phone);
        }
        //if (Objects.nonNull(SecurityUtils.getLoginUser()) && Objects.nonNull(SecurityUtils.getLoginUser().getSysUser())) {
        //    user.setCompanyId(SecurityUtils.getLoginUser().getSysUser().getCompanyId());
        //}
        List<SysUser> sysUsers = userMapper.selectUserList(user);

        for (SysUser sysUser : sysUsers) {
            sysUser.setPhotoUrl(remoteFileService.getFullFileUrl(sysUser.getPhotoUrl()));
        }
        if(user.getQueryTyoe()==1){
            return sysUsers;
        }else{
            List<Long> userIds = userMapper.selectBindUserIds();
            Set<Long> userIdSet = new HashSet<>(userIds);
            sysUsers.forEach(s -> s.setBingStatus(userIdSet.contains(s.getUserId())));
            return sysUsers;
        }

    }

    public List<SysUser> selectUserList4Job(SysUser user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        try {
            BaseEntity entity = CommonDataPermissionInfo.backMissionInfo(user.getParams().get("dataScope").toString());
            BeanUtils.copyProperties(entity, user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        try {
            BaseEntity entity = CommonDataPermissionInfo.backMissionInfo(user.getParams().get("dataScope").toString());
            BeanUtils.copyProperties(entity, user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户名查询用户
     *
     * @param photoNumber 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByPhotoNumber(String photoNumber) {
        return userMapper.selectUserByPhoneNumber(Sm4Utils.encrypt(photoNumber));
    }

    @Override
    public SysUser selectKitchenStaffByPhotoNumber(String photoNumber) {
        SysUser sysUser = userMapper.selectKitchenStaffByPhoneNumber(Sm4Utils.encrypt(photoNumber));
        if (Objects.isNull(sysUser)) {
            sysUser = userMapper.selectKitchenStaffByPhoneNumber(photoNumber);
        }
        return sysUser;
    }

    /**
     * 通过用户名查询用户
     *
     * @param email 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByEmail(String email) {
        return userMapper.selectUserByEmail(Sm4Utils.encrypt(email));
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 批量查询用户
     *
     * @param userIds 用户ID
     * @return 用户对象信息
     */
    public List<SysUser> selectUsersByIds(Long[] userIds) {
        return userMapper.selectUsersByIds(userIds);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(Sm4Utils.encrypt(user.getPhonenumber()));
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(Sm4Utils.encrypt(user.getEmail()));
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * @return
     */


    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        /*if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }*/
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    public void setUserStatus(SysUser user) {
        if (UserPermanentEnum.TEMP_USER.getCode().equals(user.getIsPermanent())) {
            Date now = new Date();
            if (Objects.nonNull(user.getEffectiveStartDay()) && user.getEffectiveStartDay().after(now)
                    || Objects.nonNull(user.getEffectiveEndDay()) && user.getEffectiveEndDay().before(now)) {
                user.setStatus(UserStatus.DISABLE.getCode());
            } else {
                user.setStatus(UserStatus.OK.getCode());
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        // 同步创建账户数据
        smartCanteenClient.syncAccInfo(user);
        // 同步更新user face数据
        try {
            uploadUserFace(user);
        } catch (Exception e) {
            log.error("同步更新user face数据失败", e.getMessage());
        }
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        // 同步更新user face数据
        try {
            uploadUserFace(user);
        } catch (Exception e) {
            log.error("同步更新user face数据失败", e.getMessage());
        }
        // 更新用户
        return userMapper.updateUser(user);
    }

    private void uploadUserFace(SysUser user) {
        try {
            SysUserFace sysUserFace = new SysUserFace();
            sysUserFace.setUserId(user.getUserId());
            sysUserFace.setPhotoUrl(user.getPhotoUrl());
            smartCanteenClient.uploadUserFace(sysUserFace);
        } catch (Exception e) {
            log.error("上传人脸失败, ", e.getMessage());
        }
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    @Override
    public int updateUserStatus4Job(SysUser user) {
        return userMapper.updateUserStatus(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        // 同步删除账户信息
        List<SysUser> users = new ArrayList<>();
        for (int i = 0; i < userIds.length; i++) {
            SysUser user = new SysUser();
            user.setUserId(userIds[i]);
            users.add(user);
        }
        smartCanteenClient.deleteAccInfoByUserIds(users);

        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        if (hasDuplicatePhonenumbers(userList)) {
            throw new ServiceException("导入用户数据存在相同的手机号！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    deptService.checkDeptDataScope(user.getDeptId());
                    String password = configService.selectConfigByKey("sys.user.initPassword");
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    deptService.checkDeptDataScope(user.getDeptId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                //修复禅道bug 4076，wangweiwei 2024/12/16
                String message = e.getMessage();
                if (message != null && message.contains(":")) {
                    // 去掉冒号及其前面的字段名部分
                    failureMsg.append(msg + message.substring(message.indexOf(":") + 2).trim());
                }else {
                    failureMsg.append(msg + e.getMessage());
                }
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    public boolean hasDuplicatePhonenumbers(List<SysUser> userList) {
        Map<String, Long> phoneCountMap = userList.stream()
                .collect(Collectors.groupingBy(SysUser::getPhonenumber, Collectors.counting()));
        return phoneCountMap.values().stream().anyMatch(count -> count > 1);
    }

    /**
     * @param userId
     * @return
     */
    @Override
    public R<T> approvalStatus(Long userId) {
        try {
            SysUser sysUser = userMapper.selectUserById(userId);
            if ("1".equals(sysUser.getApprovalStatus())) {
                return R.fail("该用户已通过审批");
            }
            Integer i = userMapper.approvalStatus(userId);
            if (i > 0) {
                if (StringUtils.isNotEmpty(sysUser.getPhonenumber())) {
                    SmsUtils.smsToken(sysUser.getPhonenumber(), "您的账号:" + sysUser.getUserName() + "已通过审批，请登录系统", "");
                }
                if (StringUtils.isNotEmpty(sysUser.getEmail())) {
                    sendSimpleEmail(sysUser.getEmail(), "您的账号:" + sysUser.getUserName() + "已通过审批，请登录系统");
                }
                return R.ok();
            } else {
                return R.fail();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
    }

    /**
     * @param user
     * @return
     */
    @Override
    public AjaxResult systemUpdateUser(SysUser user) {
        try{
            int num =  userMapper.systemUpdateUser(user);
            return num>0?AjaxResult.success():AjaxResult.error();
        }catch (Exception e){
            log.error(e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * 发送简单邮件
     *
     * @param to 接收者邮箱地址
     */
    public R<Object> sendSimpleEmail(String to, String content) {
        // 创建一个简单邮件消息对象
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("2642480752@qq.com"); // 发件人邮箱地址
        message.setTo(to); // 收件人邮箱地址
        message.setSubject(verificationCodeConfig.getTitle()); // 邮件主题
        message.setText(content); // 邮件内容
        mailSender.send(message); // 发送邮件
        return R.ok();
    }

}
