package com.fs.company.service.impl;

import com.fs.common.annotation.DataScope;
import com.fs.common.constant.UserConstants;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.*;
import com.fs.company.enums.ProductStatus;
import com.fs.company.mapper.*;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.vo.CompanyUserOptionRespVO;
import com.fs.company.vo.CompanyUserProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 理员信息Service业务层处理
 *
 * @author fs
 * @date 2021-05-25
 */
@Service
public class CompanyUserServiceImpl implements ICompanyUserService {
    @Autowired
    private CompanyUserMapper companyUserMapper;
    @Autowired
    private CompanyRoleMapper roleMapper;

    @Autowired
    private CompanyPostMapper postMapper;

    @Autowired
    private CompanyUserRoleMapper userRoleMapper;

    @Autowired
    private CompanyUserPostMapper userPostMapper;
    @Autowired
    private CompanyProductMapper companyProductMapper;

    /**
     * 查询理员信息
     *
     * @param userId 理员信息ID
     * @return 理员信息
     */
    @Override
    public CompanyUser selectCompanyUserById(Long userId) {
        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(userId);
        List<Integer> roleIds = roleMapper.selectRoleListByUserId(userId);
        Long[] roleIdsArray = roleIds.stream().map(Integer::longValue).toArray(Long[]::new);
        if(Objects.nonNull(companyUser)){
            companyUser.setRoleIds(roleIdsArray);
        }
        return companyUser;

    }

    /**
     * 查询理员信息列表
     *
     * @param companyUser 理员信息
     * @return 理员信息
     */
    @Override
//    @DataScope(deptAlias = "u", userAlias = "u")
    public List<CompanyUser> selectCompanyUserList(CompanyUser companyUser) {
        List<CompanyUser> companyUsers = companyUserMapper.selectCompanyUserList(companyUser);

        return companyUsers;
    }

    /**
     * 新增理员信息
     *
     * @param companyUser 理员信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertCompanyUser(CompanyUser companyUser) {
        companyUser.setCreateTime(DateUtils.getNowDate());
        companyUser.setPassword(SecurityUtils.encryptPassword(companyUser.getPassword()));
        int i = companyUserMapper.insertCompanyUser(companyUser);
        //角色关系
        insertUserRole(companyUser);
        //岗位关系
        insertUserPost(companyUser);

        return i;
    }

    /**
     * 修改理员信息
     *
     * @param companyUser 理员信息
     * @return 结果
     */
    @Override
    public int updateCompanyUser(CompanyUser companyUser) {
        companyUser.setUpdateTime(DateUtils.getNowDate());

        Long userId = companyUser.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(companyUser);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(companyUser);
        return companyUserMapper.updateCompanyUser(companyUser);
//        if (companyUser.getStatus().equals("1")){
//            CompanyVoiceCaller caller = callerMapper.selectCompanyVoiceCallerByUserId(companyUser.getCompanyId(),companyUser.getUserId());
//            caller.setCompanyId(0l);
//            caller.setCompanyUserId(0l);
//            caller.setMobile("");
//            caller.setStatus(1);
//            callerMapper.updateCompanyVoiceCaller(caller);
//        }
//        return companyUserMapper.updateCompanyUser(companyUser);
    }


    /**
     * 批量删除理员信息
     *
     * @param userIds 需要删除的理员信息ID
     * @return 结果
     */
    @Override
    public int deleteCompanyUserByIds(Long[] userIds) {
        return companyUserMapper.deleteCompanyUserByIds(userIds);
    }

    /**
     * 删除理员信息信息
     *
     * @param userId 理员信息ID
     * @return 结果
     */
    @Override
    public int deleteCompanyUserById(Long userId) {
        return companyUserMapper.deleteCompanyUserById(userId);
    }

    @Override
    public CompanyUser selectUserByUserName(String account) {
        return companyUserMapper.selectUserByUserName(account);
    }

