xieb
2023-10-19 1dd5d8f8a616f5cf3caa7828d46989c7d3dcafc4
skjcmanager/skjcmanager-service/skjcmanager-sm/src/main/java/cn/gistack/sm/intelligentCall/service/impl/CallServiceImpl.java
@@ -4,12 +4,14 @@
import cn.gistack.sm.intelligentCall.constant.CallConstant;
import cn.gistack.sm.intelligentCall.constant.ZtConstant;
import cn.gistack.sm.intelligentCall.entity.Scene;
import cn.gistack.sm.intelligentCall.excel.CallExcel;
import cn.gistack.sm.intelligentCall.mapper.CallTaskMapper;
import cn.gistack.sm.intelligentCall.service.CallService;
import cn.gistack.sm.intelligentCall.vo.CallTaskResultVO;
import cn.gistack.sm.intelligentCall.vo.CallTaskStatistic;
import cn.gistack.sm.sjztmd.entity.AttAdBase;
import cn.gistack.sm.sjztmd.service.IAttAdBaseService;
import cn.gistack.sm.sjztmd.service.IAttResManagePersonService;
import cn.gistack.sm.sjztmd.vo.AttAdBaseVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
@@ -20,6 +22,7 @@
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
@@ -53,6 +56,9 @@
   @Autowired
   private BladeRedis bladeRedis;
   @Autowired
   private IAttResManagePersonService attResManagePersonService;
   @Autowired
   private AsyncCallService asyncCallService;
@@ -97,7 +103,7 @@
      LocalDateTime now = LocalDateTime.now();
      String timestamp = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS"));
      String transId = generateTransId(now);
      String taskName = now.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日HH:mm:ss")) + "智能外呼";;
      String taskName = now.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日HH:mm:ss")) + "智能外呼";
      if(null!= map.get("taskName") && !map.get("taskName").equals("")){
         taskName = map.get("taskName").toString();
      }
