package com.hzs.system.sys.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.domain.system.sys.*;
import com.hzs.system.config.service.IBdNoticeConfigService;
import com.hzs.system.config.vo.BdNoticeConfigVO;
import com.hzs.system.sys.mapper.*;
import com.hzs.system.sys.param.SysUserParam;
import com.hzs.system.sys.param.SysUserQueryParam;
import com.hzs.system.sys.vo.SysRoleUserVO;
import com.hzs.system.sys.vo.SysUserQueryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hzs.common.core.constant.UserConstants;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.system.sys.service.ISysUserService;

/**
 * 用户 业务层处理
 *
 * @author hzs
 */
@Slf4j
@Service
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserCountryMapper sysUserCountryMapper;
    @Autowired
    private SysUserVertexMapper sysUserVertexMapper;
    @Autowired
    private SysUserTeamMapper sysUserTeamMapper;

    @Autowired
    private IBdNoticeConfigService iBdNoticeConfigService;

    @Autowired
    private RedisService redisService;

    /**
     * 根据条件分页查询用户列表
     *
     * @param param
     * @return
     */
    @Override
    public List<SysUserQueryVO> selectUserList(SysUserQueryParam param) {
        return sysUserMapper.selectUserList(param);
    }

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

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

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        if (sysUserMapper.checkUserNameUnique(userName) > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param phoneNumber
     * @param userId
     * @return
     */
    @Override
    public String checkPhoneUnique(String phoneNumber, Long userId) {
        userId = StringUtils.isNull(userId) ? -1L : userId;
        SysUser info = sysUserMapper.checkPhoneUnique(phoneNumber);
        if (StringUtils.isNotNull(info) && !info.getUserId().equals(userId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

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

    /**
     * 新增保存用户信息
     *
     * @param param     管理员入参
     * @param userId
     * @param pkCountry
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUserParam param, Long userId, Integer pkCountry) {
        SysUser sysUser = BeanUtil.copyProperties(param, SysUser.class);
        sysUser.setPkCreator(userId);

        if (CollectionUtil.isNotEmpty(param.getCountryIdList())) {
            if (param.getCountryIdList().size() > 1) {
                // 当结算国家有多个时，所属结算地区为默认0
                sysUser.setPkCountry(CountryConstants.DEFAULT_ADMIN_COUNTRY);
            } else {
                // 当结算国家有一个时，则结算国就是这个
                sysUser.setPkCountry(param.getCountryIdList().get(0));
            }
        }

        // 所属角色ID冗余
        sysUser.setRoleIds(StringUtils.join(param.getRoleIdList(), ","));
        // 结算国家ID冗余
        sysUser.setCountryIds(StringUtils.join(param.getCountryIdList(), ","));
        // 查询体系ID冗余
        sysUser.setVertexIds(StringUtils.join(param.getVertexIdList(), ","));
        // 查询团队ID冗余
        sysUser.setTeamIds(StringUtils.join(param.getTeamIdList(), ","));

        // 新增用户信息
        int rows = sysUserMapper.insertUser(sysUser);

        // 新增角色关联数据
        insertUserRole(sysUser, param.getRoleIdList());
        // 新增国家关联数据
        insertUserManager(sysUser, param.getCountryIdList());
        // 新增体系关联数据
        insertUserVertex(sysUser, param.getVertexIdList());
        // 新增团队关联数据
        insertUserTeam(sysUser, param.getTeamIdList());

        return rows;
    }

    /**
     * 修改用户信息
     *
     * @param param  管理员入参
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUserParam param, Long userId) {
        SysUser sysUser = BeanUtil.copyProperties(param, SysUser.class);
        sysUser.setPkModified(userId);
        sysUser.setModifiedTime(new Date());

        if (CollectionUtil.isNotEmpty(param.getCountryIdList())) {
            if (param.getCountryIdList().size() > 1) {
                // 当结算国家有多个时，所属结算地区为默认0
                sysUser.setPkCountry(CountryConstants.DEFAULT_ADMIN_COUNTRY);
            } else {
                // 当结算国家有一个时，则结算国就是这个
                sysUser.setPkCountry(param.getCountryIdList().get(0));
            }
        }

        // 所属角色ID冗余
        sysUser.setRoleIds(StringUtils.join(param.getRoleIdList(), ","));
        // 结算国家ID冗余
        sysUser.setCountryIds(StringUtils.join(param.getCountryIdList(), ","));
        // 查询体系ID冗余
        sysUser.setVertexIds(StringUtils.join(param.getVertexIdList(), ","));
        // 查询团队ID冗余
        sysUser.setTeamIds(StringUtils.join(param.getTeamIdList(), ","));

        int row = sysUserMapper.updateUser(sysUser);

        // 删除用户与角色关联数据
        sysUserRoleMapper.deleteUserRoleByUserId(param.getUserId());
        // 新增角色关联数据
        insertUserRole(sysUser, param.getRoleIdList());
        // 删除用户与国家关联数据
        sysUserCountryMapper.deleteUserCountryByUserId(param.getUserId());
        // 新增国家关联数据
        insertUserManager(sysUser, param.getCountryIdList());
        // 删除用户与体系关联数据
        sysUserVertexMapper.deleteUserVertexByUserId(param.getUserId());
        // 新增体系关联数据
        insertUserVertex(sysUser, param.getVertexIdList());
        // 删除用户与团队关联数据
        sysUserTeamMapper.deleteUserTeamByUserId(param.getUserId());
        // 新增团队关联数据
        insertUserTeam(sysUser, param.getTeamIdList());

        // 更新公告配置相关内容
        iBdNoticeConfigService.updateNoticeConfigByContent(BdNoticeConfigVO.builder()
                .pkMember(userId)
                .roleIds(param.getRoleIdList())
                .userId(param.getUserId())
                .build());

        return row;
    }

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

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

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

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

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long[] userIds, Long userId) {
        for (Long tmpUserId : userIds) {
            checkUserAllowed(tmpUserId);

            // 更新公告配置相关内容
            iBdNoticeConfigService.updateNoticeConfigByContent(BdNoticeConfigVO.builder()
                    .pkMember(userId)
                    .userId(tmpUserId)
                    .build());
        }
        return sysUserMapper.deleteUserByIds(userIds, userId);
    }

    /**
     * 管理员角色处理
     *
     * @param user       用户对象
     * @param roleIdList
     */
    public void insertUserRole(SysUser user, List<Long> roleIdList) {
        if (CollectionUtil.isNotEmpty(roleIdList)) {
            // 新增管理员角色数据
            List<SysUserRole> list = new ArrayList<>(roleIdList.size());
            for (Long roleId : roleIdList) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            sysUserRoleMapper.insertUserRoleBatch(list);
        }
    }

    /**
     * 管理员国家权限处理
     *
     * @param user          用户对象
     * @param countryIdList
     */
    public void insertUserManager(SysUser user, List<Integer> countryIdList) {
        if (CollectionUtil.isNotEmpty(countryIdList)) {
            // 新增管理员国家权限数据
            List<SysUserCountry> list = new ArrayList<>(countryIdList.size());
            for (int i = 0; i < countryIdList.size(); i++) {
                SysUserCountry sysManagerCountry = new SysUserCountry();
                sysManagerCountry.setUserId(user.getUserId());
                sysManagerCountry.setPkCountry(countryIdList.get(i));
                if (i == 0) {
                    sysManagerCountry.setIsDefault(EYesNo.YES.getIntValue());
                }
                list.add(sysManagerCountry);
            }
            sysUserCountryMapper.insertUserCountryBatch(list);
        }
    }

    /**
     * 管理员查询体系处理
     *
     * @param user         用户对象
     * @param vertexIdList
     */
    public void insertUserVertex(SysUser user, List<Integer> vertexIdList) {
        if (CollectionUtil.isNotEmpty(vertexIdList)) {
            // 新增管理员体系数据
            List<SysUserVertex> list = new ArrayList<>(vertexIdList.size());
            for (Integer vertexId : vertexIdList) {
                SysUserVertex uv = new SysUserVertex();
                uv.setUserId(user.getUserId());
                uv.setPkVertex(vertexId);
                list.add(uv);
            }
            sysUserVertexMapper.insertUserVertexBatch(list);
        }
    }

    /**
     * 管理员团队体系处理
     *
     * @param user         用户对象
     * @param teamIdList
     */
    public void insertUserTeam(SysUser user, List<Long> teamIdList) {
        if (CollectionUtil.isNotEmpty(teamIdList)) {
            // 新增管理员体系数据
            List<SysUserTeam> list = new ArrayList<>(teamIdList.size());
            for (Long teamId : teamIdList) {
                SysUserTeam ut = new SysUserTeam();
                ut.setUserId(user.getUserId());
                ut.setPkTeam(teamId);
                list.add(ut);
            }
            sysUserTeamMapper.insertUserTeamBatch(list);
        }
    }

    @Override
    public List<SysRoleUserVO> queryUserByRoleId(Long roleId) {
        return sysUserMapper.queryUserByRoleId(roleId);
    }

    @Override
    public SysUser queryUserAndDeptName(Long userId) {
        return sysUserMapper.queryUserAndDeptName(userId);
    }


    @Override
    public List<SysRole> selectSysUserRole(Integer pkCountry) {
        return sysUserMapper.selectSysUserRole(pkCountry);
    }

    @Override
    public List<SysUser> selectAll() {
        return sysUserMapper.selectAll();
    }

}