    @Override
    public String selectUserRoleGroup(String username) {
        List<CompanyRole> list = roleMapper.selectRolesByUserName(username);
        StringBuffer idsStr = new StringBuffer();
        for (CompanyRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public String selectUserPostGroup(String username) {
        List<CompanyPost> list = postMapper.selectPostsByUserName(username);
        StringBuffer idsStr = new StringBuffer();
        for (CompanyPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public int updateUserAvatar(String username, String avatar) {
        return companyUserMapper.updateUserAvatar(username, avatar);
    }

    @Override
    public int resetUserPwd(String userName, String encryptPassword) {
        return companyUserMapper.resetUserPwd(userName, encryptPassword);
    }

    @Override
    public int updateUserProfile(CompanyUser user) {
        return companyUserMapper.updateCompanyUser(user);
    }

    @Override
    public int checkUserName(String userName) {
        return companyUserMapper.checkUserName(userName);
    }


    @Override
    @Transactional
    public int insertUser(CompanyUser user) {
        String password = user.getPassword();
        user.setPassword(SecurityUtils.encryptPassword(password));
        // 新增用户信息
        int rows = companyUserMapper.insertCompanyUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(CompanyUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return companyUserMapper.updateCompanyUser(user);
    }

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

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(CompanyUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<CompanyUserRole> list = new ArrayList<CompanyUserRole>();
            for (Long roleId : roles) {
                CompanyUserRole ur = new CompanyUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                ur.setCompanyId(user.getCompanyId());
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    @Override
    public int resetUserPwdByUserId(Long userId, String encryptPassword) {
        return companyUserMapper.resetUserPwdByUserId(userId, encryptPassword);
    }

    @Override
    public String checkUserNameUnique(String userName) {
        int count = companyUserMapper.checkUserNameUnique(userName);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public Integer selectCompanyUserCountByCompanyId(Long companyId) {
        return companyUserMapper.selectCompanyUserCountByCompanyId(companyId);
    }

    @Override
    public List<CompanyUserOptionRespVO> getUserOptionVOList(String companyNickName, Long companyId) {
        return companyUserMapper.getUserOptionVOList(companyNickName,companyId);
    }

    @Override
    public List<CompanyUserProductVO> getCompanyUserProductList(Long id) {
        List<CompanyUserProductVO> list = new ArrayList<>();
        if (id == null) {
            return list;
        }

        CompanyUser companyUser = companyUserMapper.selectCompanyUserById(id);
        if (companyUser == null) {
            return list; // 或者 throw new ServiceException("用户不存在");
        }

        String productCode = companyUser.getProductCode();
        if (productCode == null || productCode.trim().isEmpty()) {
            return list;
        }

        List<String> codes = Arrays.stream(productCode.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .distinct()
                .collect(Collectors.toList());


        if (codes.isEmpty()) {
            return list;
        }

        // 2) 查启用产品（按用户 companyId）
        CompanyProduct query = new CompanyProduct();
        query.setStatus(ProductStatus.ENABLED.getCode().longValue());
        query.setCompanyId(companyUser.getCompanyId());

        List<CompanyProduct> companyProducts = companyProductMapper.selectCompanyProductList(query);

        // 3) 转 map（防重复）
        Map<String, String> productMap = companyProducts.stream()
                .filter(p -> p.getProductCode() != null)
                .collect(Collectors.toMap(
                        CompanyProduct::getProductCode,
                        CompanyProduct::getProductName,
                        (a, b) -> b
                ));

        // 4) 组装 VO，保持原顺序（以用户绑定的 codes 为准）
        for (String code : codes) {
            String name = productMap.get(code);
            CompanyUserProductVO vo = new CompanyUserProductVO();
            vo.setProductCode(code);
            vo.setProductName(name != null ? name : code); // 或 "未知产品"
            list.add(vo);
        }

        return list;
    }

    @Override
    public List<CompanyUser> queryAllCompanyUser(Long companyId) {

        return companyUserMapper.queryAllCompanyUser(companyId);
    }

    /**
     * 根据手机号查询用户
     *
     * @param phonenumber 手机号
     * @return 用户信息
     */
    @Override
    public CompanyUser selectUserByPhone(String phonenumber) {
        return companyUserMapper.selectUserByPhone(phonenumber);
    }


}
