/*
 * Copyright (c) 京北方信息技术股份有限公司 Corporation 2022 . All rights reserved.
 *
 */
package net.northking.cctp.executePlan.api.third.feilang.service;

import com.alibaba.fastjson.JSONObject;
import net.northking.cctp.common.cache.EntityNameCache;
import net.northking.cctp.common.cache.EntityNameCatalog;
import net.northking.cctp.executePlan.api.third.common.ThirdConstant;
import net.northking.cctp.executePlan.api.third.feilang.config.FeilangConfig;
import net.northking.cctp.executePlan.api.third.feilang.dto.FeiLangExecplanInfoResultDto;
import net.northking.cctp.executePlan.api.third.util.FLHttpClientUtils;
import net.northking.cctp.executePlan.constants.MsgConstant;
import net.northking.cctp.executePlan.db.entity.AtuPlanBatch;
import net.northking.cctp.executePlan.db.entity.AtuPlanInfo;
import net.northking.cctp.executePlan.db.service.AtuPlanBatchService;
import net.northking.cctp.executePlan.db.service.AtuPlanInfoService;
import net.northking.cctp.executePlan.dto.planBatch.AtuPlanBatchDetailDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 第三方飞狼系统交互类
 *
 * @author yujinfa
 * @since 1.0
 */

@Service
@ConditionalOnMissingBean(name = "FeiLangServiceImpl")
public class FeiLangServiceImpl implements FeiLangService {
    @Autowired
    private FeilangConfig feilangConfig;
    @Autowired
    private AtuPlanInfoService atuPlanInfoService;
    @Autowired
    private EntityNameCache entityNameCache;
    @Autowired
    private AtuPlanBatchService atuPlanBatchService;

    private final static Logger logger = LoggerFactory.getLogger(FeiLangServiceImpl.class);

    @Override
    public void sendMessage(AtuPlanInfo atuPlanInfo, AtuPlanBatchDetailDto atuPlanBatch) {
        // result dto model
        FeiLangExecplanInfoResultDto resultDto = new FeiLangExecplanInfoResultDto();
        // build result dto
        buildResultDto(resultDto, atuPlanInfo, atuPlanBatch);
        //飞狼发送用户id
        List<String> feiLangUserList = new ArrayList<>();
        if (resultDto.getUserAccounts().contains(",")) {
            feiLangUserList = Arrays.asList(resultDto.getUserAccounts().split(","));
        } else {
            feiLangUserList.add(resultDto.getUserAccounts());
        }
        //接口参数
        Map contentParameterMap = new HashMap<>();
        //业务模板参数
        Map templateParamMap = new HashMap();
        try {
            //执行人
            templateParamMap.put(MsgConstant.EXEC_USER, resultDto.getExecUser());
            //系统名称
            templateParamMap.put(MsgConstant.PROJECT_NAME, entityNameCache.translateById(EntityNameCatalog.MONSTER_SYSTEM, resultDto.getProjectId()));
            //执行状态
            templateParamMap.put(MsgConstant.EXEC_STATUS, resultDto.getExecStatus());
            //计划名称
            templateParamMap.put(MsgConstant.PLAN_NAME, resultDto.getPlanName());
            //执行时间
            templateParamMap.put(MsgConstant.EXEC_TIME, resultDto.getExecTime());
            //获取脚本总数 ，成功数, 失败数，取消数，超时数。
            //脚本总数
            templateParamMap.put(MsgConstant.SUN_COUNT, resultDto.getSunCount());
            //成功数
            templateParamMap.put(MsgConstant.SUCCESS_COUNT, resultDto.getSuccessCount());
            //失败数
            templateParamMap.put(MsgConstant.FAIL_COUNT, resultDto.getFailCount());
            //取消数
            templateParamMap.put(MsgConstant.CANCEL_COUNT, resultDto.getCancelCount());
            //超时数
            templateParamMap.put(MsgConstant.TIMEOUT_COUNT, resultDto.getTimeOutCount());
            //接口入参
            //消息模板id
            contentParameterMap.put(MsgConstant.MSG_TEMP_ID, feilangConfig.getMessageTemplateId());
            //发送平台（0-mc 1-picus 2-ats 3-ui 4-cc）
            contentParameterMap.put(MsgConstant.SOUR_PLAT, ThirdConstant.PLATFORM_SEND_TO_UI);

        } catch (Exception e) {
            logger.error("飞狼发送前数据组装异常:",e);
            throw new RuntimeException("飞狼发送前数据组装异常" + e.getMessage());
        }

        //循环发送飞狼信息以便提供跳转回来飞狼的登录号
        try {
            String result = null;
            for(String feiLangLoginNo:feiLangUserList){
                //跳转链接+飞狼登录号 待前端调试 todo
                //urlfeilangConfig.getBackUrl()+resultDto.getBatchId()+"?enabled=true" ">"+feiLangLoginNo
                templateParamMap.put(MsgConstant.URL, feilangConfig.getBackUrl() + "?loginName="+feiLangLoginNo +"&software=autoTest" +"&planId="+atuPlanInfo.getId() +"&planName="+resultDto.getPlanName());            //获取飞狼订阅用户
                //发送飞狼用户
                contentParameterMap.put(MsgConstant.USER_ACCOUNTS, feiLangLoginNo);
                //模板占位符所需的参数
                contentParameterMap.put(MsgConstant.CONT_PARA, JSONObject.toJSONString(templateParamMap));
                result = FLHttpClientUtils.doPostFormData(feilangConfig.getPathUrl(), null, null, contentParameterMap, feilangConfig.getAk());
                logger.info("推送飞狼"+feiLangLoginNo+"返回信息为" + result);
            }
        }catch (Exception e){
            logger.error("飞狼发送消息异常:",e);
            throw new RuntimeException("飞狼发送消息异常"+e.getMessage());
        }
    }


