/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.xrtygis.service.callCenter.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.core.util.StringUtil;
import com.tofly.xrtygis.config.RecordFile;
import com.tofly.xrtygis.custom.entity.callCenter.FlowNum;
import com.tofly.xrtygis.custom.entity.callCenter.dto.MissedCallsDto;
import com.tofly.xrtygis.custom.entity.vo.UserDeptHotlineVo;
import com.tofly.xrtygis.custom.service.EmergencyService;
import com.tofly.xrtygis.custom.service.NewHotlineService;
import com.tofly.xrtygis.custom.service.export.ExportCommonCodeService;
import com.tofly.xrtygis.custom.util.RecordAPIUtil;
import com.tofly.xrtygis.entity.callCenter.PltCalllist1000;
import com.tofly.xrtygis.entity.callCenter.CallSearch;
import com.tofly.xrtygis.callCenterMapper.PltCalllist1000Mapper;
import com.tofly.xrtygis.entity.vo.DmaCalculatePramVo;
import com.tofly.xrtygis.service.callCenter.service.PltCalllist1000Service;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 通话记录(话单)坐席或分机之间呼叫只产生一条记录
 *
 * @author wangjieliu
 * @date Thu Jun 17 00:00:00 CST 2021
 */
@Service("pltCalllist1000Service")
@AllArgsConstructor
public class PltCalllist1000ServiceImpl extends ServiceImpl<PltCalllist1000Mapper, PltCalllist1000> implements PltCalllist1000Service {

    private final EmergencyService emergencyService;
    private final NewHotlineService newHotlineService;
    private final ExportCommonCodeService exportCommonCodeService;
    private final RecordFile recordFile;

    private final static Date STAER_DATE = DateUtil.getFirstDayOfMonth();
    private final static Date END_DATE = DateUtil.getLastDayOfMonth();