@@ -111,6 +117,78 @@
         scenesIds = map.get("scenesId").toString();
      }
      JSONArray arr = getCalleeInfo(params);
      HttpHeaders httpHeaders = new HttpHeaders();
      httpHeaders.add("Content-Type", CONTENT_TYPE);
      httpHeaders.add("Accept", ACCEPT_TYPE);
      httpHeaders.add("Accept-Encoding", ACCEPT_ENCODING);
      JSONObject paramJson = new JSONObject();
      paramJson.put("taskName", taskName);
      paramJson.put("scenesId", scenesIds);
      paramJson.put("callingNumbers", numbers);
      paramJson.put("taskScheduleTime", taskScheduleTime);
      paramJson.put("calleeData", arr);
      paramJson.put("empId", empId);
      String token = getToken(appId, timestamp, transId, appSecret, paramJson.toJSONString());
      JSONObject headerJson = new JSONObject();
      headerJson.put("appId", appId);
      headerJson.put("timestamp", timestamp);
      headerJson.put("transId", transId);
      headerJson.put("token", token);
      JSONObject bodyJson = new JSONObject();
      bodyJson.put("head", headerJson);
      bodyJson.put("body", paramJson);
      HttpEntity<String> stringHttpEntity = new HttpEntity<>(bodyJson.toJSONString(), httpHeaders);
      log.info("创建超汛限智能外呼任务请求参数:{}", bodyJson.toJSONString());
      log.info("创建超汛限智能外呼任务呼叫人数:{}", arr.size());
      ResponseEntity<String> response = restTemplate.postForEntity(requestUrl, stringHttpEntity, String.class);
      log.info("创建外呼任务请求结果:{}", response.getBody());
      if (response.getStatusCode() != HttpStatus.OK) {
         log.error("创建智能外呼任务失败:{}", response.getStatusCode());
      }
      JSONObject jsonObject = JSON.parseObject(response.getBody());
      Boolean success = jsonObject.getBoolean("success");
      String taskId = "";
      if (success){
         //通过任务名称查询taskId
         taskId = callTaskMapper.getTaskIdByTaskName(taskName);
      }else {
         // 任务创建失败,发送短信告知
         asyncCallService.createOutCallErrorSendSms(jsonObject.getString("code"),jsonObject.getString("message"));
      }
      List<String> list = new ArrayList<>();
      list.add(response.getBody());
      list.add(taskId);
      list.add(success.toString());
      // 返回
      return list;
   }
   /**
    * 创建告警外呼任务
    * @param map
    * @return
    */
   @Override
   public List<String> createOutCallTaskByAlarm(Map<String, Object> map) {
      List<Map<String, String>> params = (List<Map<String, String>>) map.get("list");
      JSONArray arr = getCalleeInfoAlarm(params,(List<String>) map.get("titles"));
      String requestUrl = url + CREATE_TASK_URL;
      LocalDateTime now = LocalDateTime.now();
      String timestamp = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS"));
      String transId = generateTransId(now);
      String taskName = now.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日HH:mm:ss")) + "智能外呼";
      if(null!= map.get("taskName") && !map.get("taskName").equals("")){
         taskName = map.get("taskName").toString();
      }
      String[] numbers = StringUtils.split(callingNumbers,",");
      String taskScheduleTime = LocalDateTime.now().plusHours(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
      if (null!=map.get("taskScheduleTime") && !map.get("taskScheduleTime").equals("")){
         taskScheduleTime = map.get("taskScheduleTime").toString();
      }
      String scenesIds = scenesId;
      if (null!=map.get("scenesId") && !map.get("scenesId").equals("")){
         scenesIds = map.get("scenesId").toString();
      }
      HttpHeaders httpHeaders = new HttpHeaders();
      httpHeaders.add("Content-Type", CONTENT_TYPE);
      httpHeaders.add("Accept", ACCEPT_TYPE);
@@ -151,6 +229,23 @@
      list.add(success.toString());
      // 返回
      return list;
   }
   /**
    * 外呼动态数据封装
    * @param params
    * @return
    */
   private JSONArray getCalleeInfoAlarm(List<Map<String, String>> params,List<String> titles) {
      JSONArray arr = new JSONArray();
      params.forEach(map -> {
         JSONObject json = new JSONObject();
         for (String title : titles) {
            json.put(title, map.get(title));
         }
         arr.add(json);
      });
      return arr;
   }
   /**
@@ -369,6 +464,7 @@
         if (null!= callTaskStatistic.getIsPage()) {
            return totalList;
         }else {
            page.setTotal(totalList.size());
            return page.setRecords(totalList);
         }
      } catch (InterruptedException e) {
@@ -392,21 +488,21 @@
      Integer totalCalleeNumberCount = 0;
      Integer totalConnectionCount = 0;
      Integer totalThreeNoConnectCount = 0;
      Integer totalTwoNoConnectCount = 0;
//      Integer totalTwoNoConnectCount = 0;
      Integer totalRefuseConnectCount = 0;
      // 遍历
      for (CallTaskStatistic taskStatistic : callTaskStatistics) {
         totalCalleeNumberCount += Integer.parseInt(taskStatistic.getCalleeNumberCount());
         totalConnectionCount += Integer.parseInt(taskStatistic.getConnectionCount());
         totalThreeNoConnectCount += taskStatistic.getThreeNoConnectCount();
         totalTwoNoConnectCount += taskStatistic.getTwoNoConnectCount();
//         totalTwoNoConnectCount += taskStatistic.getTwoNoConnectCount();
         totalRefuseConnectCount += taskStatistic.getRefuseConnectCount();
      }
      // 设置数据
      callTaskStatistic.setCalleeNumberCount(totalCalleeNumberCount.toString());
      callTaskStatistic.setConnectionCount(totalConnectionCount.toString());
      callTaskStatistic.setThreeNoConnectCount(totalThreeNoConnectCount);
      callTaskStatistic.setTwoNoConnectCount(totalTwoNoConnectCount);
//      callTaskStatistic.setTwoNoConnectCount(totalTwoNoConnectCount);
      callTaskStatistic.setRefuseConnectCount(totalRefuseConnectCount);
      callTaskStatistic.setCreateTime(callTaskStatistics.get(0).getCreateTime());
      // 查询当前行政区名称
@@ -540,6 +636,7 @@
               Integer connectCount = Integer.parseInt(taskStatistic.getConnectionCount()) + Integer.parseInt(statistic.getConnectionCount());
               taskStatistic.setCalleeNumberCount(count.toString());
               taskStatistic.setConnectionCount(connectCount.toString());
               taskStatistic.setThreeNoConnectCount(taskStatistic.getThreeNoConnectCount() + statistic.getThreeNoConnectCount());
               taskStatistic.setRefuseConnectCount(taskStatistic.getRefuseConnectCount() + statistic.getRefuseConnectCount());
               // 计算比例
               if (connectCount==0){
@@ -581,7 +678,46 @@
    */
   @Override
   public Object getOutgoingStatisticByArea(CallTaskStatistic callTaskStatistic) {
      return callTaskMapper.getOutgoingStatisticByArea(callTaskStatistic);
      if (null==callTaskStatistic.getCreateTime() || callTaskStatistic.getCreateTime().equals("")){
         long l = System.currentTimeMillis();
         // 设置当前时间的前一天
         callTaskStatistic.setCreateTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date(l - 60*60*24*1000)));
      }
      if (null==callTaskStatistic.getStartTime() || callTaskStatistic.getStartTime().equals("")){
         long l = System.currentTimeMillis();
         String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date(l - 60 * 60 * 24 * 1000));
         // 设置当前时间的前一天
         callTaskStatistic.setStartTime(format);
         callTaskStatistic.setEndTime(format);
      }
      ThreadPoolExecutor executor = myThreadPoolConfig.threadPoolExecutor();
      callTaskStatistic.setIsPage(1);
      // 异步查询当前天日常呼叫(3次)统计数据
      CompletableFuture<List<CallTaskStatistic>> callTaskStatisticCompletableFuture = getListCompletableFuture(null, callTaskStatistic, executor);
      // 查询当前天除去日常呼叫外的统计数据
      CompletableFuture<List<CallTaskStatistic>> notCallConnect = getListCompletableFuture(callTaskStatistic,executor);
      //等待所有任务执行完成
      try {
         CompletableFuture.allOf(callTaskStatisticCompletableFuture,notCallConnect).get();
         // 数据处理
         List<CallTaskStatistic> callTaskStatistics = getCallTaskStatistics(callTaskStatisticCompletableFuture,null,null,null, notCallConnect,callTaskStatistic);
         // 取当前行政区总数据
//         List<CallTaskStatistic> totalList = getTotalCallTaskStatistics(callTaskStatistics,callTaskStatistic);
         List<CallTaskStatistic> totalList = new ArrayList<>();
         // 排序
         callTaskStatistics = getCallTaskStatisticsByOrder(callTaskStatistic, callTaskStatistics);
         // 合并数据
         totalList.addAll(callTaskStatistics);
         // 返回数据
         return totalList;
      } catch (InterruptedException e) {
         e.printStackTrace();
      } catch (ExecutionException e) {
         e.printStackTrace();
      }
      // 返回
      return null;
