package com.fs.qw.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.utils.DateUtils;
import com.fs.company.domain.CompanyDept;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyDeptMapper;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.qw.domain.*;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.mapper.QwUserVoiceLogMapper;
import com.fs.qw.mapper.QwWorkTaskMapper;
import com.fs.qw.service.IQwCompanyService;
import com.fs.qw.service.IQwUserVoiceLogService;
import com.fs.qw.vo.QwUserVoiceLogTotalVo;
import com.fs.qw.vo.QwUserVoiceLogVo;
import com.fs.wxwork.dto.WxWorkResponseDTO;
import com.fs.wxwork.dto.WxWorkVid2UserIdDTO;
import com.fs.wxwork.dto.WxWorkVid2UserIdRespDTO;
import com.fs.wxwork.service.WxWorkService;
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.stream.Collectors;

/**
 * 企微用户通话记录Service业务层处理
 *
 * @author fs
 * @date 2025-05-08
 */
@Service
public class QwUserVoiceLogServiceImpl extends ServiceImpl<QwUserVoiceLogMapper, QwUserVoiceLog> implements IQwUserVoiceLogService {
    private static final Logger log = LoggerFactory.getLogger(QwUserVoiceLogServiceImpl.class);
    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private QwWorkTaskMapper qwWorkTaskMapper;

    @Autowired
    WxWorkService wxWorkService;
    @Autowired
    private QwExternalContactMapper qwExternalContactMapper;

    @Autowired
    private IQwCompanyService qwCompanyService;

    @Autowired
    private CompanyUserMapper companyUserMapper;
    @Autowired
    private CompanyDeptMapper companyDeptMapper;

    /**
     * 查询企微用户通话记录
     *
     * @param id 企微用户通话记录主键
     * @return 企微用户通话记录
     */
    @Override
    public QwUserVoiceLogVo selectQwUserVoiceLogById(Long id)
    {
        return baseMapper.selectQwUserVoiceLogById(id);
    }

    /**
     * 查询企微用户通话记录列表
     *
     * @param qwUserVoiceLog 企微用户通话记录
     * @return 企微用户通话记录
     */
    @Override
    public List<QwUserVoiceLogVo> selectQwUserVoiceLogList(QwUserVoiceLogVo qwUserVoiceLog)
    {
        return baseMapper.selectQwUserVoiceLogList(qwUserVoiceLog);
    }

    /**
     * 新增企微用户通话记录
     *
     * @param qwUserVoiceLog 企微用户通话记录
     * @return 结果
     */
    @Override
    public int insertQwUserVoiceLog(QwUserVoiceLog qwUserVoiceLog)
    {
        qwUserVoiceLog.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertQwUserVoiceLog(qwUserVoiceLog);
    }

    /**
     * 修改企微用户通话记录
     *
     * @param qwUserVoiceLog 企微用户通话记录
     * @return 结果
     */
    @Override
    public int updateQwUserVoiceLog(QwUserVoiceLog qwUserVoiceLog)
    {
        return baseMapper.updateQwUserVoiceLog(qwUserVoiceLog);
    }

    /**
     * 批量删除企微用户通话记录
     *
     * @param ids 需要删除的企微用户通话记录主键
     * @return 结果
     */
    @Override
    public int deleteQwUserVoiceLogByIds(Long[] ids)
    {
        return baseMapper.deleteQwUserVoiceLogByIds(ids);
    }

    /**
     * 删除企微用户通话记录信息
     *
     * @param id 企微用户通话记录主键
     * @return 结果
     */
    @Override
    public int deleteQwUserVoiceLogById(Long id)
    {
        return baseMapper.deleteQwUserVoiceLogById(id);
    }