    @Override
    public IPage<PltCalllist1000> getPltCalllist(Page page, CallSearch search) {
        String telePhone = search.getTelephone();
        String sysphone = search.getSysphone();
        String empCode = search.getEmpcode();
        Long callType = search.getCallType();
        String connectionid = search.getConnectionid();
        Date startTime = search.getStartTime();
        Date endTime = search.getEndTime();
        Integer callState = search.getCallState();


        //按条件查询
        IPage<PltCalllist1000> pltCalllistIPage = this.page(page, Wrappers.<PltCalllist1000>lambdaQuery()
                .eq(StringUtil.isNotEmpty(connectionid), PltCalllist1000::getConnectionid, connectionid)
                .like(StringUtil.isNotEmpty(telePhone), PltCalllist1000::getTelephone, telePhone)
                //无人接听就不用筛选是否评分情况
//                .isNull(StringUtil.isNull(callState) , PltCalllist1000::getIsGrade)
                //必须是通话；如果callState=2；代表无人接听
                .isNotNull(StringUtil.isNull(callState),PltCalllist1000::getEmpcode)
                .isNotNull(PltCalllist1000::getEmpcode)
                .ne(PltCalllist1000::getEmpcode,"")
                .eq(StringUtil.isNotEmpty(sysphone), PltCalllist1000::getSysphone, sysphone)
                .eq(StringUtil.isNotEmpty(empCode), PltCalllist1000::getEmpcode, empCode)
                .eq(StringUtil.isNotNull(callType), PltCalllist1000::getCallType, callType)
                .le(StringUtil.isNotNull(endTime) , PltCalllist1000::getCallTime , endTime)
                .ge(StringUtil.isNotNull(startTime) , PltCalllist1000::getCallTime , startTime)
                .eq(StringUtil.isNotNull(callState) , PltCalllist1000::getCallResult , callState)
                .select(PltCalllist1000::getId, PltCalllist1000::getConnectionid, PltCalllist1000::getCallType, PltCalllist1000::getTelephone, PltCalllist1000::getSysphone,
                        PltCalllist1000::getCallTime, PltCalllist1000::getConnectTime, PltCalllist1000::getQueueTime, PltCalllist1000::getGetfreeTime, PltCalllist1000::getHangupTime,
                        PltCalllist1000::getTimes, PltCalllist1000::getAgentFirstringTime, PltCalllist1000::getAgentFirstconnectTime,
                        PltCalllist1000::getCallResult, PltCalllist1000::getEmpcode, PltCalllist1000::getDeptid , PltCalllist1000::getRecordFile)
                .orderByDesc(PltCalllist1000::getId));

        List<PltCalllist1000> pltCalllistList = pltCalllistIPage.getRecords();

        if (StringUtil.isNotNull(pltCalllistList) && pltCalllistList.size() > 0) {
            //获取部门、员工
//            List<PltDepartment> departmentList = pltDepartmentService.list(Wrappers.<PltDepartment>lambdaQuery().select(PltDepartment::getId, PltDepartment::getName));
//            List<PltEmployee> employeeList = pltEmployeeService.list(Wrappers.<PltEmployee>lambdaQuery().select(PltEmployee::getName, PltEmployee::getCode));
//            Map<Long, String> deptMap = new HashMap();
//            Map<String, String> empMap = new HashMap<>();
//            if (StringUtil.isNotNull(departmentList) && departmentList.size() > 0) {
//                //转MAP
//                deptMap = departmentList.stream().collect(Collectors.toMap(PltDepartment::getId, PltDepartment::getName));
//            }
//            if (StringUtil.isNotNull(employeeList) && employeeList.size() > 0) {
//                //转MAP
//                empMap = employeeList.stream().collect(Collectors.toMap(PltEmployee::getCode, PltEmployee::getName));
//            }
//            Map<Long, String> finalDeptMap = deptMap;
//            Map<String, String> finalEmpMap = empMap;
            Map<Long, String> map = newHotlineService.gerDeptNameMap().stream().collect(Collectors.toMap(UserDeptHotlineVo::getDeptId, UserDeptHotlineVo::getDeptName, (key1, key2) -> key2));
            Map<String, String> realNameMap = newHotlineService.getRealNameMap().stream().collect(Collectors.toMap(UserDeptHotlineVo::getUserCode, UserDeptHotlineVo::getUserName, (key1, key2) -> key2));
            pltCalllistList.forEach(k -> {
                //编码替换成中文
                if (StringUtil.isNotEmpty(k.getDeptid())) {
                    String deptName = map.get(Long.parseLong(k.getDeptid()));
                    if(!StringUtils.isEmpty(deptName)){
                        k.setDeptName(deptName);
                   }

                }
                if(StringUtil.isNotEmpty(k.getEmpcode())){
                    String userName = realNameMap.get(k.getEmpcode());
                    if(!StringUtils.isEmpty(userName)){
                        k.setEmpName(userName);
                    }
                }
                //编码替换成中文
//                k.setEmpName(finalEmpMap.get());
            });

//            //如果需要查满意度
//            if ("1".equals(isSatis)) {
//                //将流水号单独提取出来
//                List<String> collectIds = pltCalllistList.stream().map(PltCalllist1000::getConnectionid).collect(Collectors.toList());
//                //查询对应通话记录的满意度按键值
//                List<ServiceList1000> serviceList = serviceList1000Service.list(Wrappers.<ServiceList1000>lambdaQuery()
//                        .in(ServiceList1000::getConnectionid, collectIds)
//                        .select(ServiceList1000::getConnectionid, ServiceList1000::getSatisfactionScore));
//                //查询满意度按键值定义
//                List<SatisfactionPresskeys> satisfactionPresskeysList = satisfactionPresskeysService
//                        .list(Wrappers.<SatisfactionPresskeys>lambdaQuery()
//                                .select(SatisfactionPresskeys::getPressKey, SatisfactionPresskeys::getPressName));
//                //转MAP
//                Map<String, String> keyAndName = satisfactionPresskeysList.stream()
//                        .collect(Collectors.toMap(SatisfactionPresskeys::getPressKey, SatisfactionPresskeys::getPressName));
//                //存放通话记录与满意度MAP
//                Map<String, String> conneAndSatname = new HashMap<>();
//                for (ServiceList1000 k : serviceList) {
//                    conneAndSatname.put(k.getConnectionid(), keyAndName.get(k.getSatisfactionScore()));
//                }
//                pltCalllistList.forEach(k -> {
//                    k.setSatisfactionName(conneAndSatname.get(k.getConnectionid()));
//                });
//            }
//            pltCalllistIPage.setRecords(pltCalllistList);
            return pltCalllistIPage;
        }
        return pltCalllistIPage;
    }

