package com.test.test.service.impl;

import com.fatboyindustrial.gsonjavatime.LocalDateTimeConverter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.test.common.utils.*;
import com.test.common.utils.sql.TinyIntTypeAdapter;
import com.test.test.domain.*;
import com.test.test.domain.qo.*;
import com.test.test.mapper.*;
import com.test.test.service.ITestCaseService;
import com.test.test.service.ITestCaseStepService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用例Service业务层处理
 *
 * @author liangdl
 * @date 2025-02-18
 */
@Slf4j
@Service
public class TestCaseServiceImpl implements ITestCaseService
{
    @Resource
    private TestCaseMapper testCaseMapper;
    @Resource
    private TestCaseResultMapper testCaseResultMapper;
    @Resource
    private TestDatasourceMapper testDatasourceMapper;
    @Resource
    private TestCaseLogMapper testCaseLogMapper;
    @Resource
    private TestPlanMapper testPlanMapper;
    @Resource
    private TestPlanCaseMapper testPlanCaseMapper;

    @Autowired
    private ITestCaseStepService testCaseStepService;

    /**
     * 查询用例
     *
     * @param id 用例主键
     * @return 用例
     */
    @Override
    public TestCase selectTestCaseById(Long id)
    {
        return testCaseMapper.selectTestCaseById(id);
    }

    /**
     * 查询用例列表
     *
     * @param qo 用例
     * @return 用例
     */
    @Override
    public List<TestCase> selectTestCaseList(TestCaseListQO qo) {
        return testCaseMapper.selectTestCaseList(qo);
    }

    /**
     * 查询测试计划可关联的用例列表
     */
    @Override
    public List<TestCase> selectValidTestPlanCaseList(TestCaseListQO qo) {
        return testCaseMapper.selectValidTestPlanCaseList(qo);
    }

    @Override
    public List<TestCase> selectTestCaseList(TestCase testCase) {
        return testCaseMapper.selectTestCaseListNoGroupId(testCase);
    }

    /**
     * 新增用例
     *
     * @param testCase 用例
     * @return 结果
     */
    @Override
    public int insertTestCase(TestCase testCase)
    {
        testCase.setCreateTime(DateUtils.getNowDate());
        return testCaseMapper.insertTestCase(testCase);
    }

    /**
     * 修改用例
     *
     * @param testCase 用例
     * @return 结果
     */
    @Override
    public int updateTestCase(TestCase testCase)
    {
        testCase.setUpdateTime(DateUtils.getNowDate());
        return testCaseMapper.updateTestCase(testCase);
    }

    /**
     * 批量删除用例
     *
     * @param ids 需要删除的用例主键
     * @return 结果
     */
    @Override
    public int deleteTestCaseByIds(Long[] ids)
    {
        return testCaseMapper.deleteTestCaseByIds(ids);
    }

    /**
     * 删除用例信息
     *
     * @param id 用例主键
     * @return 结果
     */
    @Override
    public int deleteTestCaseById(Long id)
    {
        return testCaseMapper.deleteTestCaseById(id);
    }