    @Override
    public List<QwUserVoiceLogTotalVo> selectQwUserVoiceLogTotalList(QwUserVoiceLogTotalVo qwUserVoiceLog) {
        List<QwUserVoiceLogTotalVo> qwUserVoiceLogTotalVos = baseMapper.selectQwUserVoiceLogTotalList(qwUserVoiceLog);
        Set<Long> list = qwUserVoiceLogTotalVos.stream().map(QwUserVoiceLogTotalVo::getCompanyUserId).collect(Collectors.toSet());
        if(list != null && !list.isEmpty()){
            List<CompanyUser> companyUserList = companyUserMapper.selectCompanyUserByIds(list);

            // 优化：使用Map提高查找效率，避免双重循环
            Map<Long, CompanyUser> companyUserMap = companyUserList.stream()
                    .collect(Collectors.toMap(CompanyUser::getUserId, user -> user, (existing, replacement) -> existing));

            // 如果有部门过滤条件，则预先过滤用户列表
            if (qwUserVoiceLog.getDeptId() != null) {
                Set<Long> deptIds = companyDeptMapper.selectChildrenDeptById(qwUserVoiceLog.getDeptId()).stream().map(CompanyDept::getDeptId).collect(Collectors.toSet());
                companyUserMap.entrySet().removeIf(entry ->
                        entry.getValue().getDeptId() == null ||
                                !deptIds.contains(entry.getValue().getDeptId()));//需要deptId及其下级的部门
//                                !entry.getValue().getDeptId().equals(qwUserVoiceLog.getDeptId()));
            }

            // 设置用户姓名和部门ID
            qwUserVoiceLogTotalVos.forEach(logVo -> {
                CompanyUser user = companyUserMap.get(logVo.getCompanyUserId());
                if (user != null) {
                    logVo.setCompanyUserName(user.getNickName());
                    if (user.getDeptId() != null) {
                        logVo.setDeptId(user.getDeptId());
                    }
                }
            });

            // 如果有部门过滤条件，过滤掉没有部门ID的记录
            if (qwUserVoiceLog.getDeptId() != null) {
                qwUserVoiceLogTotalVos = qwUserVoiceLogTotalVos.stream()
                        .filter(m -> m.getDeptId() != null)
                        .collect(Collectors.toList());
            }
        }

        List<QwCompany> companyList = qwCompanyService.selectQwCompanyList(new QwCompany());
        // 优化：使用Map提高查找效率
        Map<String, String> corpIdToNameMap = companyList.stream()
                .collect(Collectors.toMap(QwCompany::getCorpId, QwCompany::getCorpName, (existing, replacement) -> existing));

        qwUserVoiceLogTotalVos.forEach(m -> {
            String corpName = corpIdToNameMap.get(m.getCorpId());
            if (corpName != null) {
                m.setCorpName(corpName);
            }
        });

        String companyUserName = qwUserVoiceLog.getCompanyUserName();
        if(companyUserName != null && !companyUserName.isEmpty()){
            qwUserVoiceLogTotalVos = qwUserVoiceLogTotalVos.stream()
                    .filter(n -> n.getCompanyUserName() != null && n.getCompanyUserName().contains(companyUserName))
                    .collect(Collectors.toList());
        }
        return qwUserVoiceLogTotalVos;
    }