//      return callTaskMapper.getOutgoingStatisticByArea(callTaskStatistic);
   }
   /**
@@ -636,6 +772,50 @@
   }
   /**
    * 根据条件自动创建外呼任务--一直未接通,一直未呼叫的水库
    * @param params
    * @return
    */
   @Override
   public List<String> createCallTaskByParamByNotCall(Map<String, Object> params) {
      // 常规任务,每天上午11点打150人,下午2点打11点未接人员,下午5点打下午2点未接通人员
      String redisOneKey = bladeRedis.get(CallConstant.call_task_key);
      if (null==redisOneKey){
         List<String> stringList = everydayCallByNotCall(params);
         // 取出数据进行设置 taskId
         bladeRedis.setEx(CallConstant.call_task_key,stringList.get(1)+","+1,6*60*60L);
         // 异步保存日常关联呼叫任务信息
         asyncCallService.saveDailyCallTask(stringList.get(1),1);
         // 响应
         return stringList;
      }else {
         return createEverydayAfter(redisOneKey);
      }
   }
   /**
    * 根据条件自动创建外呼任务--指定区域呼叫
    * @param params
    * @return
    */
   @Override
   public List<String> createOutCallTaskJobHandlerByArea(Map<String, Object> params) {
      // 常规任务,每天上午11点打150人,下午2点打11点未接人员,下午5点打下午2点未接通人员
      String redisOneKey = bladeRedis.get(CallConstant.call_task_key);
      if (null==redisOneKey){
         List<String> stringList = everydayCallByArea(params);
         // 取出数据进行设置 taskId
         bladeRedis.setEx(CallConstant.call_task_key,stringList.get(1)+","+1,6*60*60L);
         // 异步保存日常关联呼叫任务信息
         asyncCallService.saveDailyCallTask(stringList.get(1),1);
         // 响应
         return stringList;
      }else {
         return createEverydayAfter(redisOneKey);
      }
   }
   /**
    * 日常外呼任务未接通的继续拨打
    * @param redisOneKey 取值为上一次外呼的任务id
    * @return
@@ -675,6 +855,66 @@
      }
      // 返回
      return stringList;
   }
   /**
    * 日常外呼任务创建--从未接通和从未呼叫的水库
    * @param params
    * @return
    */
   private List<String> everydayCallByNotCall(Map<String, Object> params) {
      // 查询从未接通和从未呼叫的水库
      List<Scene> totalList = callTaskMapper.getNotCallOrCallNotConnect();
      // 取出随机的150人
      Set<Scene> taskRandomList = new HashSet<>(totalList);
//      Integer personNumber = 220;
//      Random random = new Random();
//      for (int i = 0; i < totalList.size(); i++) {
//         // 获取随机数作为下标索引
//         int num = random.nextInt(totalList.size());
//         // 保存到 hashSet ,保证唯一
//         taskRandomList.add(totalList.get(num));
//         // 数量达到预期设定退出循环
//         if (taskRandomList.size() == personNumber) {
//            break;
//         }
//      }
      //4. 传入调度时间和随机得到的人员信息进行任务的创建并返回
      params.put("list",setForListMap(taskRandomList));
      // 调度时间处理
      params.put("taskScheduleTime",new SimpleDateFormat("yyyy-MM-dd").format(new Date())+ " " +params.get("taskScheduleTime") + ":00");
      // 创建任务并返回结果
      return createTask(params);
   }
   /**
    * 日常外呼任务创建--按区域
    * @param params
    * @return
    */
   private List<String> everydayCallByArea(Map<String, Object> params) {
      // 按区域查询需要呼叫的人员信息
      List<Scene> totalList = callTaskMapper.getCallListByArea();
      // 取出随机的150人
      Set<Scene> taskRandomList = new HashSet<>();
      Integer personNumber = 150;
      Random random = new Random();
      for (int i = 0; i < totalList.size(); i++) {
         // 获取随机数作为下标索引
         int num = random.nextInt(totalList.size());
         // 保存到 hashSet ,保证唯一
         taskRandomList.add(totalList.get(num));
         // 数量达到预期设定退出循环
         if (taskRandomList.size() == personNumber) {
            break;
         }
      }
      //4. 传入调度时间和随机得到的人员信息进行任务的创建并返回
      params.put("list",setForListMap(taskRandomList));
      // 调度时间处理
      params.put("taskScheduleTime",new SimpleDateFormat("yyyy-MM-dd").format(new Date())+ " " +params.get("taskScheduleTime") + ":00");
      // 创建任务并返回结果
      return createTask(params);
   }
   /**
@@ -837,7 +1077,7 @@
   }
   /**
    * 将 jsonArray 取出手机号得到新的集合
    * 将 jsonArray 取出手机号得到新的集合--超汛限场景
    * @param jsonArray
    * @return
    */
