package com.fs.aiSipCall.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.aiSipCall.domain.AiSipCallPhone;
import com.fs.aiSipCall.domain.AiSipCallTask;
import com.fs.aiSipCall.dto.CallTaskStatModel;
import com.fs.aiSipCall.dto.CommonPhoneModel;
import com.fs.aiSipCall.mapper.AiSipCallPhoneMapper;
import com.fs.aiSipCall.mapper.AiSipCallTaskMapper;
import com.fs.aiSipCall.service.IAiSipCallPhoneService;
import com.fs.aiSipCall.utils.DateUtils;
import com.fs.company.mapper.CompanyMapper;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.vo.OptionsVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * aiSIP外呼通话记录Service业务层处理
 *
 * @author fs
 * @date 2026-03-06
 */
@Service
public class AiSipCallPhoneServiceImpl extends ServiceImpl<AiSipCallPhoneMapper, AiSipCallPhone> implements IAiSipCallPhoneService {

    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private AiSipCallTaskMapper callTaskMapper;


    /**
     * 查询aiSIP外呼通话记录
     *
     * @param id aiSIP外呼通话记录主键
     * @return aiSIP外呼通话记录
     */
    @Override
    public AiSipCallPhone selectAiSipCallPhoneById(String id) {
        return baseMapper.selectAiSipCallPhoneById(id);
    }

    @Override
    public int logicalDeletionByBatchIds(Long[] batchIds) {
        return baseMapper.logicalDeletionByBatchIds(batchIds);
    }

