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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.feign.AmosFeignService;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledFormDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledQueryDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.VoiceRecordFileDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.VoiceRecordFile;
import com.yeejoin.amos.boot.module.tzs.api.mapper.VoiceRecordFileMapper;
import com.yeejoin.amos.boot.module.tzs.api.service.ICtiService;
import com.yeejoin.amos.boot.module.tzs.api.service.IVoiceRecordFileService;
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.stereotype.Service;
import org.typroject.tyboot.component.emq.EmqKeeper;
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-08-03
 */
@Service
public class VoiceRecordFileServiceImpl extends BaseService<VoiceRecordFileDto,VoiceRecordFile,VoiceRecordFileMapper> implements IVoiceRecordFileService {

    @Autowired
    private VoiceRecordFileServiceImpl voiceRecordFileServiceImpl;

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

    @Autowired
    AlertCalledServiceImpl iAlertCalledService;

    @Autowired
    ICtiService ctiService;

    private volatile JSONArray ctiInfos;

    @Autowired
    EmqKeeper emqKeeper;

    private String ctiMessage = "/cti/callphone";

    /**
     * 分页查询
     */
    public Page<VoiceRecordFileDto> queryForVoiceRecordFilePage(Page<VoiceRecordFileDto> page)   {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<VoiceRecordFileDto> queryForVoiceRecordFileList()   {
        return this.queryForList("" , false);
    }



    @Override
    public void publishRecord(final VoiceRecordFileDto model) {

            Long now = System.currentTimeMillis();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        Long end = System.currentTimeMillis();
                // 获取通话人信息
                ctiInfos = ctiService.getCallInfo(model.getConnectId());
                if(ctiInfos == null || ctiInfos.size() == 0) {
                    logger.error("未找到通话详单信息" + (end-now));
                }
                JSONObject recordInfo = ctiInfos.getJSONObject(0);
                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) {
                    logger.error("日期转换错误");
                }
                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 = ctiService.downLoadRecordFile(recordInfo.getString("connectionid"));
                if(downloadFile.isEmpty()) {
                    logger.error("未找到附件文件");
                }
                for(Map.Entry<String,String> file : downloadFile.entrySet()) {
                    model.setFilePath(file.getKey());
                }
                AlertCalledFormDto alertDto = iAlertCalledService.selectAlertCalledByIdNoCache(model.getAlertId());
                if(alertDto == null || alertDto.getAlertCalledDto() == null) {
                    logger.error("未找到相关警情");
                }
                model.setAlertStage(alertDto.getAlertCalledDto().getAlertStage());
                model.setAlertStageCode(alertDto.getAlertCalledDto().getAlertStageCode());
                model.setSourceId(-1l);
                voiceRecordFileServiceImpl.createWithModel(model);
                JSONObject json = new JSONObject();
                json.put("code","1001");
                json.put("type","addRecord");
                try {
                    emqKeeper.getMqttClient().publish(ctiMessage, json.toJSONString().getBytes(), 2, false);
                } catch (MqttException e) {
                    logger.error("推送失败");
                }



    }

    @Override
    public Page<VoiceRecordFileDto> queryRecordListByQueryDto(Page<VoiceRecordFileDto> page, String telStartTimeStr, String telEndTimeStr, String fileType, String tel, String workNum, String sortParam, String sortRule) {
        Page<List<VoiceRecordFileDto>>list = baseMapper.queryRecordListByQueryDto(page,
                telStartTimeStr,telEndTimeStr,fileType,tel,
                workNum,sortParam,sortRule);
        Page<VoiceRecordFileDto> page1 = new Page<>();
        List<VoiceRecordFileDto> resultDtoList = JSONArray.parseArray(JSONArray.toJSONString(list.getRecords()),VoiceRecordFileDto.class);
        page1.setCurrent(page.getCurrent());
        page1.setSize(page.getSize());
        page1.setTotal(list.getTotal());
        page1.setRecords(resultDtoList);
        return page1;
    }
}