package com.fs.qw.service.impl;

import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.domain.QwTag;
import com.fs.qw.domain.QwUser;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.mapper.QwTagGroupMapper;
import com.fs.qw.mapper.QwTagMapper;
import com.fs.qw.param.QwTagParam;
import com.fs.qw.param.QwTagSearchParam;
import com.fs.qw.param.newparam.ContactTagListParam;
import com.fs.qw.service.IQwTagService;
import com.fs.qw.vo.QwTagGroupListVO;
import com.fs.qw.vo.QwTagVO;
import com.fs.qwApi.domain.QwResult;
import com.fs.qwApi.param.QwEditUserTagParam;
import com.fs.qwApi.service.QwApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 企微客户标签Service业务层处理
 *
 * @author fs
 * @date 2024-06-20
 */
@Service
public class QwTagServiceImpl implements IQwTagService
{
    private static final Logger log = LoggerFactory.getLogger(QwTagServiceImpl.class);
    @Autowired
    private QwTagMapper qwTagMapper;

    @Autowired
    private QwTagGroupMapper qwTagGroupMapper;

    /**
     * 查询企微客户标签
     *
     * @param id 企微客户标签主键
     * @return 企微客户标签
     */
    @Override
    public QwTag selectQwTagById(Long id)
    {
        return qwTagMapper.selectQwTagById(id);
    }

    /**
     * 查询企微客户标签列表
     *
     * @param qwTag 企微客户标签
     * @return 企微客户标签
     */
    @Override
    public List<QwTag> selectQwTagList(QwTag qwTag)
    {
        return qwTagMapper.selectQwTagList(qwTag);
    }

    @Override
    public List<QwTagGroupListVO> searchTags(QwTagParam tagParam) {

        List<QwTagGroupListVO> listVOS=new ArrayList<>();

        QwTag qwTag = new QwTag();
        qwTag.setName(tagParam.getName());
        qwTag.setCorpId(tagParam.getCorpId());
        qwTag.setCompanyId(tagParam.getCompanyId());
        List<QwTagVO> qwTags = qwTagMapper.selectQwTagListVO(qwTag);

        // Step 2: 提取 GroupId 列表（去重）
        Set<String> groupIds = qwTags.stream()
                .map(QwTagVO::getGroupId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        if (groupIds.isEmpty()) {
           return listVOS;
        }



        List<QwTagGroupListVO> tagGroups = qwTagGroupMapper.selectQwTagGroupListByIds(new ArrayList<>(groupIds));

        // 将标签组转换为 Map，便于快速查找
        Map<String, QwTagGroupListVO> groupMap = tagGroups.stream()
                .collect(Collectors.toMap(QwTagGroupListVO::getGroupId, Function.identity()));

        // Step 4: 组装数据
        List<QwTagGroupListVO> result = new ArrayList<>();
        for (QwTagVO tag : qwTags) {
            QwTagGroupListVO group = groupMap.get(tag.getGroupId());
            if (group != null) {
                // 为标签组附加对应的标签
                if (group.getTag() == null) {
                    group.setTag(new ArrayList<>());
                }
                group.getTag().add(tag);
                // 确保结果中只有唯一的标签组对象
                if (!result.contains(group)) {
                    result.add(group);
                }
            }
        }

        return result;
    }

    /**
     * 新增企微客户标签
     *
     * @param qwTag 企微客户标签
     * @return 结果
     */
    @Override
    public int insertQwTag(QwTag qwTag)
    {
        qwTag.setCreateTime(DateUtils.getNowDate());
        return qwTagMapper.insertQwTag(qwTag);
    }

    /**
     * 修改企微客户标签
     *
     * @param qwTag 企微客户标签
     * @return 结果
     */
    @Override
    public int updateQwTag(QwTag qwTag)
    {
        qwTag.setUpdateTime(DateUtils.getNowDate());
        return qwTagMapper.updateQwTag(qwTag);
    }

    /**
     * 批量删除企微客户标签
     *
     * @param ids 需要删除的企微客户标签主键
     * @return 结果
     */
    @Override
    public int deleteQwTagByIds(Long[] ids)
    {
        return qwTagMapper.deleteQwTagByIds(ids);
    }

    /**
     * 删除企微客户标签信息
     *
     * @param id 企微客户标签主键
     * @return 结果
     */
    @Override
    public int deleteQwTagById(Long id)
    {
        return qwTagMapper.deleteQwTagById(id);
    }
    @Autowired
    QwApiService qwApiService;
    @Autowired
    QwExternalContactMapper qwExternalContactMapper;
    @Override
    public void AddCourseTag(QwUser user) {
        QwTagVO courseTag = qwTagMapper.selectQwTagByName("已完课",user.getCorpId());
        QwTagVO noCourseTag = qwTagMapper.selectQwTagByName("待看课",user.getCorpId());
        if (courseTag!=null && noCourseTag!=null) {
            List<QwExternalContact> extIds = qwExternalContactMapper.selectExternalUserIdByQwUserId(user.getId());
            for (QwExternalContact extId : extIds) {
                String externalUserId = extId.getExternalUserId();
                QwEditUserTagParam qwEditUserTagParam = new QwEditUserTagParam();
                qwEditUserTagParam.setAdd_tag(Arrays.asList(noCourseTag.getTagId()));
                qwEditUserTagParam.setRemove_tag(Arrays.asList(courseTag.getTagId()));
                qwEditUserTagParam.setUserid(user.getQwUserId());
                qwEditUserTagParam.setExternal_userid(externalUserId);
                QwResult qwResult = qwApiService.editUserTag(qwEditUserTagParam, user.getCorpId());
                if (qwResult != null) {

                }
            }

        }else {
            log.info("没有标签");
        }


    }

    @Override
    public List<String> selectQwTagListByTagIds(QwTagSearchParam param) {
        return qwTagMapper.selectQwTagListNameByTagIds(param);
    }

    @Override
    public List<QwTagVO> getTagListByUserId(ContactTagListParam param) {
        String[] keywords = new String[0];
        if(param != null){
            if(StringUtils.isNotEmpty(param.getKeyword())){
                keywords = param.getKeyword().split(",");
            }
        }
        return qwTagMapper.selectTagListByUserId(param, keywords);
    }
}