    private void buildResultDto(FeiLangExecplanInfoResultDto feiLangExecplanInfoResultDto,AtuPlanInfo atuPlanInfo,AtuPlanBatchDetailDto atuPlanBatch) {

        //执行人
        String executedByName = entityNameCache.translateById(EntityNameCatalog.MONSTER_USER, atuPlanBatch.getExecutedBy());
        feiLangExecplanInfoResultDto.setExecUser(executedByName==null?"":executedByName);
        //系统id
        feiLangExecplanInfoResultDto.setProjectId(atuPlanInfo.getProjectId());
        //执行状态  0-等待中，1-执行中，2-已完成，3-已取消
        String tempStatus = atuPlanInfo.getStatus();
        String tempStatusCHN = "";
        if(Objects.nonNull(tempStatus)&&tempStatus.equals("0")){
            tempStatusCHN = "等待中";
        }else if(Objects.nonNull(tempStatus)&&tempStatus.equals("1")){
            tempStatusCHN = "执行中";
        }else if(Objects.nonNull(tempStatus)&&tempStatus.equals("2")){
            tempStatusCHN = "已完成";
        }else if(Objects.nonNull(tempStatus)&&tempStatus.equals("3")){
            tempStatusCHN = "已取消";
        }
        feiLangExecplanInfoResultDto.setExecStatus(tempStatusCHN);
        //计划名称
        feiLangExecplanInfoResultDto.setPlanName(atuPlanInfo.getPlanName());
        //执行时间
        DateFormat dateFormat=new SimpleDateFormat(MsgConstant.DATE_FORMAT_PATTERN);
        feiLangExecplanInfoResultDto.setExecTime(dateFormat.format(atuPlanBatch.getStartTime()));
        //飞狼订阅用户
        feiLangExecplanInfoResultDto.setUserAccounts(atuPlanInfo.getMailAddress());
        //batchId
        feiLangExecplanInfoResultDto.setBatchId(atuPlanBatch.getId());
        //根据batchId查询脚本信息
        AtuPlanBatch tempResultAtuPlanBatch = this.atuPlanBatchService.findByPrimaryKey(atuPlanBatch.getId());
        //脚本总数
        feiLangExecplanInfoResultDto.setSunCount(tempResultAtuPlanBatch.getScriptNum().toString());
        //成功数
        feiLangExecplanInfoResultDto.setSuccessCount(tempResultAtuPlanBatch.getSuccessNum().toString());
        //失败数
        feiLangExecplanInfoResultDto.setFailCount(tempResultAtuPlanBatch.getExecFailNum().toString());
        //取消数
        feiLangExecplanInfoResultDto.setCancelCount(tempResultAtuPlanBatch.getCancelNum().toString());
        //超时数
        feiLangExecplanInfoResultDto.setTimeOutCount(tempResultAtuPlanBatch.getTimeoutNum().toString());
    }


}
