package com.ruoyi.aicall.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aicall.domain.CcLlmAgentAccount;
import com.ruoyi.aicall.llm.ILlmCapability;
import com.ruoyi.aicall.llm.model.AccountBaseEntity;
import com.ruoyi.aicall.model.CallTaskStatModel;
import com.ruoyi.cc.utils.LlmAccountParser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.aicall.mapper.CcCallPhoneMapper;
import com.ruoyi.aicall.domain.CcCallPhone;
import com.ruoyi.aicall.service.ICcCallPhoneService;
import com.ruoyi.common.core.text.Convert;

/**
 * 外呼号码Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-29
 */
@Service
@Slf4j
public class CcCallPhoneServiceImpl implements ICcCallPhoneService 
{
    @Autowired
    private CcCallPhoneMapper ccCallPhoneMapper;

    /**
     * 查询外呼号码
     * 
     * @param id 外呼号码主键
     * @return 外呼号码
     */
    @Override
    public CcCallPhone selectCcCallPhoneById(String id)
    {
        return ccCallPhoneMapper.selectCcCallPhoneById(id);
    }

    /**
     * 查询外呼号码列表
     * 
     * @param ccCallPhone 外呼号码
     * @return 外呼号码
     */
    @Override
    public List<CcCallPhone> selectCcCallPhoneList(CcCallPhone ccCallPhone)
    {
        normalizeListQueryParams(ccCallPhone);
        return ccCallPhoneMapper.selectCcCallPhoneList(ccCallPhone);
    }

    @Override
    public List<String> selectCcCallPhoneIds(CcCallPhone ccCallPhone) {
        normalizeListQueryParams(ccCallPhone);
        return ccCallPhoneMapper.selectCcCallPhoneIds(ccCallPhone);
    }