    /**
     * 查询aiSIP外呼通话记录列表
     *
     * @param aiSipCallPhone aiSIP外呼通话记录
     * @return aiSIP外呼通话记录
     */
    @Override
    public List<AiSipCallPhone> selectAiSipCallPhoneList(AiSipCallPhone aiSipCallPhone) {

        if (aiSipCallPhone.getTimeLenStart() != null) {
            aiSipCallPhone.setTimeLenStart(aiSipCallPhone.getTimeLenStart() * 60 * 1000L);
        }
        if (aiSipCallPhone.getTimeLenEnd() != null) {
            aiSipCallPhone.setTimeLenEnd(aiSipCallPhone.getTimeLenEnd() * 60 * 1000L);
        }
        if (StringUtils.isNotBlank(aiSipCallPhone.getCalloutTimeStart())) {
            aiSipCallPhone.setCalloutTimeStartLong(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", aiSipCallPhone.getCalloutTimeStart()).getTime());
        }
        if (StringUtils.isNotBlank(aiSipCallPhone.getCalloutTimeEnd())) {
            aiSipCallPhone.setCalloutTimeEndLong(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", aiSipCallPhone.getCalloutTimeEnd()).getTime());
        }
        if (StringUtils.isNotBlank(aiSipCallPhone.getAnsweredTimeStart())) {
            aiSipCallPhone.setAnsweredTimeStartLong(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", aiSipCallPhone.getAnsweredTimeStart()).getTime());
        }
        if (StringUtils.isNotBlank(aiSipCallPhone.getAnsweredTimeEnd())) {
            aiSipCallPhone.setAnsweredTimeEndLong(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", aiSipCallPhone.getAnsweredTimeEnd()).getTime());
        }

        if (StringUtils.isNotBlank(aiSipCallPhone.getCallEndTimeStart())) {
            aiSipCallPhone.setCallEndTimeStartLong(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", aiSipCallPhone.getCallEndTimeStart()).getTime());
        }
        if (StringUtils.isNotBlank(aiSipCallPhone.getCallEndTimeEnd())) {
            aiSipCallPhone.setCallEndTimeEndLong(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", aiSipCallPhone.getCallEndTimeEnd()).getTime());
        }

        if (StringUtils.isNotBlank(aiSipCallPhone.getCreatetimeStart())) {
            aiSipCallPhone.setCreatetimeStartLong(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", aiSipCallPhone.getCreatetimeStart()).getTime());
        }
        if (StringUtils.isNotBlank(aiSipCallPhone.getCreatetimeEnd())) {
            aiSipCallPhone.setCreatetimeEndLong(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", aiSipCallPhone.getCreatetimeEnd()).getTime());
        }
        List<AiSipCallPhone> list = baseMapper.selectAiSipCallPhoneList(aiSipCallPhone);
        if(!CollectionUtils.isEmpty(list)){
            // 批量查询公司名称
            Map<Long, String> companyNameMap = buildCompanyNameMap(list);
            // 批量查询批次名称
            Map<Long, String> batchNameMap = buildBatchNameMap(list);

            // 处理每条记录
            list.forEach(data -> processCallRecord(data, companyNameMap, batchNameMap));
        }
        return list;
    }

    /**
     * 新增aiSIP外呼通话记录
     *
     * @param aiSipCallPhone aiSIP外呼通话记录
     * @return 结果
     */
    @Override
    public int insertAiSipCallPhone(AiSipCallPhone aiSipCallPhone) {
        return baseMapper.insertAiSipCallPhone(aiSipCallPhone);
    }

    /**
     * 修改aiSIP外呼通话记录
     *
     * @param aiSipCallPhone aiSIP外呼通话记录
     * @return 结果
     */
    @Override
    public int updateAiSipCallPhone(AiSipCallPhone aiSipCallPhone) {
        return baseMapper.updateAiSipCallPhone(aiSipCallPhone);
    }

    /**
     * 批量删除aiSIP外呼通话记录
     *
     * @param ids 需要删除的aiSIP外呼通话记录主键
     * @return 结果
     */
    @Override
    public int deleteAiSipCallPhoneByIds(String[] ids) {
        return baseMapper.deleteAiSipCallPhoneByIds(ids);
    }

    /**
     * 删除aiSIP外呼通话记录信息
     *
     * @param id aiSIP外呼通话记录主键
     * @return 结果
     */
    @Override
    public int deleteAiSipCallPhoneById(String id) {
        return baseMapper.deleteAiSipCallPhoneById(id);
    }

    @Override
    public List<CallTaskStatModel> statByBatchIds(List<Long> batchIds) {
        List<CallTaskStatModel> callTaskStatModels = baseMapper.statByBatchIds(batchIds);
        callTaskStatModels.forEach(callTaskStatModel -> {
            if (null == callTaskStatModel.getPhoneCount()) {
                callTaskStatModel.setPhoneCount(0);
            }
            if (null == callTaskStatModel.getCallCount()) {
                callTaskStatModel.setCallCount(0);
            }
            if (null == callTaskStatModel.getConnectCount()) {
                callTaskStatModel.setConnectCount(0);
            }
        });
        return callTaskStatModels;
    }

    @Override
    public List<String> isDuplicateEntry(Long batchId, List<CommonPhoneModel> phoneList) {
        return baseMapper.isDuplicateEntry(batchId, phoneList);
    }

    public List<AiSipCallPhone> selectCurrentDayCallRecords(Long startMillis, Long endMillis) {
        return baseMapper.selectCurrentDayCallRecords(startMillis, endMillis);
    }




    /**
     * 构建公司名称映射
     */
    private Map<Long, String> buildCompanyNameMap(List<AiSipCallPhone> list) {
        List<Long> companyIds = list.stream()
                .map(AiSipCallPhone::getCompanyId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        if (companyIds.isEmpty()) {
            return Collections.emptyMap();
        }

        List<OptionsVO> companyOptions = companyMapper.selectByIds(companyIds);
        return companyOptions.stream()
                .collect(Collectors.toMap(OptionsVO::getDictValue, OptionsVO::getDictLabel, (v1, v2) -> v1));
    }

    /**
     * 构建批次名称映射
     */
    private Map<Long, String> buildBatchNameMap(List<AiSipCallPhone> list) {
        List<Long> localBatchIds = list.stream()
                .map(AiSipCallPhone::getLocalBatchId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        if (localBatchIds.isEmpty()) {
            return Collections.emptyMap();
        }

        List<AiSipCallTask> tasks = callTaskMapper.selectByIds(localBatchIds);
        return tasks.stream()
                .collect(Collectors.toMap(AiSipCallTask::getBatchId, AiSipCallTask::getBatchName, (v1, v2) -> v1));
    }

    /**
     * 处理单条通话记录
     */
    private void processCallRecord(AiSipCallPhone data, Map<Long, String> companyNameMap, Map<Long, String> batchNameMap) {
        // 设置公司名称
        if (data.getCompanyId() != null) {
            data.setCompanyName(companyNameMap.getOrDefault(data.getCompanyId(), ""));
        }
        // 设置批次名称
        if (data.getLocalBatchId() != null) {
            data.setBatchName(batchNameMap.getOrDefault(data.getLocalBatchId(), ""));
        }
        // 设置呼叫状态名称
        data.setCallstatusName(AiSipCallPhone.getCallStatusName(data.getCallstatus(), data.getUuid()));
        // 格式化时间字段
        formatTimestampField(data.getCalloutTime(), data::setCalloutTimeStr);
        formatTimestampField(data.getConnectedTime(), data::setAnsweredTimeStr);
        formatTimestampField(data.getCallEndTime(), data::setCallEndTimeStr);
        formatTimestampField(data.getCreatetime(), data::setCreatetimeStr);
        // 格式化通话时长
        data.setTimeLenSec(DateUtils.formatTimeLength(data.getTimeLen() / 1000));
        // 处理录音文件路径
        formatWavfilePath(data);
        // 处理电话号码加密显示
        encryptPhoneNumber(data);
    }

    /**
     * 格式化时间戳字段
     */
    private void formatTimestampField(Long timestamp, java.util.function.Consumer<String> setter) {
        if (timestamp != null && timestamp != 0) {
            setter.accept(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date(timestamp)));
        }
    }

    /**
     * 格式化录音文件路径
     */
    private void formatWavfilePath(AiSipCallPhone data) {
        if (StringUtils.isNotBlank(data.getWavfile())) {
            String filename = data.getWavfile().startsWith("/") ? data.getWavfile().substring(1) : data.getWavfile();
            data.setWavfile("/recordings/files?filename=" + filename);
        }
    }

    /**
     * 加密电话号码
     */
    private void encryptPhoneNumber(AiSipCallPhone data) {
        if (StringUtils.isNotBlank(data.getTelephone())) {
            data.setTelephone(PhoneUtil.encryptPhone(data.getTelephone()));
        }
    }
}