    /**
     * 获取未接来电信息
     *
     * @param dto 条件
     * @return list
     */
    @Override
    public List<Map<String, Object>> missedCalls(MissedCallsDto dto) {
        if (!StringUtils.isEmpty(dto.getPhoneNumber())){
            String s = "'%" + dto.getPhoneNumber() + "%'";
            dto.setPhoneNumber(s);
        }
        return baseMapper.missedCalls(dto);
    }

    /**
     * 获取当天呼入个数
     *
     * @return map
     */
    @Override
    public Map<String,Long> getCallInCount() {
        FlowNum entry = baseMapper.getFlowNum();
        Long flowNum=0L;
        Long blockCallNum=0L;
        if(entry!=null){
             flowNum = entry.getFlowNum();
             blockCallNum = entry.getBlockCallNum();
        }

        //获取当天时间
        String currentDay = DateUtil.parseDateToStr("yyyy-MM-dd", Date8Util.getCurrentDate());

        Long count = baseMapper.getCallInCount(currentDay);
        Long notCallInCount = baseMapper.getNotCallInCount(currentDay);
        //如果当天流量超过设定的流量预警数，则创建一条应急记录
        if (count > flowNum){
            saveEmerSys(flowNum);
        }
        if (notCallInCount > blockCallNum){
            saveEmerSys2(blockCallNum);
        }
        Map<String,Long> map = new HashMap<>();
        map.put("flowNum",flowNum);
        map.put("blockCallNum",blockCallNum);
        map.put("inbound",count);
        map.put("notCall",notCallInCount);
        return map;
    }

    /**
     * 异步执行创建应急记录
     * 这个不用及时创建，因为前端11S请求一次
     * @param flowNum
     */
    @Async
    public void saveEmerSys(Long flowNum){
        emergencyService.saveEmerSys(flowNum);
    }

    public void saveEmerSys2(Long blockCallNum){
        emergencyService.saveEmerSys2(blockCallNum);
    }

    @Override
    public List<Map> getSatisfaction(String yearMonth) {
//        //获取所有坐席通话记录
//        List<PltCalllist1000> pltCalllist = this.list(Wrappers.<PltCalllist1000>lambdaQuery()
//                .select(PltCalllist1000::getConnectionid, PltCalllist1000::getEmpcode));
//        if (StringUtil.isNotNull(pltCalllist) && pltCalllist.size() > 0) {
//            //转MAP
//            Map conAndEmp = pltCalllist.stream()
//                    .collect(Collectors.toMap(PltCalllist1000::getConnectionid , PltCalllist1000::getEmpcode));
//            //取流水号属性
//            List<String> connectionList = pltCalllist.stream().map(PltCalllist1000::getConnectionid).collect(Collectors.toList());
//            //取按键值为 1的数据，代表只要 满意 的按键值
//            List<ServiceList1000> serviceList = serviceList1000Service.list(Wrappers.<ServiceList1000>lambdaQuery()
//                    .eq(ServiceList1000::getSatisfactionScore,"1").select(ServiceList1000::getConnectionid));
//            if (StringUtil.isNotNull(serviceList) && serviceList.size()>0){
//
//            }
//        }
        //上面的方法太复杂了，还不如一个SQL就解决事情
        List<Map> mapList = baseMapper.getSatisfactionCount(yearMonth);
        return mapList;
    }