    @Override
    public List<CcCallPhone> selectCcCallPhoneLiteByIds(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return new java.util.ArrayList<>();
        }
        return ccCallPhoneMapper.selectCcCallPhoneLiteByIds(ids);
    }

    /**
     * 统一处理列表查询时间参数；已是数值则不再转换，避免重复转换异常
     */
    private void normalizeListQueryParams(CcCallPhone ccCallPhone) {
        Map<String, Object> params = ccCallPhone.getParams();
        if (params == null) {
            params = new HashMap<>();
            ccCallPhone.setParams(params);
            return;
        }
        convertStringDateToMillis(params, "calloutTimeStart");
        convertStringDateToMillis(params, "calloutTimeEnd");
        convertStringDateToMillis(params, "callEndTimeStart");
        convertStringDateToMillis(params, "callEndTimeEnd");
        convertStringDateToMillis(params, "connectedTimeStart");
        convertStringDateToMillis(params, "connectedTimeEnd");
        convertStringDateToMillis(params, "answeredTimeStart");
        convertStringDateToMillis(params, "answeredTimeEnd");
        // 页面时长按“分钟”筛选（历史逻辑）
        convertMinutesToMillis(params, "timeLenStart");
        convertMinutesToMillis(params, "timeLenEnd");
        convertMinutesToMillis(params, "timeLenSecondStart");
        convertMinutesToMillis(params, "timeLenSecondEnd");
        ccCallPhone.setParams(params);
    }

    private void convertStringDateToMillis(Map<String, Object> params, String key) {
        Object value = params.get(key);
        if (!(value instanceof String) || StringUtils.isEmpty((String) value)) {
            return;
        }
        String text = ((String) value).trim();
        if (text.matches("^\\d+$")) {
            params.put(key, Long.parseLong(text));
            return;
        }
        params.put(key, DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", text).getTime());
    }

    private void convertMinutesToMillis(Map<String, Object> params, String key) {
        Object value = params.get(key);
        if (value == null || "".equals(value)) {
            return;
        }
        if (value instanceof Number) {
            return;
        }
        params.put(key, Double.valueOf(value.toString()) * 60 * 1000L);
    }

    /**
     * 新增外呼号码
     * 
     * @param ccCallPhone 外呼号码
     * @return 结果
     */
    @Override
    public int insertCcCallPhone(CcCallPhone ccCallPhone)
    {
        return ccCallPhoneMapper.insertCcCallPhone(ccCallPhone);
    }

    /**
     * 修改外呼号码
     * 
     * @param ccCallPhone 外呼号码
     * @return 结果
     */
    @Override
    public int updateCcCallPhone(CcCallPhone ccCallPhone)
    {
        return ccCallPhoneMapper.updateCcCallPhone(ccCallPhone);
    }

    /**
     * 批量删除外呼号码
     * 
     * @param ids 需要删除的外呼号码主键
     * @return 结果
     */
    @Override
    public int deleteCcCallPhoneByIds(String ids)
    {
        return ccCallPhoneMapper.deleteCcCallPhoneByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除外呼号码信息
     * 
     * @param id 外呼号码主键
     * @return 结果
     */
    @Override
    public int deleteCcCallPhoneById(String id)
    {
        return ccCallPhoneMapper.deleteCcCallPhoneById(id);
    }

    @Override
    public CallTaskStatModel statByBatchId(Long batchId) {
        CallTaskStatModel callTaskStatModel = ccCallPhoneMapper.statByBatchId(batchId);
        return normalizeStat(callTaskStatModel);
    }

    @Override
    public Map<Long, CallTaskStatModel> statByBatchIds(List<Long> batchIds) {
        Map<Long, CallTaskStatModel> result = new HashMap<>();
        if (batchIds == null || batchIds.isEmpty()) {
            return result;
        }
        List<CallTaskStatModel> stats = ccCallPhoneMapper.statByBatchIds(batchIds);
        if (stats != null) {
            for (CallTaskStatModel stat : stats) {
                CallTaskStatModel normalized = normalizeStat(stat);
                if (normalized.getBatchId() != null) {
                    result.put(normalized.getBatchId(), normalized);
                }
            }
        }
        return result;
    }

    private CallTaskStatModel normalizeStat(CallTaskStatModel callTaskStatModel) {
        if (callTaskStatModel == null) {
            callTaskStatModel = new CallTaskStatModel();
        }
        if (null == callTaskStatModel.getPhoneCount()) {
            callTaskStatModel.setPhoneCount(0);
        }
        if (null == callTaskStatModel.getCallCount()) {
            callTaskStatModel.setCallCount(0);
        }
        if (null == callTaskStatModel.getConnectCount()) {
            callTaskStatModel.setConnectCount(0);
        }
        return callTaskStatModel;
    }

    @Override
    public void batchInsertCcCallPhone(List<CcCallPhone> phoneList) {
        if (phoneList.size() <= 0) {
            return;
        }
        ccCallPhoneMapper.batchInsertCcCallPhone(phoneList);
    }

    @Override
    public List<CcCallPhone> getCustIntentionList() {
        return ccCallPhoneMapper.getCustIntentionList();
    }

    @Override
    public void updateIntentionByIds(String intention, List<String> phoneIds) {
        if (StringUtils.isBlank(intention) || phoneIds.size() <= 0) {
            return;
        }
        ccCallPhoneMapper.updateIntentionByIds(intention, phoneIds);
    }

    @Override
    public String getIntenetionByDialogue(CcLlmAgentAccount ccLlmAgentAccount, String dialogue) {
        try {
            ILlmCapability llmAccount;
            String provider = ccLlmAgentAccount.getProviderClassName();
            AccountBaseEntity account =  LlmAccountParser.parse(ccLlmAgentAccount);
            llmAccount = (ILlmCapability) (Class.forName("com.ruoyi.aicall.llm.impl." + provider).newInstance());
            JSONArray dialogueContents = JSONArray.parseArray(dialogue);
            log.info("account:{}", JSONObject.toJSONString(account));
            llmAccount.setAccount(account);
            String intention = llmAccount.getIntentionByTips(ccLlmAgentAccount, dialogueContents);
            return intention;
        } catch (Exception e) {

        }
        return "";
    }

    @Override
    public List<CcCallPhone> selectNoHangupCalls(Long batchId) {
        return ccCallPhoneMapper.selectNoHangupCalls(batchId);
    }

    @Override
    public void bakCallPhoneByBatchId(Long batchId) {
        ccCallPhoneMapper.bakCallPhoneByBatchId(batchId);
    }

    @Override
    public void delCallPhoneByBatchId(Long batchId) {
        ccCallPhoneMapper.delCallPhoneByBatchId(batchId);
    }
    /**
     * 查询外呼号码列表
     *
     * @param ccCallPhone 外呼号码
     * @return 外呼号码
     */
    @Override
    public List<CcCallPhone> selectCcCallPhoneYlrzList(CcCallPhone ccCallPhone)
    {
        Map<String, Object> params = ccCallPhone.getParams();
        if (null == params) {
            params = new HashMap<>();
        }
        if (null != params.get("timeLenStart")
                && !"".equals(params.get("timeLenStart"))) {
            params.put("timeLenStart", Double.valueOf((String)params.get("timeLenStart")) * 60 * 1000L);
        }
        if (null != params.get("timeLenEnd")
                && !"".equals(params.get("timeLenEnd"))) {
            params.put("timeLenEnd", Double.valueOf((String)params.get("timeLenEnd")) * 60 * 1000L);
        }
        if (null != params.get("calloutTimeStart")
                && !"".equals(params.get("calloutTimeStart"))) {
            params.put("calloutTimeStart", DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", (String)params.get("calloutTimeStart")).getTime());
        }
        if (null != params.get("calloutTimeEnd")
                && !"".equals(params.get("calloutTimeEnd"))) {
            params.put("calloutTimeEnd", DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", (String)params.get("calloutTimeEnd")).getTime());
        }
        if (null != params.get("answeredTimeStart")
                && !"".equals(params.get("answeredTimeStart"))) {
            params.put("answeredTimeStart", DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", (String)params.get("answeredTimeStart")).getTime());
        }
        if (null != params.get("answeredTimeEnd")
                && !"".equals(params.get("answeredTimeEnd"))) {
            params.put("answeredTimeEnd", DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", (String)params.get("answeredTimeEnd")).getTime());
        }
        if (null != params.get("callEndTimeStart")
                && !"".equals(params.get("callEndTimeStart"))) {
            params.put("callEndTimeStart", DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", (String)params.get("callEndTimeStart")).getTime());
        }
        if (null != params.get("callEndTimeEnd")
                && !"".equals(params.get("callEndTimeEnd"))) {
            params.put("callEndTimeEnd", DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", (String)params.get("callEndTimeEnd")).getTime());
        }
        ccCallPhone.setParams(params);
        return ccCallPhoneMapper.selectCcCallPhoneYlrzList(ccCallPhone);
    }
    @Override
    public List<CcCallPhone> selectCcCallPhoneListByIds(List<String> callPhoneIds) {
        return ccCallPhoneMapper.selectCcCallPhoneListByIds(callPhoneIds);
    }

    @Override
    public String selectCcCallPhoneDialogueByUuid(String uuid) {
        return ccCallPhoneMapper.selectCcCallPhoneDialogueByUuid(uuid);
    }
}
