package org.matrix.testNg.web.report;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.matrix.actuators.checkpoint.CheckPointResult;
import org.matrix.actuators.checkpoint.CheckPointResultDetail;
import org.matrix.exception.GlobalException;
import org.matrix.testNg.web.entity.DataBean;
import org.matrix.testNg.web.entity.DataBeans;
import org.matrix.testNg.web.entity.DataMove;
import org.matrix.testNg.web.vo.DataBeansMoveVo;
import org.matrix.util.ReporterUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author MRY
 */
public class ReporterDataJob {
    /**
     * 模板公共部分
     *
     * @return 补全了的所有报告信息
     */
    public DataBean testDataBean() {
        return ReporterUtils.jobMap.get("job").getDataBean();
    }

    /**
     * 动作部分
     */
    public List<DataMove> testDataBeanMove() {
        List<DataMove> dataMoveList = new ArrayList<>();
        List<DataBeansMoveVo> dataBeansMoveVos = ReporterUtils.jobMap.get("job").getDataBeansMove();
        for (DataBeansMoveVo dataBeansMoveVo : dataBeansMoveVos) {
            DataMove dataMove = dataBeansMoveVo.getDataMove();
            dataMoveList.add(dataMove);
        }
        return dataMoveList;
    }

    /**
     * 模板的细节部分
     *
     * @return 报告中细节部分的信息
     */
    public List<DataBeans> testDataBeans() {
        List<DataBeans> list = new ArrayList<>();
        List<DataBeansMoveVo> dataBeansMoveVos = ReporterUtils.jobMap.get("job").getDataBeansMove();
        ObjectMapper objectMapper = new ObjectMapper();
        for (DataBeansMoveVo dataBeansMoveVo : dataBeansMoveVos) {
            List<DataBeans> dataBeansList = dataBeansMoveVo.getDataBeansList();
            for (DataBeans dataBeans : dataBeansList) {
                try {
                    CheckPointResult resultMessage = dataBeans.getResultMessage();
                    List<CheckPointResultDetail> checkPointResultDetails = resultMessage.getCheckPointResultDetails();
                    for (CheckPointResultDetail checkPointResultDetail : checkPointResultDetails) {
                        if (checkPointResultDetail.getMatchExpression() == null){
                            checkPointResultDetail.setMatchExpression("");
                        }
                        if (checkPointResultDetail.getParseExpression() == null){
                            checkPointResultDetail.setParseExpression("");
                        }
                    }
                    dataBeans.setStr(objectMapper.writeValueAsString(resultMessage));
                    list.add(dataBeans);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                    throw new GlobalException("报告中结果信息,序列化失败");
                }
            }
        }
        return list;
    }
}
