package com.fs.qw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.PubFun;
import com.fs.qw.domain.QwWorkLink;
import com.fs.qw.domain.QwWorkLinkUser;
import com.fs.qw.mapper.QwWorkLinkMapper;
import com.fs.qw.service.IQwUserService;
import com.fs.qw.service.IQwWorkLinkService;
import com.fs.qw.service.IQwWorkLinkUserService;
import com.fs.qw.vo.QwUserVO;
import com.fs.qwApi.domain.QwLinkCreateResult;
import com.fs.qwApi.param.QwLinkCreateParam;
import com.fs.qwApi.param.QwLinkGetParam;
import com.fs.qwApi.service.QwApiService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 企微获客链接管理Service业务层处理
 *
 * @author fs
 * @date 2025-01-10
 */
@Service
@AllArgsConstructor
public class QwWorkLinkServiceImpl extends ServiceImpl<QwWorkLinkMapper, QwWorkLink> implements IQwWorkLinkService {

    private final QwWorkLinkMapper qwWorkLinkMapper;
    private final QwApiService qwApiService;
    private final IQwUserService qwUserService;
    private final IQwWorkLinkUserService qwWorkLinkUserService;
    private final Function<Long, QueryWrapper<QwWorkLinkUser>> LINK_USER_QUERY = id -> new QueryWrapper<QwWorkLinkUser>().eq("link_id", id);


    /**
     * 查询企微获客链接管理
     *
     * @param id 企微获客链接管理主键
     * @return 企微获客链接管理
     */
    @Override
    public QwWorkLink selectQwWorkLinkById(Long id) {
        QwWorkLink qwWorkLink = qwWorkLinkMapper.selectById(id);
        List<QwWorkLinkUser> list = qwWorkLinkUserService.list(LINK_USER_QUERY.apply(id));
        qwWorkLink.setUserIds(PubFun.listToNewList(list, QwWorkLinkUser::getQwUserId));
        return qwWorkLink;
    }

    /**
     * 查询企微获客链接管理列表
     *
     * @param qwWorkLink 企微获客链接管理
     * @return 企微获客链接管理
     */
    @Override
    public List<QwWorkLink> selectQwWorkLinkList(QwWorkLink qwWorkLink) {
        return qwWorkLinkMapper.selectQwWorkLinkList(qwWorkLink);
    }

    @Override
    public List<QwWorkLink> selectQwWorkLinkListAll(QwWorkLink qwWorkLink) {

        return qwWorkLinkMapper.selectQwWorkLinkListAll(qwWorkLink);
    }

    /**
     * 新增企微获客链接管理
     *
     * @param qwWorkLink 企微获客链接管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertQwWorkLink(QwWorkLink qwWorkLink) {
        List<QwUserVO> qwUserVOS = new ArrayList<>();
        if (qwWorkLink.getType() != null && qwWorkLink.getType() == 1) {
            qwUserVOS = saveOrUpdateQwWorkLink(qwWorkLink);
        }
        int insert = qwWorkLinkMapper.insert(qwWorkLink);
        if (qwWorkLink.getType() != null && qwWorkLink.getType() == 1 && qwUserVOS.isEmpty()) {
            saveOrUpdateQwWorkUser(qwWorkLink, qwUserVOS);
        }
        return insert;
    }

    private void saveOrUpdateQwWorkUser(QwWorkLink qwWorkLink, List<QwUserVO> qwUserVOS) {
        qwWorkLinkUserService.remove(LINK_USER_QUERY.apply(qwWorkLink.getId()));
        Map<Long, QwUserVO> qwUserMap = PubFun.listToMapByGroupObject(qwUserVOS, QwUserVO::getId);
        List<QwWorkLinkUser> qwLinkUserList = qwWorkLink.getUserIds().stream().map(e -> {
            QwUserVO qwUserVO = qwUserMap.get(e);
            QwWorkLinkUser linkUser = new QwWorkLinkUser();
            linkUser.setLinkId(qwWorkLink.getId());
            linkUser.setQwUserId(qwUserVO.getId());
            linkUser.setQwUserWxId(qwUserVO.getQwUserId());
            return linkUser;
        }).collect(Collectors.toList());
        qwWorkLinkUserService.saveBatch(qwLinkUserList);
    }

    public List<QwUserVO> saveOrUpdateQwWorkLink(QwWorkLink qwWorkLink) {
        List<QwUserVO> qwUserVOS = qwUserService.selectQwUserVOByIds(qwWorkLink.getUserIds().toArray(new Long[0]));
        String corpId = qwUserVOS.get(0).getCorpId();
        QwLinkCreateParam qwLinkCreateParam = new QwLinkCreateParam();
        if (qwWorkLink.getId() != null) {
            qwLinkCreateParam.setLink_id(qwWorkLink.getLinkId());
        }
        qwLinkCreateParam.setLink_name(qwWorkLink.getLinkName());
        QwLinkCreateParam.Range range = new QwLinkCreateParam.Range();
        range.setUser_list(qwUserVOS.stream().map(QwUserVO::getQwUserId).collect(Collectors.toList()));
        qwLinkCreateParam.setRange(range);
        QwLinkCreateResult qwLinkCreateResult;
        if (qwWorkLink.getId() != null) {
            qwApiService.linkUpdate(qwLinkCreateParam, corpId);
        } else {
            qwLinkCreateResult = qwApiService.linkCreate(qwLinkCreateParam, corpId);
            qwWorkLink.setCorpId(corpId);
            qwWorkLink.setLinkId(qwLinkCreateResult.getLinkId());
            qwWorkLink.setUrl(qwLinkCreateResult.getUrl());
            qwWorkLink.setCreateTime(DateUtils.getNowDate());
        }
        return qwUserVOS;
    }

    /**
     * 修改企微获客链接管理
     *
     * @param qwWorkLink 企微获客链接管理
     * @return 结果
     */
    @Override
    public int updateQwWorkLink(QwWorkLink qwWorkLink) {
        List<QwUserVO> qwUserVOS = new ArrayList<>();
        if (qwWorkLink.getType() != null && qwWorkLink.getType() == 1) {
            qwUserVOS = saveOrUpdateQwWorkLink(qwWorkLink);
            qwWorkLink.setUpdateTime(DateUtils.getNowDate());
        }
        int i = qwWorkLinkMapper.updateById(qwWorkLink);
        if (qwWorkLink.getType() != null && qwWorkLink.getType() == 1 && !qwUserVOS.isEmpty()) {
            saveOrUpdateQwWorkUser(qwWorkLink, qwUserVOS);
        }
        return i;
    }

    /**
     * 批量删除企微获客链接管理
     *
     * @param ids 需要删除的企微获客链接管理主键
     * @return 结果
     */
    @Override
    public int deleteQwWorkLinkByIds(Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        Collection<QwWorkLink> list = listByIds(idList);
        list.forEach(e -> qwApiService.linkDelete(QwLinkGetParam.builder().link_id(e.getLinkId()).build(), e.getCorpId()));
        qwWorkLinkUserService.remove(new QueryWrapper<QwWorkLinkUser>().in("link_id", idList));
        return qwWorkLinkMapper.deleteQwWorkLinkByIds(ids);
    }

    /**
     * 删除企微获客链接管理信息
     *
     * @param id 企微获客链接管理主键
     * @return 结果
     */
    @Override
    public int deleteQwWorkLinkById(Long id) {
        QwWorkLink e = getById(id);
        qwApiService.linkDelete(QwLinkGetParam.builder().link_id(e.getLinkId()).build(), e.getCorpId());
        return qwWorkLinkMapper.deleteQwWorkLinkById(id);
    }
}