    /**
     * 执行用例计划
     *
     * @param id             用例主键id
     * @param jmeterHomePath jmeter安装路径
     * @param caseSid 用例执行uuid
     * @return 是否成功
     */
    @Override
    public String executeTestCaseById(Long id, String jmeterHomePath, String caseSid) {
        TestCase testCase = this.selectTestCaseById(id);
        if (testCase == null || "2".equals(testCase.getDelFlag())) {
            log.error("用例计划已被删除，不能执行！");
            return null;
        }
        Map<String, String> contextResultMap = new HashMap<>();
        testCase.setContextResultMap(contextResultMap);
        TestCaseLog testCaseLog = new TestCaseLog();
        testCaseLog.setCaseId(id);
        testCaseLog.setOperTime(DateUtils.getNowDate());
        testCaseLog.setOperType("执行");
        testCaseLog.setCaseSid(caseSid);
        testCase.setCaseSid(caseSid);
        List<TestCaseStep> testCaseStepList = testCaseStepService.selectTestCaseStepListByCaseId(id);
        for (TestCaseStep testCaseStep : testCaseStepList) {
            if (testCaseStep.getType() == 1L) {
                // http接口处理
                boolean httpTestResult = doHttpRequestTest(testCase, testCaseStep, jmeterHomePath);
                if (!httpTestResult) {
                    testCaseLog.setOperDetail("失败");
                    testCaseLogMapper.insertTestCaseLog(testCaseLog);
                    log.error("用例步骤:{}执行失败！", testCaseStep.getName());
                    return null;
                }
            } else if (testCaseStep.getType() == 2L) {
                // 数据库接口处理
                boolean dateSourceTestResult = doDateSourceRequestTest(testCase, testCaseStep);
                if (!dateSourceTestResult) {
                    testCaseLog.setOperDetail("失败");
                    testCaseLogMapper.insertTestCaseLog(testCaseLog);
                    log.error("数据源用例步骤:{}执行失败！", testCaseStep.getName());
                    return null;
                }
            } else if (testCaseStep.getType() == 3L) {
                // 循环节点处理
                boolean pollTestResult = doPollRequestTest(testCase, testCaseStep, jmeterHomePath);
                if (!pollTestResult) {
                    testCaseLog.setOperDetail("失败");
                    testCaseLogMapper.insertTestCaseLog(testCaseLog);
                    log.error("循环用例步骤:{}执行失败！", testCaseStep.getName());
                    return null;
                }
            } else if (testCaseStep.getType() == 4L) {
                // 轮询节点处理
                boolean loopTestResult = doLoopRequestTest(testCase, testCaseStep, jmeterHomePath);
                if (!loopTestResult) {
                    testCaseLog.setOperDetail("失败");
                    testCaseLogMapper.insertTestCaseLog(testCaseLog);
                    log.error("轮询用例步骤:{}执行失败！", testCaseStep.getName());
                    return null;
                }
            } else {
                log.error("错误的用例步骤类型！");
            }
        }
        testCaseLog.setOperDetail("成功");
        testCaseLogMapper.insertTestCaseLog(testCaseLog);
        return caseSid;
    }

    /**
     * 执行测试计划关联的用例
     *
     * @param testPlanCase   测试计划关联用例查询条件
     * @param jmeterHomePath jmeter安装路径
     * @param caseSid 用例执行uuid
     * @return 是否成功
     */
    @Override
    public void executeTestCaseByPlanCase(TestPlanCase testPlanCase, String jmeterHomePath, String caseSid) {
        List<TestPlanCase> testPlanCaseList = testPlanCaseMapper.selectTestPlanCaseList(testPlanCase);
        if (CollectionUtils.isEmpty(testPlanCaseList)) {
            log.error("计划关联测试用例为空，不能执行！");
            return ;
        }
        TestPlan testPlan = testPlanMapper.selectTestPlanById(testPlanCase.getPlanId());
        testPlan.setStatus("1");
        testPlan.setUpdateTime(DateUtils.getNowDate());
        testPlanMapper.updateTestPlan(testPlan);
        for (TestPlanCase input : testPlanCaseList) {
            boolean isSuccess = true;
            input.setExecuteTime(DateUtils.getNowDate());
            input.setExecuteBy(SecurityUtils.getUsername());
            TestCase testCase = this.selectTestCaseById(input.getCaseId());
            Long id = input.getCaseId();
            Map<String, String> contextResultMap = new HashMap<>();
            testCase.setContextResultMap(contextResultMap);
            TestCaseLog testCaseLog = new TestCaseLog();
            testCaseLog.setCaseId(id);
            testCaseLog.setOperTime(DateUtils.getNowDate());
            testCaseLog.setOperType("执行");
            testCaseLog.setCaseSid(caseSid);
            testCase.setCaseSid(caseSid);
            List<TestCaseStep> testCaseStepList = testCaseStepService.selectTestCaseStepListByCaseId(id);
            for (TestCaseStep testCaseStep : testCaseStepList) {
                if (testCaseStep.getType() == 1L) {
                    // http接口处理
                    boolean httpTestResult = doHttpRequestTest(testCase, testCaseStep, jmeterHomePath);
                    if (!httpTestResult) {
                        testCaseLog.setOperDetail("失败");
                        testCaseLogMapper.insertTestCaseLog(testCaseLog);
                        log.error("用例步骤:{}执行失败！", testCaseStep.getName());
                        isSuccess = false;
                        break;
                    }
                } else if (testCaseStep.getType() == 2L) {
                    // 数据库接口处理
                    boolean dateSourceTestResult = doDateSourceRequestTest(testCase, testCaseStep);
                    if (!dateSourceTestResult) {
                        testCaseLog.setOperDetail("失败");
                        testCaseLogMapper.insertTestCaseLog(testCaseLog);
                        log.error("数据源用例步骤:{}执行失败！", testCaseStep.getName());
                        isSuccess = false;
                        break;
                    }
                } else if (testCaseStep.getType() == 3L) {
                    // 循环节点处理
                    boolean pollTestResult = doPollRequestTest(testCase, testCaseStep, jmeterHomePath);
                    if (!pollTestResult) {
                        testCaseLog.setOperDetail("失败");
                        testCaseLogMapper.insertTestCaseLog(testCaseLog);
                        log.error("循环用例步骤:{}执行失败！", testCaseStep.getName());
                        isSuccess = false;
                        break;
                    }
                } else if (testCaseStep.getType() == 4L) {
                    // 轮询节点处理
                    boolean loopTestResult = doLoopRequestTest(testCase, testCaseStep, jmeterHomePath);
                    if (!loopTestResult) {
                        testCaseLog.setOperDetail("失败");
                        testCaseLogMapper.insertTestCaseLog(testCaseLog);
                        log.error("轮询用例步骤:{}执行失败！", testCaseStep.getName());
                        isSuccess = false;
                        break;
                    }
                } else {
                    log.error("错误的用例步骤类型！");
                    isSuccess = false;
                    break;
                }
            }
            if (isSuccess) {
                testCaseLog.setOperDetail("成功");
                input.setExecuteResult("成功");
            } else {
                testCaseLog.setOperDetail("失败");
                input.setExecuteResult("失败");
            }
            testCaseLogMapper.insertTestCaseLog(testCaseLog);
            testPlanCaseMapper.updateTestPlanCase(input);
        }
        testPlan.setUpdateTime(DateUtils.getNowDate());
        testPlan.setStatus("2");
        testPlanMapper.updateTestPlan(testPlan);
    }