    @Override
    public void addQuUserVoiceByIpadCallback(Long id, Long extUserId, Integer recordType, Long totalSeconds, String uuid) {
        // 参数校验
        if (id == null || (extUserId == null && uuid == null)) {
            log.error("参数校验失败: id={}, extUserId={}, uuid={}", id, extUserId, uuid);
            return;
        }

        try {
            QwUser sendUser = qwUserMapper.selectQwUserById(id);
            if (sendUser != null) {
                String extId = getExtId(extUserId, uuid, sendUser.getServerId());
                // 检查extId是否有效
                if (extId == null || extId.isEmpty()) {
                    log.error("获取外部联系人ID失败,qwUserId:" + id + "，extUserId:" + extUserId + "，uuid:" + uuid);
                    return;
                }

                QwExternalContact qwExternalContacts = qwExternalContactMapper.selectQwExternalContactByExternalUserIdAndQwUserId(extId, sendUser.getCorpId(), sendUser.getQwUserId());
                if (qwExternalContacts == null) {
                    log.error("未找到外部联系人,qwUserId:" + id + "，extId:" + extId);
                    return;
                }

                QwUserVoiceLog qwUserVoiceLog = new QwUserVoiceLog();
                qwUserVoiceLog.setCorpId(sendUser.getCorpId());
                qwUserVoiceLog.setExtId(qwExternalContacts.getId());
                qwUserVoiceLog.setQwUserId(sendUser.getId());
                qwUserVoiceLog.setCompanyId(qwExternalContacts.getCompanyId());
                if (qwExternalContacts.getCompanyUserId() != null) {
                    qwUserVoiceLog.setCompanyUserId(qwExternalContacts.getCompanyUserId());
                }

                if (recordType == 2) {//2是未接通的处理
                    qwUserVoiceLog.setStatus(recordType);
                    qwUserVoiceLog.setTitle("通话拒接");
                }else if(recordType == 3){
                    qwUserVoiceLog.setStatus(recordType);
                    qwUserVoiceLog.setTitle("通话未接听");
                } else {
                    qwUserVoiceLog.setStatus(1);
                    if (totalSeconds != null) {
                        qwUserVoiceLog.setDuration(totalSeconds);
                    } else {
                        qwUserVoiceLog.setDuration(0L);
                    }
                    qwUserVoiceLog.setTitle("通话已接听");
                }
                qwUserVoiceLog.setCreateTime(new Date());

                int insert = baseMapper.insertQwUserVoiceLog(qwUserVoiceLog);
                // 插入成功的情况下就处理定时任务
                if (insert == 1) {
                    List<QwWorkTask> qwWorkTaskList = qwWorkTaskMapper.selectQwWorkTaskByExtIdAndQwUserId(qwUserVoiceLog);
                    if (qwWorkTaskList != null && !qwWorkTaskList.isEmpty()) {
                        for (QwWorkTask qwWorkTask : qwWorkTaskList) {
                            try {
                                if (qwUserVoiceLog.getStatus() == 1L) {//接通电话
                                    qwWorkTask.setTrackType(3);//1正常处理 2 未接听 3 已接听
                                    qwWorkTask.setDuration(qwUserVoiceLog.getDuration());
                                } else {
                                    qwWorkTask.setTrackType(2);//1正常处理 2 未接听 3 已接听
                                }
                                qwWorkTask.setStatus(1);//0 待处理 1 已处理 3 过期
                                qwWorkTask.setUpdateTime(new Date());
                                qwWorkTaskMapper.updateQwWorkTask(qwWorkTask);
                            } catch (Exception e) {
                                log.error("更新任务状态失败, taskId: " + qwWorkTask.getId(), e);
                            }
                        }
                    }
                } else {
                    log.error("插入失败,qwUserId:" + id + "，extId:" + extUserId + "，uuid:" + uuid + "，totalSeconds" + totalSeconds);
                }
            } else {
                log.error("未找到企微用户,id:" + id + "，extId:" + extUserId + "，uuid:" + uuid + "，totalSeconds" + totalSeconds);
            }
        } catch (Exception e) {
            log.error("处理通话回调异常, id:" + id + "，extUserId:" + extUserId + "，recordType:" + recordType + "，totalSeconds:" + totalSeconds + "，uuid:" + uuid, e);
        }
    }

    String getExtId(Long id,String uid,Long serverId){
        WxWorkVid2UserIdDTO wxWorkVid2UserIdDTO = new WxWorkVid2UserIdDTO();
        wxWorkVid2UserIdDTO.setUser_id(Arrays.asList(id));
        wxWorkVid2UserIdDTO.setUuid(uid);
        WxWorkResponseDTO<List<WxWorkVid2UserIdRespDTO>> WxWorkVid2UserIdRespDTO = wxWorkService.Vid2UserId(wxWorkVid2UserIdDTO,serverId);
        List<WxWorkVid2UserIdRespDTO> data = WxWorkVid2UserIdRespDTO.getData();
        if (data==null || data.isEmpty()){
            System.out.println("未获取到extId,uid:" + uid);
            return "";
        }
        com.fs.wxwork.dto.WxWorkVid2UserIdRespDTO dto = data.get(0);
        return dto.getOpenid();
    }
}
