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

import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.constants.BaseDefineDependencyConstants;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.entity.Message;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.enums.MessageScopeEnum;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.enums.MessageTypeEnum;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.vo.ResponseVO;
import net.northking.cctp.common.cache.EntityNameCache;
import net.northking.cctp.common.cache.EntityNameCatalog;
import net.northking.cctp.executePlan.api.third.feilang.service.FeiLangServiceImpl;
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.dto.planBatch.AtuPlanBatchDetailDto;
import net.northking.cctp.executePlan.feign.ApiCommonCenterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

@Service
public class MessageCenterServiceImpl implements MessageCenterService {

    @Autowired
    EntityNameCache entityNameCache;

    @Autowired
    ApiCommonCenterService commonCenterService;

    @Autowired
    private AtuPlanBatchService atuPlanBatchService;

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

    @Override
    public void sendMessage(AtuPlanInfo atuPlanInfo, AtuPlanBatchDetailDto atuPlanBatch) {
        logger.info("开始处理发送消息中心...");

        String executedByName = entityNameCache.translateById(EntityNameCatalog.MONSTER_USER, atuPlanBatch.getExecutedBy()) == null ?
                "" : entityNameCache.translateById(EntityNameCatalog.MONSTER_USER, atuPlanBatch.getExecutedBy());

        //执行状态  0-等待中，1-执行中，2-已完成，3-已取消
        String tempStatusStr = atuPlanInfo.getStatus();
        Integer tempStatus = Integer.valueOf(tempStatusStr);
        String tempStatusCHN = "";
        //根据batchId查询脚本信息
        if (tempStatus.equals(3)) {
            tempStatusCHN = "已取消";
        } else {
            AtuPlanBatch tempResultAtuPlanBatch = this.atuPlanBatchService.findByPrimaryKey(atuPlanBatch.getId());
            if (tempResultAtuPlanBatch.getScriptNum() != null
                    && tempResultAtuPlanBatch.getSuccessNum() != null
                    && tempResultAtuPlanBatch.getScriptNum().equals(tempResultAtuPlanBatch.getSuccessNum())) {
                tempStatusCHN = "执行成功";
            } else {
                tempStatusCHN = "执行失败";
            }
        }

        try {
            String title = "执行计划执行结束";
            String planName = atuPlanInfo.getPlanName();
            // 避免脚本注入
            if(planName.contains("<")){
                planName.replaceAll("<","&lt;");
            }
            if(planName.contains(">")){
                planName.replaceAll(">","&gt;");
            }

            Message message = new Message();
            message.setScope(MessageScopeEnum.PERSONAL.getValue());
            message.setUserId(Long.valueOf(atuPlanBatch.getExecutedBy()));
            message.setTitle(title);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("uniqueField", "planId");

            String path = "/UiTest/taskPlanExeRecord";
            dataMap.put("path", path);
            dataMap.put("title", "查询执行记录-" + atuPlanInfo.getPlanName());
            dataMap.put("planId", atuPlanInfo.getId());
            dataMap.put("projectId", atuPlanInfo.getProjectId());
            dataMap.put("enabled", true);
            dataMap.put("planName", atuPlanInfo.getPlanName());
            dataMap.put("methodToSetProject", "view");

            message.setContent("执行计划【" + planName + "】 " + tempStatusCHN +
                    "，类型【UI】" +
                    "，系统【" + entityNameCache.translateById(EntityNameCatalog.MONSTER_SYSTEM, atuPlanInfo.getProjectId()) + "】" +
                    "，执行人【" + executedByName +"】，" +
                    "<a class='planLabel' type='2' path='" + path + //type 2 系统级
                    "' data='" + com.hzbank.testteam.autotest.dependencies.baseDefineDependency.utils.JSONUtil.toJSONString(dataMap) +
                    "'  checkFlag='0' checkType='1' checkId='planId'>点击此处</a>查看执行报告。");

            message.setType(MessageTypeEnum.MESSAGE.getValue());
            message.setCreateTime(new Date());
            logger.info("发送消息中心内容为：" + message);
            ResponseVO responseVO = commonCenterService.sendMessage(message);
            if (!responseVO.getCode().equals(BaseDefineDependencyConstants.SYSTEM_RESPONSE_CODE_SUCCESS)) {
                logger.error(responseVO.getCode() + ":" + responseVO.getMessage());
            }
        } catch (Exception e) {
            logger.error("发送执行计划结果消息失败，计划报告id{}，错误原因{}：", atuPlanInfo.getId(), e.toString());
        }
    }
}
