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
        System.out.println(JSON.toJSONString(RequestContext.cloneRequestContext()));
        // 首先查找未完成 且失败次数少于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());
//                if(ctiInfos == null || ctiInfos.size() == 0) {
//                    this.updateById(l);
//                    return;
//                }
                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;
                try {
//                    JSONObject jsonObject = fusionService.getCallRecordByCID(l.getConnectId());
//                    Map<String, String> map = voiceRecordFileService.getResult(jsonObject);
//                    downloadFile = ctiService.downLoadRecordFile(recordInfo.getString("connectionid"));
                } catch (Exception e) {
                    e.printStackTrace();
                    this.updateById(l);
                    return;
                }
                if(downloadFile.isEmpty()) {
                    this.updateById(l);
                    return;
                }
                for(Map.Entry<String,String> file : downloadFile.entrySet()) {
                    model.setFilePath(file.getKey());
                }
//                AlertCalledFormDto alertDto = iAlertCalledService.selectAlertCalledByIdNoCache(model.getAlertId());
//                if(alertDto == null || alertDto.getAlertCalledDto() == null) {
//                    this.updateById(l);
//                    return;
//                }
//                model.setAlertStage(alertDto.getAlertCalledDto().getAlertStage());
//                model.setAlertStageCode(alertDto.getAlertCalledDto().getAlertStageCode());
//                model.setSourceId(-1l);
//                voiceRecordFileServiceImpl.createWithModel(model);
//                JSONObject json = new JSONObject();
//                json.put("alertId",model.getAlertId());
//                try {
//                    emqKeeper.getMqttClient().publish(ctiMessage, json.toJSONString().getBytes(), 2, false);
//                    try {
//                        redisUtils.del(RedisKey.jcs_ALERTCALLED_ID+model.getAlertId());
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        logger.error("删除redis失败:" + e.getMessage());
//                    }
//                } catch (MqttException e) {
//                    logger.error("推送失败");
//                }
//                l.setIsDeal(true);
//                this.updateById(l);
            });
        }

        System.out.println("执行通话记录任务");

    }
}