package com.fs.wxUser.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.DictUtils;
import com.fs.company.cache.ICompanyUserCacheService;
import com.fs.company.domain.CompanyUser;
import com.fs.qw.param.CompanyWxUserAddGroupParam;
import com.fs.voice.utils.StringUtil;
import com.fs.wxUser.domain.CompanyWxUser;
import com.fs.wxUser.domain.CompanyWxUserGroup;
import com.fs.wxUser.mapper.CompanyWxUserGroupMapper;
import com.fs.wxUser.mapper.CompanyWxUserMapper;
import com.fs.wxUser.param.CompanyWxUserBindFsUserParam;
import com.fs.wxUser.param.CompanyWxUserParam;
import com.fs.wxUser.service.ICompanyWxUserService;
import com.fs.wxUser.vo.CompanyWxUserVO;
import com.hc.openapi.tool.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 个微用户Service业务层处理
 *
 * @author fs
 * @date 2024-10-22
 */
@Service
public class CompanyWxUserServiceImpl implements ICompanyWxUserService
{
    @Autowired
    private CompanyWxUserMapper companyWxUserMapper;
    @Autowired
    private CompanyWxUserGroupMapper companyWxUserGroupMapper;
    @Autowired
    private ICompanyUserCacheService companyUserCacheService;
    /**
     * 查询个微用户
     *
     * @param userId 个微用户主键
     * @return 个微用户
     */
    @Override
    public CompanyWxUser selectCompanyWxUserByUserId(Long userId)
    {
        return companyWxUserMapper.selectCompanyWxUserByUserId(userId);
    }

    /**
     * 查询个微用户列表
     *
     * @param companyWxUser 个微用户
     * @return 个微用户
     */
    @Override
    public List<CompanyWxUser> selectCompanyWxUserList(CompanyWxUser companyWxUser)
    {
        List<CompanyWxUser> list = companyWxUserMapper.selectCompanyWxUserList(companyWxUser);
        for (CompanyWxUser wxUser : list) {
            CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(wxUser.getCompanyUserId());
            if(ObjectUtil.isNotNull(companyUser)){
                wxUser.setCompanyUserName(String.format("%s_%s",companyUser.getUserName(),companyUser.getUserId()));
            }
            String personalWechatStatus = DictUtils.getDictLabel("personal_wechat_status", String.valueOf(wxUser.getStatus()));
            if(StringUtils.isNotBlank(personalWechatStatus)){
                wxUser.setStatusText(personalWechatStatus);
            }
        }
        return list;
    }

    @Override
    public List<CompanyWxUserVO> selectCompanyWxUserListVO(CompanyWxUserParam param) {

        //查询分组
        CompanyWxUserGroup wxUserGroup=new CompanyWxUserGroup();
        wxUserGroup.setGroupName(param.getGroupName());
        wxUserGroup.setCompanyId(param.getCompanyId());

        if (!StringUtil.strIsNullOrEmpty(param.getGroupName())){
            List<CompanyWxUserGroup> companyWxUserGroups = companyWxUserGroupMapper.selectCompanyWxUserGroupList(wxUserGroup);
            if(companyWxUserGroups!=null && companyWxUserGroups.size()>0){
                // 使用Stream API提取groupId，去重，并收集到新的列表中
             List<Long>   uniqueGroupIds = companyWxUserGroups.stream()
                        .map(CompanyWxUserGroup::getGroupId) // 假设CompanyWxUserGroup类有getGroupId()方法
                        .distinct() // 去重
                        .collect(Collectors.toList()); // 收集到列表

                param.setUniqueGroupIds(uniqueGroupIds);
            }
        }

        return companyWxUserMapper.selectCompanyWxUserListVO(param);
    }

    /**
     * 新增个微用户
     *
     * @param companyWxUser 个微用户
     * @return 结果
     */
    @Override
    public int insertCompanyWxUser(CompanyWxUser companyWxUser)
    {
        companyWxUser.setCreateTime(DateUtils.getNowDate());
        return companyWxUserMapper.insertCompanyWxUser(companyWxUser);
    }

    /**
     * 修改个微用户
     *
     * @param companyWxUser 个微用户
     * @return 结果
     */
    @Override
    public int updateCompanyWxUser(CompanyWxUser companyWxUser)
    {
        return companyWxUserMapper.updateCompanyWxUser(companyWxUser);
    }

    /**
     * 批量删除个微用户
     *
     * @param userIds 需要删除的个微用户主键
     * @return 结果
     */
    @Override
    public int deleteCompanyWxUserByUserIds(Long[] userIds)
    {
        return companyWxUserMapper.deleteCompanyWxUserByUserIds(userIds);
    }

    /**
     * 删除个微用户信息
     *
     * @param userId 个微用户主键
     * @return 结果
     */
    @Override
    public int deleteCompanyWxUserByUserId(Long userId)
    {
        return companyWxUserMapper.deleteCompanyWxUserByUserId(userId);
    }

    @Override
    public CompanyWxUser selectCompanyWxUserByWeixinId(String weixinId) {
        return companyWxUserMapper.selectCompanyWxUserByWeixinId(weixinId);
    }

    @Override
    public R updateCompanyWxUserBindFsUser(CompanyWxUserBindFsUserParam param) {

        CompanyWxUser companyWxUser=new CompanyWxUser();
        companyWxUser.setUserId(param.getUserId());
        companyWxUser.setFsUserId(param.getFsUserId());
        int i = companyWxUserMapper.updateCompanyWxUser(companyWxUser);

        if(i>0){
            return R.ok("绑定成功");
        }else {
            return R.error("绑定失败");
        }
    }

    @Override
    public R addGroup(CompanyWxUserAddGroupParam param) {

        int suc = 0;
        List<Long> userIds = param.getUserIds();
        for (Long userId : userIds) {

            CompanyWxUser wxUser = companyWxUserMapper.selectCompanyWxUserByUserId(userId);

            String groupIds = wxUser.getGroupId();

            if (groupIds != null && groupIds != "") {
                    List<String> ids = JSON.parseArray(groupIds, String.class);
                    for (String tagId : param.getGroupIds()) {
                        ids.add(tagId);
                    }
                    Set<String> uniqueIds = new HashSet<>(ids);

                    wxUser.setGroupId(JSON.toJSONString(uniqueIds));

                } else {
                    wxUser.setGroupId(JSON.toJSONString(param.getGroupIds()));

                }
                wxUser.setUserId(userId);

                suc++;
                companyWxUserMapper.updateCompanyWxUser(wxUser);
            }


        return R.ok("成功：" + suc );
    }

    /**
    * 批量移除分组
    */
    @Override
    public R delGroup(CompanyWxUserAddGroupParam param) {
        int suc = 0;
        List<Long> userIds = param.getUserIds();
        for (Long userId : userIds) {
            CompanyWxUser wxUser = companyWxUserMapper.selectCompanyWxUserByUserId(userId);

            String groupIds = wxUser.getGroupId();

                if (groupIds != null && groupIds != "") {
                    List<String> ids = JSON.parseArray(groupIds, String.class);
                    for (String tagId : param.getGroupIds()) {
                        ids.removeIf(str -> str.equals(tagId));
                    }

                    wxUser.setGroupId(JSON.toJSONString(ids));

                    companyWxUserMapper.updateCompanyWxUser(wxUser);

                    suc++;
                }


            }

        return R.ok("成功：" + suc );
    }
}