    /**
     * 处理http接口测试
     * @param testCase
     * @param testCaseStep
     * @param jmeterHomePath
     * @return 成功或失败
     */
    private boolean doHttpRequestTest(TestCase testCase, TestCaseStep testCaseStep, String jmeterHomePath) {
        TestCaseResult testCaseResult = new TestCaseResult();
        try {
            String assignment = testCaseStep.getAssignment(); // 参数提取
            String assertion = testCaseStep.getAssertion(); // 校验规则
            testCaseResult.setExecuteTime(DateUtils.getNowDate());
            Map<String, String> resultMap = testCaseStepService.executeJmeterTestCaseStepById(testCaseStep.getId(), jmeterHomePath);
            testCaseResult.setCaseId(testCase.getId());
            testCaseResult.setStepId(testCaseStep.getId());
            testCaseResult.setCaseSid(testCase.getCaseSid());
            if (resultMap != null) {
                testCaseResult.setRequestHeader(resultMap.get("requestHeader"));
                testCaseResult.setRequestBody(resultMap.get("requestBody"));
                testCaseResult.setResponseHeader(resultMap.get("responseHeader"));
                testCaseResult.setResponseBody(resultMap.get("responseBody"));
                // 处理参数提取
                Map<String, String> assignmentResultMap = new HashMap<>();
                assignmentResultMap.putAll(testCase.getContextResultMap());
                String assignmentResult = this.dealTestCaseStepAssignment(resultMap, assignmentResultMap, assignment);
                testCaseResult.setAssignment(assignmentResult);
                // 根据提取结果处理校验规则
                String assertionResult = this.dealTestCaseStepAssertion(assignmentResultMap, assertion);
                testCase.getContextResultMap().putAll(assignmentResultMap);
                testCaseResult.setAssertion(assertionResult);
                Long useTime = null;
                if (resultMap.get("costMiliseconds") != null) {
                    useTime = Long.valueOf(resultMap.get("costMiliseconds"));
                }
                testCaseResult.setUseTime(useTime);
                if ("fail".equals(assignmentResultMap.get("assertionResult"))) {
                    testCaseResult.setStatus("失败");
                    testCaseResultMapper.insertTestCaseResult(testCaseResult);
                    return false;
                } else {
                    testCaseResult.setStatus("成功");
                    testCaseResultMapper.insertTestCaseResult(testCaseResult);
                }
            } else {
                testCaseResult.setAssignment(assignment);
                testCaseResult.setAssertion(assertion);
                testCaseResult.setUseTime(0L);
                testCaseResult.setStatus("失败");
                testCaseResultMapper.insertTestCaseResult(testCaseResult);
                return false;
            }
        } catch (Exception e) {
            log.error("HTTP请求测试发生异常: ", e);
            testCaseResult.setUseTime(0L);
            testCaseResult.setStatus("失败");
            testCaseResultMapper.insertTestCaseResult(testCaseResult);
            return false;
        }
        return true;
    }