    @Override
    public IPage<Map> getTelephoneSta(HttpServletResponse response,Page page, CallSearch search) {
        IPage<Map> telephoneSta = baseMapper.getTelephoneSta(page, search);
        if (search.getExport() == 1){
            exportCommonCodeService.exportCode(response,"telephoneStaService",telephoneSta.getRecords());
        }
        return telephoneSta;
    }

    @Override
    public IPage<Map> getSatisfactionStatis(HttpServletResponse response,Page page, CallSearch search) {
        IPage<Map> satisfactionStatis = baseMapper.getSatisfactionStatis(page, search);
        if (search.getExport() == 1){
            exportCommonCodeService.exportCode(response,"satisfactionStatisService",satisfactionStatis.getRecords());
        }
        return satisfactionStatis;
    }

    @Override
    public IPage<Map> getSatisfactionStatisInfo(HttpServletResponse response, Page page, CallSearch search) {
        IPage<Map> satisfactionStatisInfo = baseMapper.getSatisfactionStatisInfo(page, search);
        Long export = search.getExport();
        if (export == 1){
            exportCommonCodeService.exportCode(response,"",baseMapper.getSatisfactionStatisInfo(search));
        }
        return satisfactionStatisInfo;
    }

    @Override
    public IPage<Map> getStateStatis(HttpServletResponse response,Page page, CallSearch search) {
        IPage<Map> stateStatis = baseMapper.getStateStatis(page, search);
        if (search.getExport() == 1){
            exportCommonCodeService.exportCode(response,"stateStatisService",stateStatis.getRecords());
        }
        return stateStatis;
    }

    @Override
    public boolean configFlow(FlowNum flowNum) {
        return baseMapper.configFlow(flowNum);
    }

    /**
     * 获取今日话务流量
     *
     * @return map
     */
    @Override
    public Map<String, List<Map>> getTodayFlow() {
        Map<String, List<Map>> map = new HashMap<>();
        map.put("hrl",baseMapper.getInboundVolume());
        map.put("hcl",baseMapper.getOutboundVolume());
        return map;
    }

    /**
     * 获取当月呼入统计
     *
     * @return list
     */
    @Override
    public Map<String, Long> incomingCallCount() {
        return baseMapper.incomingCallCount(STAER_DATE,END_DATE);
    }

    /**
     * 获取当月呼出统计
     *
     * @return list
     */
    @Override
    public Map<String, Long> exhalationCount() {
        return baseMapper.exhalationCount(STAER_DATE,END_DATE);

    }

    /**
     * 获取呼入呼出总数
     *
     * @param userName 人员名称
     * @return map
     */
    @Override
    public Map<String, Long> getCallCount(String userName) {
        return baseMapper.getCallCount(STAER_DATE,END_DATE,userName);
    }

    @Override
    public Map<String, BigDecimal> getUserScoreInfo( Date start,Date end,String userName) {
        return baseMapper.getUserScoreInfo(start,end,userName);
    }

    @Override
    public String listenRecordFile(String connectionId, HttpServletResponse response) {
        //查询是否有录音文件  语音系统原则上是指 接通了电话，并且服务器没有存满的情况下，就会在服务器保存一份录音文件
        PltCalllist1000 pltCalllist1000 = this.getOne(Wrappers.<PltCalllist1000>lambdaQuery()
                .eq(PltCalllist1000::getConnectionid, connectionId)
                .eq(PltCalllist1000::getCallResult, "1")
                .ne(PltCalllist1000::getRecordFile, "")
                .select(PltCalllist1000::getId, PltCalllist1000::getConnectionid, PltCalllist1000::getRecordFile));
        //如果查询出来是null，则没有录音文件
        if (StringUtil.isNull(pltCalllist1000)) {
            return "1";
        }
        //获取配置文件里的IP地址
        String listenRecordFile = recordFile.getListenRecordFile();
        //拼接听取录音地址
        listenRecordFile = listenRecordFile + connectionId;
        //根据录音地址获取录音文件，并响应给前端
        RecordAPIUtil.getFileByURL(listenRecordFile, response);
        return "2";
    }

}
