package com.lemon.cases;

import com.lemon.constants.Constants;
import com.lemon.pojo.API;
import com.lemon.pojo.Case;
import com.lemon.pojo.TestRecord;
import com.lemon.utils.AuthorizationUtils;
import com.lemon.utils.ExcelUtils;
import com.lemon.utils.SqlUtils;
/*import com.pcloud.universe.wework.client.MessageBuilder;
import com.pcloud.universe.wework.client.WeworkRobotSender;*/
import io.qameta.allure.Description;
import org.apache.http.client.utils.DateUtils;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.Assert;

import java.util.Date;

public class ServerCase extends BaseCase {
    @Test(dataProvider = "data1", description = "1A：A段和B段sql完全匹配")   // DTO数据传输
    @Description("1A：A段和B段sql完全匹配")
    public void testManager1A(API api, Case cas) throws Exception {
        String assertContent = "Pass";
        String body = "";
        Object afterASqlResult = null;
        Object afterBSqlResult = null;
        try {
            System.out.println("testManager1A==================================================接口请求分割线==================================================");
            //0、执行前休眠30秒
            Thread.sleep(1000 * 3);
            //1、参数化替换
            String params = replace(cas.getParams());
            String sql = replace(cas.getCheckSQL());
            String Bsql = replace(cas.getCheckBSQL());
            cas.setParams(params);
            cas.setCheckSQL(sql);
            cas.setCheckBSQL(Bsql);
            //2、数据库前置查询结果（断言必须在接口执行前后都查询）
            Object beforeASqlResult = SqlUtils.querySingle(cas.getCheckSQL());
            Object beforeBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
            //3、调用接口
            body = call(api, cas, false);
            // 3.1 将登录的token存储（仅限于登录接口特有）
            AuthorizationUtils.storeToken(body);
//        System.out.println(AuthorizationUtils.env);
            //4、断言响应结果，Excel中预期响应数据与实际响应数据进行对比
            boolean assertResponseFlag = assertResponse(cas, body);
            //5、添加接口响应回写excel内容
            addWBD(Integer.parseInt(cas.getId()), Constants.ACTURL_WRITER_BACK_CELL_NUM, body);
            //6、数据库后置查询结果
            System.out.println("A-sql: " + cas.getCheckSQL());
             afterASqlResult = SqlUtils.querySingle(cas.getCheckSQL());
             // 查不到 ，等待5秒再查
              if (null == afterASqlResult) {
                Thread.sleep(1000 * 5);
                afterASqlResult = SqlUtils.querySingle(cas.getCheckSQL());

            }
            System.out.println("B-sql: " + cas.getCheckBSQL());
            afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
            // 查不到 ，等待5秒再查
            if (null == afterBSqlResult) {
                Thread.sleep(1000 * 5);
                afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
                // 查不到 ，等待10秒再查
                if (null == afterBSqlResult) {
                    Thread.sleep(1000 * 10);
                    afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
                }
            }

            //7-1、A段数据库断言
            boolean sqlAFlag = assertSql(cas.getaExpectValue(), beforeASqlResult == null ? null : beforeASqlResult.toString(), afterASqlResult == null ? null : afterASqlResult.toString());
            String assertSqlAFlag = (sqlAFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.A_ASSERT_RESULT_CELL_NUM, assertSqlAFlag);
            if(beforeASqlResult != null) System.out.println("数据库A-sql执行前是否有数据：" + beforeASqlResult.toString());
            System.out.println("数据库A-sql断言结果：" + sqlAFlag);
            //7-2、B段数据库断言
            boolean sqlBFlag = assertSql(cas.getbExpectValue(), beforeBSqlResult == null ? null : beforeBSqlResult.toString(), afterBSqlResult == null ? null : afterBSqlResult.toString());
            String assertSqlBFlag = (sqlBFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.B_ASSERT_RESULT_CELL_NUM, assertSqlBFlag);
            if(beforeBSqlResult != null) System.out.println("数据库B-sql执行前是否有数据：" + beforeBSqlResult.toString());
            System.out.println("数据库B-sql断言结果：" + sqlBFlag);
            //8、添加断言回写内容
            assertContent = (assertResponseFlag && sqlAFlag && sqlBFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.ASSERT_RESULT_CELL_NUM, assertContent);
            Assert.assertEquals(assertContent, "Pass");
        } catch (Exception e) {
            log.error("接口测试失败", e);
        }  finally {
            // 同时将测试结果新增到数据库中
            TestRecord  testRecord = new TestRecord();
            testRecord.setCaseId(Integer.valueOf(cas.getId()));
            testRecord.setCaseDesc(cas.getDesc());
            testRecord.setInquiry(cas.getParams());
            testRecord.setExpectContent(cas.getExpectValue());
            testRecord.setInputContent(cas.getParams());
            testRecord.setOutputContent(null != afterASqlResult ? afterASqlResult.toString() : null + " | " + null != afterBSqlResult ? afterBSqlResult.toString() : null);
            testRecord.setState("Pass".equals(assertContent) ? 1 : 0);
            testRecord.setTestVersion(DateUtils.formatDate(new Date(), "yyyyMMdd HH:mm"));
            testRecord.setCreateTime(new Date());
            testRecord.setUpdateTime(new Date());
            testRecord.setIsDelete(0);
            SqlUtils.insertTestRecord(testRecord);
            // 如果失败则发送消息提醒
            if (!"Pass".equals(assertContent)) {
              sendAlarm(cas.getParams());
            }


        }

    }