    /**
     * 处理数据源接口测试
     * @param testCase
     * @param testCaseStep
     * @return 成功或失败
     */
    private boolean doDateSourceRequestTest(TestCase testCase, TestCaseStep testCaseStep) {
        TestCaseResult testCaseResult = new TestCaseResult();
        try {
            String assignment = testCaseStep.getAssignment(); // 参数提取
            String assertion = testCaseStep.getAssertion(); // 校验规则
            testCaseResult.setExecuteTime(DateUtils.getNowDate());
            testCaseResult.setCaseId(testCase.getId());
            testCaseResult.setStepId(testCaseStep.getId());
            testCaseResult.setCaseSid(testCase.getCaseSid());
            Long startTime = System.currentTimeMillis();
            TestDatasource testDatasource = testDatasourceMapper.selectTestDatasourceById(testCaseStep.getDatasourceId());
            Long useTime = System.currentTimeMillis() - startTime;
            testCaseResult.setUseTime(useTime);
            if (testDatasource == null) {
                log.error("根据数据源id：{}无法查询到数据源信息", testCaseStep.getDatasourceId());
                return false;
            }
            String url = "jdbc:mysql://"+ testDatasource.getHost() +":"+ testDatasource.getPort() +"/" + testDatasource.getDbName();
            List<String> columnNameList = new ArrayList<>();
            // sql查询特有字段结果存储
            Map<String, String> sqlSpecialResultMap = new HashMap<>();
            // 获取所有sql查询集合对象
            List<Map<String, Object>> resultMapList = MySQLExecutor.executeQuery(testCaseStep.getSqlCommand(), url, testDatasource.getUsername(), testDatasource.getPassword(), columnNameList, sqlSpecialResultMap);
            if (!CollectionUtils.isEmpty(resultMapList)) {
                SqlResult sqlResult = new SqlResult();
                sqlResult.setColumnNameList(columnNameList);
                sqlResult.setResultMapList(resultMapList);
                Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Byte.class, new TinyIntTypeAdapter())
                        .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeConverter())
                        .create();
                testCaseResult.setSqlResult(gson.toJson(sqlResult));
                // 处理参数提取
                Map<String, String> assignmentResultMap = new HashMap<>();
                assignmentResultMap.putAll(testCase.getContextResultMap());
                String assignmentResult = this.dealDataSourceTestCaseStepAssignment(resultMapList, assignmentResultMap, sqlSpecialResultMap, assignment);
                testCaseResult.setAssignment(assignmentResult);
                // 根据提取结果处理校验规则
                String assertionResult = this.dealTestCaseStepAssertion(assignmentResultMap, assertion);
                testCase.getContextResultMap().putAll(assignmentResultMap);
                testCaseResult.setAssertion(assertionResult);
                if ("fail".equals(assignmentResultMap.get("assertionResult"))) {
                    testCaseResult.setStatus("失败");
                    testCaseResultMapper.insertTestCaseResult(testCaseResult);
                    return false;
                } else {
                    testCaseResult.setStatus("成功");
                    testCaseResultMapper.insertTestCaseResult(testCaseResult);
                }
            } else {
                testCaseResult.setAssignment(assignment);
                testCaseResult.setAssertion(assertion);
                testCaseResult.setStatus("失败");
                testCaseResultMapper.insertTestCaseResult(testCaseResult);
                return false;
            }
        } catch (Exception e) {
            log.error("数据源请求测试发生异常: ", e);
            testCaseResult.setSqlResult("数据源请求测试发生异常: " + e.getMessage());
            testCaseResult.setStatus("失败");
            testCaseResultMapper.insertTestCaseResult(testCaseResult);
            return false;
        }
        return true;
    }

    /**
     * 处理循环节点接口测试
     * @param testCase
     * @param testCaseStep
     * @param jmeterHomePath
     * @return 是否成功
     */
    private boolean doPollRequestTest(TestCase testCase, TestCaseStep testCaseStep, String jmeterHomePath) {
        try {
            // 先查出所有子节点测试步骤
            long pollCountCount = testCaseStep.getCount();
            Integer async = testCaseStep.getAsync();
            TestCaseResult testCaseResult = new TestCaseResult();
            testCaseResult.setExecuteTime(DateUtils.getNowDate());
            testCaseResult.setCaseId(testCase.getId());
            testCaseResult.setStepId(testCaseStep.getId());
            testCaseResult.setCaseSid(testCase.getCaseSid());
            Long parentId = testCaseStep.getId();
            TestCaseStep testCaseStepInput = new TestCaseStep();
            testCaseStepInput.setCaseId(testCase.getId());
            testCaseStepInput.setParentId(parentId);
            testCaseStepInput.setDelFlag("0");
            List<TestCaseStep> testCaseStepChildList = testCaseStepService.selectTestCaseStepList(testCaseStepInput);
            long realPollCount = 1; // 实际循环次数
            boolean pollResult = true;
            long startTime = System.currentTimeMillis();
            for (int i = 0; i < pollCountCount; i++) {
                for (TestCaseStep testCaseStepChild : testCaseStepChildList) {
                    if (testCaseStepChild.getType() == 1L) {
                        // http接口处理
                        boolean httpTestResult = doHttpRequestTest(testCase, testCaseStepChild, jmeterHomePath);
                        if (!httpTestResult) {
                            log.error("子用例步骤:{}执行失败！", testCaseStepChild.getName());
                            pollResult = false;
                            break;
                        }
                    } else if (testCaseStepChild.getType() == 2L) {
                        // 数据库接口处理
                        boolean dateSourceTestResult = doDateSourceRequestTest(testCase, testCaseStepChild);
                        if (!dateSourceTestResult) {
                            log.error("子数据源用例步骤:{}执行失败！", testCaseStepChild.getName());
                            pollResult = false;
                            break;
                        }
                    }
                }
                if (!pollResult) {
                    break;
                }
                realPollCount++;
            }
            testCaseResult.setUseTime(System.currentTimeMillis() - startTime);
            if (pollResult) {
                testCaseResult.setStatus("成功");
                testCaseResult.setPollingCount(realPollCount);
                testCaseResultMapper.insertTestCaseResult(testCaseResult);
                return true;
            } else {
                testCaseResult.setStatus("失败");
                testCaseResult.setPollingCount(realPollCount);
                testCaseResultMapper.insertTestCaseResult(testCaseResult);
                return false;
            }
        } catch (Exception e) {
            log.error("循环节点测试发生异常: ", e);
            return false;
        }
    }

    /**
     * 处理轮询节点接口测试
     * @param testCase
     * @param testCaseStep
     * @param jmeterHomePath
     * @return 是否成功
     */
    private boolean doLoopRequestTest(TestCase testCase, TestCaseStep testCaseStep, String jmeterHomePath) {
        try {
            // 先查出所有子节点测试步骤
//            String breakError = testCaseStep.getBreakError();
            long interval =  testCaseStep.getInterval() == null ? 0 : testCaseStep.getInterval();;
            long loopCountCount = testCaseStep.getCount();
            TestCaseResult testCaseResult = new TestCaseResult();
            testCaseResult.setExecuteTime(DateUtils.getNowDate());
            testCaseResult.setCaseId(testCase.getId());
            testCaseResult.setStepId(testCaseStep.getId());
            testCaseResult.setCaseSid(testCase.getCaseSid());
            Long parentId = testCaseStep.getId();
            TestCaseStep testCaseStepInput = new TestCaseStep();
            testCaseStepInput.setCaseId(testCase.getId());
            testCaseStepInput.setParentId(parentId);
            testCaseStepInput.setDelFlag("0");
            List<TestCaseStep> testCaseStepChildList = testCaseStepService.selectTestCaseStepList(testCaseStepInput);
            long realLoopCount = 1; // 实际轮询次数
            boolean loopResult = false;
            long startTime = System.currentTimeMillis();
            int maxSize = testCaseStepChildList.size();
            for (int i = 0; i < loopCountCount; i++) {
                if (i > 0) {
                    try {
                        Thread.sleep(interval);
                    } catch (InterruptedException e) {
                        log.error("线程睡眠被中断: ", e);
                    }
                }
                int index = 0;
                for (TestCaseStep testCaseStepChild : testCaseStepChildList) {
                    if (testCaseStepChild.getType() == 1L) {
                        // http接口处理
                        boolean httpTestResult = doHttpRequestTest(testCase, testCaseStepChild, jmeterHomePath);
                        if (!httpTestResult) {
                            log.error("子用例步骤:{}执行失败！", testCaseStepChild.getName());
                            break;
                        }
                    } else if (testCaseStepChild.getType() == 2L) {
                        // 数据库接口处理
                        boolean dateSourceTestResult = doDateSourceRequestTest(testCase, testCaseStepChild);
                        if (!dateSourceTestResult) {
                            log.error("子数据源用例步骤:{}执行失败！", testCaseStepChild.getName());
                            break;
                        }
                    }
                    index ++;
                }
                realLoopCount ++;
                if (maxSize == index) {
                    loopResult = true;
                    break;
                }
            }
            testCaseResult.setUseTime(System.currentTimeMillis() - startTime);
            if (loopResult) {
                testCaseResult.setStatus("成功");
                testCaseResult.setLoopCount(realLoopCount);
                testCaseResultMapper.insertTestCaseResult(testCaseResult);
                return true;
            } else {
                testCaseResult.setStatus("失败");
                testCaseResult.setLoopCount(realLoopCount);
                testCaseResultMapper.insertTestCaseResult(testCaseResult);
                return false;
            }
        } catch (Exception e) {
            log.error("轮询节点测试发生异常: ", e);
            return false;
        }
    }

    /**
     * 处理响应字段提取
     * @param resultMap
     * @param assignmentResultMap
     * @param assignment
     * @return 处理后的提取结果
     */
    private String dealTestCaseStepAssignment(Map<String, String> resultMap, Map<String, String> assignmentResultMap, String assignment) {
        String responseHeader = resultMap.get("responseHeader");
        String responseBody = resultMap.get("responseBody");
        String responseCode = resultMap.get("responseCode");
        if (!StringUtils.isEmpty(assignment) && !"[]".equals(assignment)) {
            Map<String, String> responseHeaderMap = JMeterUtil.parseHeaders(responseHeader);
            Gson gson = new Gson();
            Type ruleListType = new TypeToken<List<ExtractionRule>>() {}.getType();
            // 将 JSON 字符串解析为 List<ExtractionRule>
            List<ExtractionRule> rules = gson.fromJson(assignment, ruleListType);
            List<ExtractionRuleResult> ruleResultList = new ArrayList<>();
            for (ExtractionRule rule : rules) {
                ExtractionRuleResult ruleResult = new ExtractionRuleResult();
                BeanUtils.copyProperties(rule, ruleResult);
                String type = rule.getType();
                String content = rule.getContent();
                String path = rule.getPath();
                if ("${RESPONSE_BODY}".equals(content)) {
                    if (type.startsWith("JSON")) {
                        if (!path.startsWith("$.")) {
                            path = "$." + path;
                        }
                        String value = JMeterUtil.extractFieldValue(responseBody, path);
                        ruleResult.setValue(value);
                    }
                } else if ("${RESPONSE_HEADER}".equals(content)) {
                    String value = responseHeaderMap.get(path);
                    ruleResult.setValue(value);
                } else if ("${RESPONSE_CODE}".equals(content)) {
                    ruleResult.setValue(responseCode);
                } else if (content.startsWith("${")) {
                    ruleResult.setValue(assignmentResultMap.get(StringUtils.substringBetween(content, "${", "}")));
                }
                assignmentResultMap.put(rule.getName(), ruleResult.getValue());
                ruleResultList.add(ruleResult);
            }
            return gson.toJson(ruleResultList);
        } else {
            return assignment;
        }
    }

    /**
     * 处理数据源响应字段提取
     * @param resultMapList
     * @param assignmentResultMap
     * @param sqlSpecialResultMap 存储sql特有的响应信息字段结果值
     * @param assignment
     * @return 处理后的提取结果
     */
    private String dealDataSourceTestCaseStepAssignment(List<Map<String, Object>> resultMapList, Map<String, String> assignmentResultMap, Map<String, String> sqlSpecialResultMap, String assignment) {
        if (!StringUtils.isEmpty(assignment) && !"[]".equals(assignment)) {
            Gson gson = new Gson();
            String responseBody = gson.toJson(resultMapList);
            Type ruleListType = new TypeToken<List<ExtractionRule>>() {}.getType();
            // 将 JSON 字符串解析为 List<ExtractionRule>
            List<ExtractionRule> rules = gson.fromJson(assignment, ruleListType);
            List<ExtractionRuleResult> ruleResultList = new ArrayList<>();
            for (ExtractionRule rule : rules) {
                ExtractionRuleResult ruleResult = new ExtractionRuleResult();
                BeanUtils.copyProperties(rule, ruleResult);
                String type = rule.getType();
                String content = rule.getContent();
                String path = rule.getPath();
                if ("${RESULT_DATA}".equals(content)) {
                    if (type.startsWith("JSON")) {
                        if (!path.startsWith("$.")) {
                            path = "$." + path;
                        }
                        String value = JMeterUtil.extractFieldValue(responseBody, path);
                        ruleResult.setValue(value);
                    }
                } else if ("${RESULT_DATA_LENGTH}".equals(content)) {
                    if (!CollectionUtils.isEmpty(resultMapList)) {
                        String value = String.valueOf(resultMapList.size());
                        ruleResult.setValue(value);
                    } else {
                        ruleResult.setValue("0");
                    }
                } else if ("${AFFECT_ROWS}".equals(content) || "${CHANGE_ROWS}".equals(content)) {
                    String affectRows = sqlSpecialResultMap.get("${AFFECT_ROWS}");
                    if (affectRows == null) {
                        ruleResult.setValue("0");
                    } else {
                        ruleResult.setValue(affectRows);
                    }
                } else if (content.startsWith("${")) {
                    ruleResult.setValue(assignmentResultMap.get(StringUtils.substringBetween(content, "${", "}")));
                }
                assignmentResultMap.put(rule.getName(), ruleResult.getValue());
                ruleResultList.add(ruleResult);
            }
            return gson.toJson(ruleResultList);
        } else {
            return assignment;
        }
    }

    /**
     * 校验测试用例步骤是否通过
     * @param assignmentResultMap
     * @param assertion
     * @return
     */
    private String dealTestCaseStepAssertion(Map<String, String> assignmentResultMap, String assertion) {
        if (!StringUtils.isEmpty(assertion) && !"[]".equals(assertion)) {
            Gson gson = new Gson();
            Type ruleListType = new TypeToken<List<AssertRule>>() {}.getType();
            // 将 JSON 字符串解析为 List<AssertRule>
            List<AssertRule> rules = gson.fromJson(assertion, ruleListType);
            List<AssertRuleResult> ruleResultList = new ArrayList<>();
            for (AssertRule rule : rules) {
                AssertRuleResult ruleResult = new AssertRuleResult();
                BeanUtils.copyProperties(rule, ruleResult);
                String source = rule.getSource();
                String target = rule.getTarget();
                String fn = rule.getFn();
                if (source.equals("${RESPONSE_BODY}")) {
                    source = "responseBody";
                } else if (source.equals("${RESPONSE_CODE}")) {
                    source = "responseCode";
                } else if (source.equals("${RESPONSE_HEADER}")) {
                    source = "responseHeader";
                } else if (source.startsWith("$")){
                    source = StringUtils.substringBetween(source, "${", "}");
                }
                String value = assignmentResultMap.get(source);
                ruleResult.setValue(value);
                if ("等于".equals(fn)) {
                    if (target.equals(value)) {
                        ruleResult.setResult("通过");
                    } else {
                        ruleResult.setResult("未通过");
                    }
                } else if ("大于".equals(fn)) {
                    int result = value.compareTo(target);
                    if (result > 0) {
                        ruleResult.setResult("通过");
                    } else {
                        ruleResult.setResult("未通过");
                    }
                } else if ("小于".equals(fn)) {
                    int result = value.compareTo(target);
                    if (result < 0) {
                        ruleResult.setResult("通过");
                    } else {
                        ruleResult.setResult("未通过");
                    }
                } else if ("不等于".equals(fn)) {
                    if (!target.equals(value)) {
                        ruleResult.setResult("通过");
                    } else {
                        ruleResult.setResult("未通过");
                    }
                } else {
                    ruleResult.setResult("未通过");
                }
                if ("未通过".equals(ruleResult.getResult())) {
                    assignmentResultMap.put("assertionResult", "fail");
                }
                ruleResultList.add(ruleResult);
            }
            return gson.toJson(ruleResultList);
        } else {
            return assertion;
        }

    }
}
