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

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.tzs.api.dto.AlertCalledFormDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.VoiceRecordFileDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.VoiceRecordLogDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.VoiceRecordLog;
import com.yeejoin.amos.boot.module.tzs.api.mapper.VoiceRecordLogMapper;
import com.yeejoin.amos.boot.module.tzs.api.service.ICtiService;
import com.yeejoin.amos.boot.module.tzs.api.service.IVoiceRecordLogService;
import com.yeejoin.amos.component.feign.config.TokenOperation;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.IdPasswordAuthModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
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.HashMap;
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
    ICtiService ctiService;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    AlertCalledServiceImpl iAlertCalledService;

    @Autowired
    EmqKeeper emqKeeper;

    public final static long ONE_Minute =  60 * 1000;

    @Value("${mqtt.topic.cti.push}")
    private String ctiMessage;


    @Value("${cti.user.name}")
    private String ctiUserName;

    @Value("${cti.user.pwd}")
    private String ctiUserPwd;


    @Autowired
    private VoiceRecordFileServiceImpl voiceRecordFileServiceImpl;

    @Autowired
    private TzsAuthServiceImpl tzsAuthServiceImpl;

    @Scheduled(fixedDelay=ONE_Minute)
    public void fixedDelayJob(){
        // 设置token
        tzsAuthServiceImpl.setRequestContext();
        // 首先查找未完成 且失败次数少于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);
                JSONArray ctiInfos = ctiService.getCallInfo(l.getConnectId());
                if(ctiInfos == null || ctiInfos.size() == 0) {
                    this.updateById(l);
                    return;
                }
                VoiceRecordFileDto model = new VoiceRecordFileDto();
                JSONObject recordInfo = ctiInfos.getJSONObject(0);
                model.setAlertId(l.getAlertId());
                model.setTel(recordInfo.getString("telephone"));

                Date telStartTime = null;
                Date telEndTime = null;
                try {
                    telStartTime = DateUtils.longStr2Date(recordInfo.getString("connectTime"));
                    telEndTime = DateUtils.longStr2Date(recordInfo.getString("hangupTime"));
                } catch (Exception e) {
                    this.updateById(l);
                    return;
                }
                int times = recordInfo.getIntValue("times");
                model.setTelTime(DateUtils.secondsToTimeStr(times));
                model.setTelStartTime(telStartTime);
                model.setTelEndTime(telEndTime);
                if(1 == recordInfo.getInteger("callType")) {
                    model.setFileType("客户呼入");
                } else if(2 == recordInfo.getInteger("callType")) {
                    model.setFileType("坐席呼出");
                }

                Map<String, String> downloadFile = null;
                try {
                    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.TZS_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("执行通话记录任务");

    }






}