    @DataProvider(name = "data1")
    public Object[][] data1() {
        Object[][] data = ExcelUtils.getAPIAndCaseByApiId("1");  // 传参apiID
        return data;
    }

    @Test(dataProvider = "data2", description = "2B：B段sql部分匹配")
    @Description("2B：B段sql部分匹配")
    public void testManager2B(API api, Case cas) throws Exception {
        Object afterASqlResult = null;
        Object afterBSqlResult = null;
        String assertContent = "Fail";
        try {
            System.out.println("testManager2B==================================================接口请求分割线==================================================");
            Thread.sleep(1000 * 5);
            String params = replace(cas.getParams());
            String Bsql = replace(cas.getCheckBSQL());
            cas.setParams(params);
            cas.setCheckBSQL(Bsql);
            Object beforeBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
            String body = call(api, cas, false);
            AuthorizationUtils.storeToken(body);
//        System.out.println(AuthorizationUtils.env);
            boolean assertResponseFlag = assertResponse(cas, body);
            addWBD(Integer.parseInt(cas.getId()), Constants.ACTURL_WRITER_BACK_CELL_NUM, body);
            System.out.println("B-sql: " + cas.getCheckBSQL());
            afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
            // 查不到 ，等待5秒再查
            if (null == afterBSqlResult) {
                Thread.sleep(1000 * 5);
                afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
                // 查不到 ，等待10秒再查
                if (null == afterBSqlResult) {
                    Thread.sleep(1000 * 10);
                    afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
                }
            }
            //7-2、B段数据库断言
            boolean sqlBFlag = assertSqlB(beforeBSqlResult == null ? null : beforeBSqlResult.toString(), afterBSqlResult == null ? null : afterBSqlResult.toString());
            String assertSqlBFlag = (sqlBFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.B_ASSERT_RESULT_CELL_NUM, assertSqlBFlag);
            System.out.println("数据库B-sql断言结果：" + sqlBFlag);
            //8、添加断言回写内容
              assertContent = (assertResponseFlag && sqlBFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.ASSERT_RESULT_CELL_NUM, assertContent);
            Assert.assertEquals(assertContent, "Pass");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (NumberFormatException e) {
            throw new RuntimeException(e);
        } finally {
            // 同时将测试结果新增到数据库中
            TestRecord  testRecord = new TestRecord();
            testRecord.setCaseId(Integer.valueOf(cas.getId()));
            testRecord.setCaseDesc(cas.getDesc());
            testRecord.setInquiry(cas.getParams());
            testRecord.setExpectContent(cas.getExpectValue());
            testRecord.setInputContent(cas.getParams());
            testRecord.setOutputContent(null != afterASqlResult ? afterASqlResult.toString() : null + " | " + null != afterBSqlResult ? afterBSqlResult.toString() : null);
            testRecord.setState("Pass".equals(assertContent) ? 1 : 0);
            testRecord.setTestVersion(DateUtils.formatDate(new Date(), "yyyyMMdd HH:mm"));
            testRecord.setCreateTime(new Date());
            testRecord.setUpdateTime(new Date());
            testRecord.setIsDelete(0);
          SqlUtils.insertTestRecord(testRecord);
            // 如果失败则发送消息提醒
            if (!"Pass".equals(assertContent)) {
              sendAlarm(cas.getParams());
            }
        }
    }

    // 使用Excel文件传输接口信息和请求信息
    @DataProvider(name = "data2")
    public Object[][] data2() {
        Object[][] data = ExcelUtils.getAPIAndCaseByApiId("2");  // 传参apiID
        return data;
    }

    @Test(dataProvider = "data3", description = "3C：A段sql完全匹配")   // DTO数据传输
    @Description("3C：A段sql完全匹配")
    public void testManager3C(API api, Case cas) throws Exception {
        Object afterASqlResult = null;
        Object afterBSqlResult = null;
        String assertContent = "Fail";
        try {
            System.out.println("testManager3C==================================================接口请求分割线==================================================");
            Thread.sleep(1000 * 2);
            String params = replace(cas.getParams());
            String sql = replace(cas.getCheckSQL());
            cas.setParams(params);
            cas.setCheckBSQL(sql);
            Object beforeASqlResult = SqlUtils.querySingle(cas.getCheckSQL());
            String body = call(api, cas, false);
            AuthorizationUtils.storeToken(body);
            boolean assertResponseFlag = assertResponse(cas, body);
            addWBD(Integer.parseInt(cas.getId()), Constants.ACTURL_WRITER_BACK_CELL_NUM, body);
            System.out.println("a-sql: " + cas.getCheckSQL());
            afterASqlResult = SqlUtils.querySingle(cas.getCheckSQL());
            // 查不到 ，等待5秒再查
            if (null == afterASqlResult) {
                Thread.sleep(1000 * 5);
                afterASqlResult = SqlUtils.querySingle(cas.getCheckSQL());

            }
            boolean sqlAFlag = assertSql(cas.getaExpectValue(), beforeASqlResult == null ? null : beforeASqlResult.toString(), afterASqlResult == null ? null : afterASqlResult.toString());
            String assertSqlAFlag = (sqlAFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.A_ASSERT_RESULT_CELL_NUM, assertSqlAFlag);
            System.out.println("数据库A-sql断言结果：" + sqlAFlag);
              assertContent = (assertResponseFlag && sqlAFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.ASSERT_RESULT_CELL_NUM, assertContent);
            Assert.assertEquals(assertContent, "Pass");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (NumberFormatException e) {
            throw new RuntimeException(e);
        } finally {
            // 同时将测试结果新增到数据库中
            TestRecord  testRecord = new TestRecord();
            testRecord.setCaseId(Integer.valueOf(cas.getId()));
            testRecord.setCaseDesc(cas.getDesc());
            testRecord.setInquiry(cas.getParams());
            testRecord.setExpectContent(cas.getExpectValue());
            testRecord.setInputContent(cas.getParams());
            testRecord.setOutputContent(null != afterASqlResult ? afterASqlResult.toString() : null + " | " + null != afterBSqlResult ? afterBSqlResult.toString() : null);
            testRecord.setState("Pass".equals(assertContent) ? 1 : 0);
            testRecord.setTestVersion(DateUtils.formatDate(new Date(), "yyyyMMdd HH:mm"));
            testRecord.setCreateTime(new Date());
            testRecord.setUpdateTime(new Date());
            testRecord.setIsDelete(0);
          SqlUtils.insertTestRecord(testRecord);
            // 如果失败则发送消息提醒
            if (!"Pass".equals(assertContent)) {
              sendAlarm(cas.getParams());
            }
        }
    }

    @DataProvider(name = "data3")
    public Object[][] data3() {
        Object[][] data = ExcelUtils.getAPIAndCaseByApiId("3");  // 传参apiID
        return data;
    }


    @Test(dataProvider = "data4", description = "4D：A段sql完全匹配，B段sql部分匹配")   // DTO数据传输
    @Description("4D：A段sql完全匹配，B段sql部分匹配")
    public void testManager4D(API api, Case cas) throws Exception {
        Object afterASqlResult = null;
        Object afterBSqlResult = null;
        String assertContent = "Fail";
        try {
            System.out.println("testManager4D==================================================接口请求分割线==================================================");
            //0、执行前休眠30秒
            //1、参数化替换
            String params = replace(cas.getParams());
            String sql = replace(cas.getCheckSQL());
            String Bsql = replace(cas.getCheckBSQL());
            cas.setParams(params);
            cas.setCheckSQL(sql);
            cas.setCheckBSQL(Bsql);
            //2、数据库前置查询结果（断言必须在接口执行前后都查询）
             Object beforeASqlResult = SqlUtils.querySingle(cas.getCheckSQL());
             Object beforeBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
            //3、调用接口
            String body = call(api, cas, false);
            // 3.1 将登录的token存储（仅限于登录接口特有）
            AuthorizationUtils.storeToken(body);
//        System.out.println(AuthorizationUtils.env);
            //4、断言响应结果，Excel中预期响应数据与实际响应数据进行对比
            boolean assertResponseFlag = assertResponse(cas, body);
            //5、添加接口响应回写excel内容
            addWBD(Integer.parseInt(cas.getId()), Constants.ACTURL_WRITER_BACK_CELL_NUM, body);
            //6、数据库后置查询结果
            System.out.println("A-sql: " + cas.getCheckSQL());
            afterASqlResult = SqlUtils.querySingle(cas.getCheckSQL());
            // 查不到 ，等待5秒再查
            if (null == afterASqlResult) {
                Thread.sleep(1000 * 5);
                afterASqlResult = SqlUtils.querySingle(cas.getCheckSQL());

            }
            System.out.println("B-sql: " + cas.getCheckBSQL());
            afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
            // 查不到 ，等待5秒再查
            if (null == afterBSqlResult) {
                Thread.sleep(1000 * 5);
                afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
                // 查不到 ，等待10秒再查
                if (null == afterBSqlResult) {
                    Thread.sleep(1000 * 10);
                    afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
                }
            }
            //7-1、A段数据库断言
            boolean sqlAFlag = assertSql(cas.getaExpectValue(), beforeASqlResult == null ? null : beforeASqlResult.toString(), afterASqlResult == null ? null : afterASqlResult.toString());
            String assertSqlAFlag = (sqlAFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.A_ASSERT_RESULT_CELL_NUM, assertSqlAFlag);
            System.out.println("数据库A-sql断言结果：" + sqlAFlag);
            //7-2、B段数据库断言
            boolean sqlBFlag = assertSqlB(beforeBSqlResult == null ? null : beforeBSqlResult.toString(), afterBSqlResult == null ? null : afterBSqlResult.toString());
            String assertSqlBFlag = (sqlBFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.B_ASSERT_RESULT_CELL_NUM, assertSqlBFlag);
            System.out.println("数据库B-sql断言结果：" + sqlBFlag);
            //8、添加断言回写内容
              assertContent = (assertResponseFlag && sqlAFlag && sqlBFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.ASSERT_RESULT_CELL_NUM, assertContent);
            Assert.assertEquals(assertContent, "Pass");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (NumberFormatException e) {
            throw new RuntimeException(e);
        } finally {
            // 同时将测试结果新增到数据库中
            TestRecord  testRecord = new TestRecord();
            testRecord.setCaseId(Integer.valueOf(cas.getId()));
            testRecord.setCaseDesc(cas.getDesc());
            testRecord.setInquiry(cas.getParams());
            testRecord.setExpectContent(cas.getExpectValue());
            testRecord.setInputContent(cas.getParams());
            testRecord.setOutputContent(null != afterASqlResult ? afterASqlResult.toString() : null + " | " + null != afterBSqlResult ? afterBSqlResult.toString() : null);
            testRecord.setState("Pass".equals(assertContent) ? 1 : 0);
            testRecord.setTestVersion(DateUtils.formatDate(new Date(), "yyyyMMdd HH:mm"));
            testRecord.setCreateTime(new Date());
            testRecord.setUpdateTime(new Date());
            testRecord.setIsDelete(0);
          SqlUtils.insertTestRecord(testRecord);
            // 如果失败则发送消息提醒
            if (!"Pass".equals(assertContent)) {
              sendAlarm(cas.getParams());
            }
        }
    }

    // 使用Excel文件传输接口信息和请求信息
    @DataProvider(name = "data4")
    public Object[][] data4() {
        Object[][] data = ExcelUtils.getAPIAndCaseByApiId("4");  // 传参apiID
        return data;
    }


    @Test(dataProvider = "data5", description = "5E：A段sql完全匹配，B段sql部分匹配，适用于作品应用")
    @Description("5E：A段sql完全匹配，B段sql部分匹配，适用于作品应用")
    public void testManager5E(API api, Case cas) throws Exception {
        Object afterASqlResult = null;
        Object afterBSqlResult = null;
        String assertContent = "Fail";
        try {
            System.out.println("testManager5E==================================================接口请求分割线==================================================");
            //1、参数化替换
            String params = replace(cas.getParams());
            String sql = replace(cas.getCheckSQL());
            String Bsql = replace(cas.getCheckBSQL());
            cas.setParams(params);
            cas.setCheckSQL(sql);
            cas.setCheckBSQL(Bsql);
            //2、数据库前置查询结果（断言必须在接口执行前后都查询）
            Object beforeASqlResult = SqlUtils.querySingle(cas.getCheckSQL());
            Object beforeBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
            //3、调用接口
            String body = call(api, cas, false);
            // 3.1 将登录的token存储（仅限于登录接口特有）
            AuthorizationUtils.storeToken(body);
//        System.out.println(AuthorizationUtils.env);
            //4、断言响应结果，Excel中预期响应数据与实际响应数据进行对比
            boolean assertResponseFlag = assertResponse(cas, body);
            //5、添加接口响应回写excel内容
            addWBD(Integer.parseInt(cas.getId()), Constants.ACTURL_WRITER_BACK_CELL_NUM, body);
            //6、数据库后置查询结果
            System.out.println("A-sql: " + cas.getCheckSQL());
            afterASqlResult = SqlUtils.querySingle(cas.getCheckSQL());
            // 查不到 ，等待5秒再查
            if (null == afterASqlResult) {
                Thread.sleep(1000 * 5);
                afterASqlResult = SqlUtils.querySingle(cas.getCheckSQL());

            }
            System.out.println("B-sql: " + cas.getCheckBSQL());
            afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
            // 查不到 ，等待5秒再查
            if (null == afterBSqlResult) {
                Thread.sleep(1000 * 5);
                afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
                // 查不到 ，等待10秒再查
                if (null == afterBSqlResult) {
                    Thread.sleep(1000 * 10);
                    afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
                }
            }
            //7-1、A段数据库断言
            boolean sqlAFlag = assertSql(cas.getaExpectValue(), beforeASqlResult == null ? null : beforeASqlResult.toString(), afterASqlResult == null ? null : afterASqlResult.toString());
            String assertSqlAFlag = (sqlAFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.A_ASSERT_RESULT_CELL_NUM, assertSqlAFlag);
            if(beforeASqlResult != null) System.out.println("数据库A-sql执行前是否有数据：" + beforeASqlResult.toString());
            System.out.println("数据库A-sql断言结果：" + sqlAFlag);
            //7-2、B段数据库断言
            boolean sqlBFlag = assertSqlB(beforeBSqlResult == null ? null : beforeBSqlResult.toString(), afterBSqlResult == null ? null : afterBSqlResult.toString());
            String assertSqlBFlag = (sqlBFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.B_ASSERT_RESULT_CELL_NUM, assertSqlBFlag);
            if(beforeBSqlResult != null) System.out.println("数据库B-sql执行前是否有数据：" + beforeBSqlResult.toString());
            System.out.println("数据库B-sql断言结果：" + sqlBFlag);
            //8、添加断言回写内容
              assertContent = (assertResponseFlag && sqlAFlag && sqlBFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.ASSERT_RESULT_CELL_NUM, assertContent);
            Assert.assertEquals(assertContent, "Pass");
        } catch (NumberFormatException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 同时将测试结果新增到数据库中
            TestRecord  testRecord = new TestRecord();
            testRecord.setCaseId(Integer.valueOf(cas.getId()));
            testRecord.setCaseDesc(cas.getDesc());
            testRecord.setInquiry(cas.getParams());
            testRecord.setExpectContent(cas.getExpectValue());
            testRecord.setInputContent(cas.getParams());
            testRecord.setOutputContent(null != afterASqlResult ? afterASqlResult.toString() : null + " | " + null != afterBSqlResult ? afterBSqlResult.toString() : null);
            testRecord.setState("Pass".equals(assertContent) ? 1 : 0);
            testRecord.setTestVersion(DateUtils.formatDate(new Date(), "yyyyMMdd HH:mm"));
            testRecord.setCreateTime(new Date());
            testRecord.setUpdateTime(new Date());
            testRecord.setIsDelete(0);
          SqlUtils.insertTestRecord(testRecord);
            // 如果失败则发送消息提醒
            if (!"Pass".equals(assertContent)) {
              sendAlarm(cas.getParams());
            }
        }
    }

    @DataProvider(name = "data5")
    public Object[][] data5() {
        Object[][] data = ExcelUtils.getAPIAndCaseByApiId("5");
        return data;
    }

    @Test(dataProvider = "data6", description = "6F：B段sql完全匹配")   // DTO数据传输
    @Description("6F：B段sql完全匹配")
    public void testManager6F(API api, Case cas) throws Exception {
        Object afterASqlResult = null;
        Object afterBSqlResult = null;
        String assertContent = "Fail";
        try {
            System.out.println("testManager6F==================================================接口请求分割线==================================================");
            //0、执行前休眠30秒
            Thread.sleep(1000 * 2);
            //1、参数化替换
            String params = replace(cas.getParams());
            String sql = replace(cas.getCheckSQL());
            String Bsql = replace(cas.getCheckBSQL());
            cas.setParams(params);
            cas.setCheckSQL(sql);
            cas.setCheckBSQL(Bsql);
            //2、数据库前置查询结果（断言必须在接口执行前后都查询）
            Object beforeASqlResult = SqlUtils.querySingle(cas.getCheckSQL());
            Object beforeBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
            //3、调用接口
            String body = call(api, cas, false);
            // 3.1 将登录的token存储（仅限于登录接口特有）
            AuthorizationUtils.storeToken(body);
//        System.out.println(AuthorizationUtils.env);
            //4、断言响应结果，Excel中预期响应数据与实际响应数据进行对比
            boolean assertResponseFlag = assertResponse(cas, body);
            //5、添加接口响应回写excel内容
            addWBD(Integer.parseInt(cas.getId()), Constants.ACTURL_WRITER_BACK_CELL_NUM, body);
            //6、数据库后置查询结果
//        System.out.println("A-sql: " + cas.getCheckSQL());
//        Object afterASqlResult = SqlUtils.querySingle(cas.getCheckSQL());
            System.out.println("B-sql: " + cas.getCheckBSQL());
            afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
            // 查不到 ，等待5秒再查
            if (null == afterBSqlResult) {
                Thread.sleep(1000 * 5);
                afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
                // 查不到 ，等待10秒再查
                if (null == afterBSqlResult) {
                    Thread.sleep(1000 * 10);
                    afterBSqlResult = SqlUtils.querySingle(cas.getCheckBSQL());
                }
            }

            //7-2、B段数据库断言
            boolean sqlBFlag = assertSql(cas.getbExpectValue(), beforeBSqlResult == null ? null : beforeBSqlResult.toString(), afterBSqlResult == null ? null : afterBSqlResult.toString());
            String assertSqlBFlag = (sqlBFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.B_ASSERT_RESULT_CELL_NUM, assertSqlBFlag);
            System.out.println("数据库B-sql断言结果：" + sqlBFlag);
            //8、添加断言回写内容
              assertContent = (assertResponseFlag && sqlBFlag) ? "Pass" : "Fail";
            addWBD(Integer.parseInt(cas.getId()), Constants.ASSERT_RESULT_CELL_NUM, assertContent);
            Assert.assertEquals(assertContent, "Pass");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (NumberFormatException e) {
            throw new RuntimeException(e);
        } finally {
            // 同时将测试结果新增到数据库中
            TestRecord  testRecord = new TestRecord();
            testRecord.setCaseId(Integer.valueOf(cas.getId()));
            testRecord.setCaseDesc(cas.getDesc());
            testRecord.setInquiry(cas.getParams());
            testRecord.setExpectContent(cas.getExpectValue());
            testRecord.setInputContent(cas.getParams());
            testRecord.setOutputContent(null != afterASqlResult ? afterASqlResult.toString() : null + " | " + null != afterBSqlResult ? afterBSqlResult.toString() : null);
            testRecord.setState("Pass".equals(assertContent) ? 1 : 0);
            testRecord.setTestVersion(DateUtils.formatDate(new Date(), "yyyyMMdd HH:mm"));
            testRecord.setCreateTime(new Date());
            testRecord.setUpdateTime(new Date());
            testRecord.setIsDelete(0);
          SqlUtils.insertTestRecord(testRecord);
            // 如果失败则发送消息提醒
            if (!"Pass".equals(assertContent)) {
              sendAlarm(cas.getParams());
            }
        }
    }

    @DataProvider(name = "data6")
    public Object[][] data6() {
        Object[][] data = ExcelUtils.getAPIAndCaseByApiId("6");  // 传参apiID
        return data;
    }

    public void sendAlarm(String inquiry) {
     /*
        Long chatUserId =     null;
         String msgRemoteId = null;
        String origin =null;
        Long digitalPersonId =null;
        Long bookId = null;
      

        StringBuilder sb = new StringBuilder();
        sb.append("案例书自动化测试结果异常告警").append("\n");
        sb.append("<@").append("599").append(">\n");
        sb.append("> 环境：").append(MessageBuilder.comment("prod")).append("\t").append(MessageBuilder.comment(null)).append("\n");
        sb.append("> 用户输入：").append(MessageBuilder.comment(inquiry)).append("\n");
         sb.append("> 消息到达的节点描述：").append("案例书_长江作业本").append("\n");
        sb.append("> Time：").append(MessageBuilder.comment(MessageBuilder.format(new Date()))).append("\n");

        String alarmKey = "7782a9ad-817a-4b7e-9745-b2b173ddc04a";
        if (StringUtils.isNotBlank(alarmKey)) {
            log.info("发送告警消息：" +sb.toString());
//            WeworkRobotSender.asyncSend(alarmKey, MessageBuilder.buildMarkdown(sb.toString()));
        }*/
    }
}
