package com.yeejoin.amos.boot.module.jcs.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledFormDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.VoiceRecordFileDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.VoiceRecordLogDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.VoiceRecordLog;
import com.yeejoin.amos.boot.module.jcs.api.mapper.VoiceRecordLogMapper;
import com.yeejoin.amos.boot.module.jcs.api.service.IVoiceRecordLogService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 通话记录记录表服务实现类
 *
 * @author system_generator
 * @date 2021-11-09
 */
@Service
public class VoiceRecordLogServiceImpl extends BaseService<VoiceRecordLogDto,VoiceRecordLog,VoiceRecordLogMapper> implements IVoiceRecordLogService {

    private final Logger logger = LogManager.getLogger(VoiceRecordFileServiceImpl.class);

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    AlertCalledServiceImpl iAlertCalledService;

    @Autowired
    FusionServiceImpl fusionService;

    @Autowired
    VoiceRecordFileServiceImpl voiceRecordFileService;

    @Autowired
    EmqKeeper emqKeeper;

    public final static long ONE_Minute =  60 * 1000;


    @Autowired
    private VoiceRecordFileServiceImpl voiceRecordFileServiceImpl;


//    @Scheduled(fixedDelay=ONE_Minute)
    public void fixedDelayJob(){
        // 设置token
        String logs=JSON.toJSONString(RequestContext.cloneRequestContext());
        logger.info(logs);
        // 首先查找未完成 且失败次数少于5 的 记录
        List<VoiceRecordLog> logList = this.list(new LambdaQueryWrapper<VoiceRecordLog>().eq(VoiceRecordLog::getIsDeal,false).lt(VoiceRecordLog::getDealTimes,5));
        if(logList != null && logList.size() >0) {
            logList.stream().forEach(l -> {
                // 保存录音 修改状态 发送mqtt 通知
                // 获取通话人信息
                Integer dealTimes = 1;
                if(l.getDealTimes() != null) {
                    dealTimes += l.getDealTimes();
                }
                l.setDealTimes(dealTimes);
                Map<String, String> map = fusionService.getCallRecordByCID(l.getConnectId());

                VoiceRecordFileDto model = new VoiceRecordFileDto();
                model.setAlertId(l.getAlertId());
                model.setCaller(map.get("caller"));
                model.setCalled(map.get("called"));

                Date telStartTime = null;
                Date telEndTime = null;
                try {
                    telStartTime = DateUtils.longStr2Date(map.get("createTime"));
                    telEndTime = DateUtils.longStr2Date(map.get("releaseTime"));
                } catch (Exception e) {
                    this.updateById(l);
                    return;
                }
                model.setTelTime(DateUtils.secondsToTimeStr(Integer.valueOf(map.get("timeLength"))));
                model.setTelStartTime(telStartTime);
                model.setTelEndTime(telEndTime);
                if(1 == Integer.valueOf(map.get("callType"))) {
                    model.setFileType("客户呼入");
                } else if(2 == Integer.valueOf(map.get("callType"))) {
                    model.setFileType("坐席呼出");
                }

                Map<String, String> downloadFile = null;

                if(downloadFile.isEmpty()) {
                    this.updateById(l);
                    return;
                }
                for(Map.Entry<String,String> file : downloadFile.entrySet()) {
                    model.setFilePath(file.getKey());
                }
            });
        }

        logger.info("执行通话记录任务");

    }
}