<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--  Copyright (c) 京北方信息技术股份有限公司 Corporation 2022 . All rights reserved. -->
<!--  Mybatis数据库持久层(业务层映射文件):计划执行任务表 -->
<!--  version: 1.0  -->
<!--  author:  maven-cctp-plugin    -->
<!--  date:  2022-12-06 11:00:17  -->
<mapper namespace="net.northking.cctp.executePlan.db.dao.AtuPlanTaskDao">


  <!-- 请在本文件内添加自定义SQL语句 -->

  <resultMap id="DetailMap" type="net.northking.cctp.executePlan.dto.planTask.AtuPlanTaskPageDto">
      <!-- 主键 -->
    <id column="id" jdbcType="VARCHAR" property="id"/>
    <!-- 调度主键 -->
    <result column="batch_id" jdbcType="VARCHAR" property="batchId"/>
    <!-- 环境主键 -->
    <result column="env_id" jdbcType="VARCHAR" property="envId"/>
        <!-- 脚本主键 -->
    <result column="script_id" jdbcType="VARCHAR" property="scriptId"/>
      <!-- 版本主键 -->
    <result column="version_id" jdbcType="INTEGER" property="versionId"/>
      <!-- 版本名称 -->
    <result column="version_name" jdbcType="VARCHAR" property="versionName"/>
        <!-- 脚本名称 -->
    <result column="script_name" jdbcType="VARCHAR" property="scriptName"/>
        <!-- 用例主键 -->
    <result column="case_id" jdbcType="VARCHAR" property="caseId"/>
        <!-- 用例名称 -->
    <result column="case_name" jdbcType="VARCHAR" property="caseName"/>
        <!-- 用例类型;1-接口,2-PC/BS,3-PC/CS,4-安卓,5-ios,6-场景用例 -->
    <result column="case_type" jdbcType="CHAR" property="caseType"/>
        <!-- 引擎主键 -->
    <result column="engine_id" jdbcType="VARCHAR" property="engineId"/>
        <!-- 设备主键 -->
    <result column="device_id" jdbcType="VARCHAR" property="deviceId"/>
        <!-- 应用主键 -->
    <result column="app_id" jdbcType="VARCHAR" property="appId"/>
        <!-- 状态;0-等待中,1-执行中,2-执行成功,3-执行失败,4-断言失败,5-取消,6-超时 -->
    <result column="status" jdbcType="CHAR" property="status"/>
        <!-- 开始时间 -->
    <result column="start_time" jdbcType="BIGINT" property="startTime"/>
        <!-- 结束时间 -->
    <result column="end_time" jdbcType="BIGINT" property="endTime"/>
        <!-- 错误信息 -->
    <result column="error_msg" jdbcType="LONGVARCHAR" property="errorMsg"/>
        <!-- 视频地址 -->
    <result column="video_url" jdbcType="VARCHAR" property="videoUrl"/>
        <!-- 执行结果文件 -->
    <result column="exec_result_file" jdbcType="VARCHAR" property="execResultFile"/>
        <!-- 创建时间 -->
    <result column="created_time" jdbcType="TIMESTAMP" property="createdTime"/>
    </resultMap>

  <resultMap id="TaskExtendMap"  extends="BaseResultMap" type="net.northking.cctp.executePlan.dto.planTask.AtuPlanTaskExtendDto">
    <!-- 计划主键 -->
    <result column="plan_id" jdbcType="VARCHAR" property="planId"/>
    <!-- 脚本主键 -->
    <result column="plan_name" jdbcType="VARCHAR" property="planName"/>
  </resultMap>

    <select id="queryList" resultMap="DetailMap" parameterType="net.northking.cctp.executePlan.dto.planTask.AtuPlanTaskQueryDto">
      select
      id
      ,batch_id
      ,env_id
      ,script_id
      ,version_id
      ,version_name
      ,script_name
      ,case_id
      ,case_no
      ,case_name
      ,case_type
      ,engine_id
      ,device_id
      ,app_id
      ,status
      ,start_time
      ,end_time
      ,error_msg
      ,video_url
      ,exec_result_file
      ,created_time
      from
      <include refid="Table_Name"/>
      <trim prefix="WHERE" prefixOverrides="AND" >
        <if test="batchId != null">
          AND batch_id = #{batchId,jdbcType=VARCHAR}
        </if>
        <if test="keyword != null and keyword != ''">
          AND (script_name like "%"#{keyword,jdbcType=VARCHAR}"%" or case_name like "%"#{keyword,jdbcType=VARCHAR}"%" or case_no like "%"#{keyword,jdbcType=VARCHAR}"%")
        </if>
        <if test="scriptName != null">
          AND LOCATE(#{scriptName,jdbcType=VARCHAR},script_name) > 0
        </if>
        <if test="caseName != null">
          AND LOCATE(#{caseName,jdbcType=VARCHAR},case_name) > 0
        </if>
        <if test="status != null">
          AND status = #{status,jdbcType=CHAR}
        </if>
      </trim>
      order by case_no desc,created_time desc
    </select>

    <select id="pagingQuery" resultMap="DetailMap" parameterType="net.northking.cctp.executePlan.db.entity.AtuPlanTask">
    select
    id
    ,batch_id
    ,env_id
    ,script_id
    ,version_id
    ,version_name
    ,script_name
    ,case_id
    ,case_no
    ,case_name
    ,case_type
    ,engine_id
    ,device_id
    ,app_id
    ,status
    ,start_time
    ,end_time
    ,error_msg
    ,video_url
    ,exec_result_file
    ,created_time
    from
    <include refid="Table_Name"/>
    <trim prefix="WHERE" prefixOverrides="AND" >
      <if test="id != null">
        AND id = #{id,jdbcType=VARCHAR}
      </if>
      <if test="batchId != null">
        AND batch_id = #{batchId,jdbcType=VARCHAR}
      </if>
      <if test="envId != null">
        AND env_id = #{envId,jdbcType=VARCHAR}
      </if>
      <if test="scriptId != null">
        AND script_id = #{scriptId,jdbcType=VARCHAR}
      </if>
      <if test="versionId != null">
        AND version_id = #{versionId,jdbcType=INTEGER}
      </if>
      <if test="versionName != null">
        AND LOCATE(#{versionName,jdbcType=VARCHAR},version_name) > 0
      </if>
      <if test="scriptName != null">
        AND LOCATE(#{scriptName,jdbcType=VARCHAR},script_name) > 0
      </if>
      <if test="caseId != null">
        AND case_id = #{caseId,jdbcType=VARCHAR}
      </if>
      <if test="caseNo != null">
        AND LOCATE(#{caseNo,jdbcType=VARCHAR},case_no) > 0
      </if>
      <if test="caseName != null">
        AND LOCATE(#{caseName,jdbcType=VARCHAR},case_name) > 0
      </if>
      <if test="caseType != null">
        AND case_type = #{caseType,jdbcType=CHAR}
      </if>
      <if test="engineId != null">
        AND engine_id = #{engineId,jdbcType=VARCHAR}
      </if>
      <if test="deviceId != null">
        AND device_id = #{deviceId,jdbcType=VARCHAR}
      </if>
      <if test="appId != null">
        AND app_id = #{appId,jdbcType=VARCHAR}
      </if>
      <if test="status != null">
        AND status = #{status,jdbcType=CHAR}
      </if>
      <if test="startTime != null">
        AND start_time = #{startTime,jdbcType=BIGINT}
      </if>
      <if test="endTime != null">
        AND end_time = #{endTime,jdbcType=BIGINT}
      </if>
      <if test="errorMsg != null">
        AND error_msg = #{errorMsg,jdbcType=LONGVARCHAR}
      </if>
      <if test="videoUrl != null">
        AND video_url = #{videoUrl,jdbcType=VARCHAR}
      </if>
      <if test="execResultFile != null">
        AND exec_result_file = #{execResultFile,jdbcType=VARCHAR}
      </if>
      <if test="createdTime != null">
        AND created_time = #{createdTime,jdbcType=TIMESTAMP}
      </if>
    </trim>
    order by case_no desc,created_time desc
  </select>

  <select id="countUnFinishedTask" resultType="java.lang.Integer">
    select 1 from <include refid="Table_Name"/> where batch_id = #{batchId} and end_time is null limit 1
  </select>

  <select id="queryBatchLastTaskEndTime" resultType="java.lang.Long">
    select max(end_time) from <include refid="Table_Name"/> where batch_id = #{batchId}
  </select>

  <select id="queryUnfinishedTaskByBatchId" resultMap="BaseResultMap">
    select id,batch_id ,script_id ,script_name ,case_id ,case_name ,case_type ,engine_id ,device_id ,app_id ,status
    ,start_time ,end_time ,error_msg ,video_url,exec_result_file ,created_time
    from <include refid="Table_Name"/>
    where status in ('0', '1') and batch_id = #{batchId}
  </select>

  <select id="queryBatchFirstTaskStartTime" resultType="java.lang.Long">
    select min(start_time) from <include refid="Table_Name"/> where batch_id = #{batchId}
  </select>
  
  <select id="selectCaseListByBatchId" resultMap="DetailMap" >
    select
      id
      ,batch_id
      ,env_id
      ,script_id
      ,version_id
      ,version_name
      ,script_name
      ,case_id
      ,case_no
      ,case_name
      ,case_type
      ,engine_id
      ,device_id
      ,app_id
      ,status
      ,start_time
      ,end_time
      ,error_msg
      ,video_url
      ,exec_result_file
      ,created_time
    from atu_plan_task
    where batch_id = #{batchId}
  </select>
    <select id="queryEnvIdByBatchId" resultType="java.lang.String">
      select env_id from <include refid="Table_Name"/> where batch_id = #{batchId} limit 1
    </select>
    <select id="queryAppIdListByBatchId" resultType="java.lang.String">
      select app_id from <include refid="Table_Name"/> where batch_id = #{batchId}
    </select>

  <select id="countByPlanId" resultType="java.lang.Integer">
    select count(1) from <include refid="Table_Name"/> t
    left join atu_plan_batch b on b.id = t.batch_id
    where b.plan_id = #{planId}
  </select>

    <select id="queryMobilePerDataPathByBatchId" resultType="java.lang.String">
      select per_data_path from atu_plan_task
      where case_type in ('3', '4')
      and per_data_path is not null
      and batch_id = #{batchId}
      UNION ALL
      select per_data_path from atu_plan_scene_case_task
      where node_type in ('3', '4')
      and per_data_path is not null
      and task_id in (select id from atu_plan_task where batch_id = #{batchId} and case_type = '5')
    </select>

    <select id="querySendBugTaskInfo"
            resultType="net.northking.cctp.executePlan.dto.planTask.AtuTaskSendBugDto">
      select p.id planId, p.plan_name planName, t.script_id scriptId, t.script_name scriptName, t.created_time createdTime
      from atu_plan_info p
      LEFT JOIN atu_plan_batch b on b.plan_id = p.id
      LEFT JOIN atu_plan_task t on t.batch_id = b.id
      where t.id = #{taskId}
    </select>
    <select id="getFirstExecuteInfo"
            resultType="net.northking.cctp.executePlan.pub.dto.ScriptFirstExecutionDTO">

      SELECT apt2.script_id,
      apt2.start_time firstExecutionTime,
      api.id firstExecutionPlanId,
      api.plan_name firstExecutionPlanName
      FROM (
      SELECT script_id,MIN(start_time) firstExecutionTime FROM atu_plan_task  WHERE script_id in
      <foreach collection="scriptIds" item="id" open="(" separator="," close=")">
        #{id}
      </foreach>
      and start_time is not null
      AND `status` =2 GROUP BY script_id) apt1
      LEFT JOIN atu_plan_task apt2 ON apt1.script_id = apt2.script_id AND apt2.start_time = apt1.firstExecutionTime
      LEFT JOIN atu_plan_batch apb ON apt2.batch_id = apb.id
      LEFT JOIN atu_plan_info api on apb.plan_id = api.id
    </select>
  <select id="getScriptExecuteSuccessNum" resultType="java.lang.Integer">
    SELECT COUNT(1) FROM atu_plan_task apt
    WHERE apt.`status` = 2
    AND apt.script_id = #{scriptId}
    AND DATE_FORMAT(apt.created_time,'%Y-%m') = DATE_FORMAT(#{now},'%Y-%m')
    AND batch_id IN (
    SELECT id FROM atu_plan_batch WHERE plan_id = #{planId})
  </select>
  <select id="getTasksByPlanId" resultType="net.northking.cctp.executePlan.db.entity.AtuPlanTask">
    select
    <include refid="Base_Column_List"/>
    FROM <include refid="Table_Name"/>
    where batch_id in (select id from atu_plan_batch where plan_id = #{planId})
  </select>
  <select id="getTaskIdsByScriptIdsAndPlanId" resultType="java.lang.String">
    select id FROM <include refid="Table_Name"/>
    where batch_id in (select id from atu_plan_batch where plan_id = #{planId})
    and script_id in
    <foreach collection="scriptIds" item="id" open="(" separator="," close=")">
      #{id}
    </foreach>
  </select>
    <select id="queryTasksByBatchIds" resultType="net.northking.cctp.executePlan.db.entity.AtuPlanTask">
      SELECT * FROM atu_plan_task WHERE batch_id IN
      <foreach collection="batchIds" item="batchId" open="(" separator="," close=")">
        #{batchId}
      </foreach>
    </select>
    <select id="queryExecTimeoutTask" resultMap="BaseResultMap">
      select <include refid="Base_Column_List"/> from <include refid="Table_Name"/>
      where status = 1 and case_type != 5 and timestampdiff(second, last_heartbeat_time, NOW()) > #{timeout}
    </select>
  <select id="queryTaskExtendById" resultMap="TaskExtendMap">
    SELECT t.*, b.plan_id from <include refid="Table_Name"/> t
    left join atu_plan_batch b on b.id = t.batch_id
    where t.id = #{id}
  </select>
    <select id="getFirstExecuteInfos"
            resultType="net.northking.cctp.executePlan.pub.dto.ScriptFirstExecutionDTO">
      SELECT
      apt.start_time firstExecutionTime,
      api.id firstExecutionPlanId,
      api.plan_name firstExecutionPlanName
      from atu_plan_task apt
      LEFT JOIN atu_plan_batch apb ON apt.batch_id = apb.id
      LEFT JOIN atu_plan_info api on apb.plan_id = api.id
      WHERE apt.script_id = #{scriptId}
      ORDER BY apt.start_time
    </select>
  <select id="queryWaitTimeoutTask" resultType="net.northking.cctp.executePlan.db.entity.AtuPlanTask">
    SELECT * FROM atu_plan_task
    WHERE
    batch_id IN (
      SELECT id FROM atu_plan_batch WHERE plan_id in (
        SELECT id FROM atu_plan_info WHERE is_deleted = 0
      )
    )
    AND `status` = 0
    AND case_type != 5
    AND timestampdiff(HOUR, created_time, NOW())>= #{waitTimeout}
  </select>


  <delete id="deleteByPlanIdLimit">
    DELETE FROM <include refid="Table_Name"/>
    where batch_id in (select id from atu_plan_batch where plan_id = #{planId})
    LIMIT #{num}
  </delete>

  <select id="queryAllFailIdList" resultType="java.lang.String">
    select id from <include refid="Table_Name"/> where batch_id = #{batchId} and status in ("3", "4", "6")
  </select>

  <resultMap id="taskStatusMap" type="net.northking.cctp.executePlan.dto.planTask.ScriptStatusStatistic">
    <!-- 脚本id -->
    <result column="script_id" jdbcType="VARCHAR" property="scriptId"/>
    <!-- 状态字符串 -->
    <result column="task_status" jdbcType="VARCHAR" property="statusString"/>
    <!-- 任务数量   -->
    <result column="total" jdbcType="INTEGER" property="total" />
  </resultMap>

  <select id="countTaskStatus" parameterType="net.northking.cctp.executePlan.db.entity.AtuPlanTask" resultMap="taskStatusMap">
    SELECT
    script_id,
    group_concat(status) as task_status,
    count(*) as total
    FROM <include refid="Table_Name" />
    WHERE
    batch_id = #{task.batchId,jdbcType=VARCHAR}
    GROUP BY script_id
  </select>

  <update id="batchUpdateTaskStatusToTimeout" >
    UPDATE
    <include refid="Table_Name" />
    SET
    `status` = #{timeoutStatus,jdbcType=VARCHAR}
    WHERE
    batch_id = #{batchId,jdbcType=VARCHAR}
    AND
    (`status` = #{waitStatus, jdbcType=VARCHAR} or `status` = #{timeoutStatus, jdbcType=VARCHAR})
  </update>
</mapper>