@@ -967,17 +1207,61 @@
    */
   @Override
   public Object getCallResultList(IPage<CallTaskStatistic> page, CallTaskStatistic callTaskStatistic) {
      List<String> list = new ArrayList<>();
      if (null!= callTaskStatistic.getAdCode() && !callTaskStatistic.getAdCode().equals("")){
         // 查询所有下级区域code
         list = getAllChildrenAreaByAreaCode(callTaskStatistic.getAdCode());
      }
      if (null!=callTaskStatistic.getIsPage()){
         // 不分页
         return callTaskMapper.getCallResultList(null, list,callTaskStatistic);
         return callTaskMapper.getCallResultList(null,callTaskStatistic);
      }
      List<CallTaskStatistic> callNotConnectResultList = callTaskMapper.getCallResultList(page,list, callTaskStatistic);
      List<CallTaskStatistic> callNotConnectResultList = callTaskMapper.getCallResultList(page, callTaskStatistic);
      // 返回
      return page.setRecords(callNotConnectResultList);
   }
   /**
    * 详情导出临时接口
    * @param callTaskResult
    * @param page
    * @return
    */
   @Override
   public Object getCallResultListTemp(IPage<CallTaskResultVO> page, CallTaskResultVO callTaskResult) {
      List<String> list = new ArrayList<>();
      if (null!=callTaskResult.getIds() && !callTaskResult.getIds().equals("")){
         list = Arrays.asList(callTaskResult.getIds().split(","));
      }
      // 不分页
      return callTaskMapper.getCallResultListTemp(null,callTaskResult,list);
   }
   /**
    * 导入表格发送智能外呼
    * @param list
    * @param time
    * @return
    */
   @Override
   public Object importCall(List<CallExcel> list,String time) {
      // 转换
      List<String> stringList = list.stream().map(CallExcel::getWaterCode).collect(Collectors.toList());
      // 通过水库代码获取水库及巡查责任人信息
      Set<Scene>  personList = attResManagePersonService.getPatrolPersonListByWaterCodeList(stringList);
      Map<String, Object> params = new HashMap<>();
      //传入调度时间和随机得到的人员信息进行任务的创建并返回
      params.put("list",setForListMap(personList));
      // 调度时间处理
      if (null!=time && !time.equals("")){
         params.put("taskScheduleTime",time);
      }else {
         params.put("taskScheduleTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
      }
      // 创建任务并返回结果
      List<String> task = createTask(params);
      if (null!=task.get(1) && !task.get(1).equals("")){
         String successMsg = "外呼任务创建成功";
         // 返回
         return R.data(200,successMsg,null);
      }
      String errorMsg = task.get(0);
      // 返回
      return R.data(400,errorMsg,null);
   }
}