<?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">
<mapper namespace="com.bonus.material.repair.mapper.RepairMapper">
    <insert id="addRecord">
        insert into repair_apply_record (task_id,ma_id,type_id,repair_num,scrap_num,repair_type,create_by,create_time,repair_content,company_id,scrap_id,scrap_reason,scrap_type,supplier_id,part_num,part_price,part_type,part_name,repairer,file_ids,remark,part_id)
        values (#{taskId},#{maId},#{typeId},#{repairNum},#{scrapNum},#{repairType},#{createBy},now(),#{repairContent},#{companyId}, #{scrapId},#{scrapReason},#{scrapType},#{supplierId},#{partNum},#{partPrice},#{partType},#{partName},#{repairer},#{fileIds},#{remark},#{partId});
    </insert>

    <insert id="addPart">
        insert into repair_part_details (task_id,ma_id,type_id,part_id,part_num,part_cost,part_type,create_by,create_time,company_id,repair_content)
        values (#{taskId},#{maId},#{typeId},#{partId},#{partNum},#{partCost},#{partType},#{createBy},now(),#{companyId},#{repairContent});
    </insert>

    <insert id="addTask" useGeneratedKeys="true" keyProperty="taskId">
        insert into tm_task (pre_task_id,task_status,task_type,code,create_by,create_time,company_id,month_order)
        values (#{preTaskId},#{taskStatus},#{taskType},#{repairCode},#{createBy},now(),#{companyId},#{monthOrder});
    </insert>

    <insert id="createAgreementTask">
        insert into tm_task_agreement (task_id,agreement_id,create_by,create_time,company_id)
        values (#{taskId},#{agreementId},#{createBy},now(),#{companyId});
    </insert>

    <insert id="addAuditDetails">
        insert into repair_audit_details (task_id,repair_id,ma_id,type_id,repair_num,repaired_num,scrap_num,status,
                                          create_by,create_time,company_id, back_id)
        values (#{taskId},#{id},#{maId},#{typeId},#{repairNum},#{repairedNum},#{scrapNum},'0',#{createBy},now(),
                #{companyId}, #{backId});
    </insert>

    <insert id="addRepairCost">
        insert into repair_cost (task_id,repair_id,type_id,ma_id,repair_num,costs,part_type,status,repair_type)
        values (#{bean.taskId},#{bean.id},#{bean.typeId},#{bean.maId},#{bean.repairNum},#{costs},#{partType},'0',#{bean.repairType});
    </insert>

    <insert id="insertRepaired">
        insert into repair_apply_details
        (
        <if test="newTaskId != null">
            task_id,
        </if>
        <if test="maId != null">
            ma_id,
        </if>
        <if test="typeId != null">
            type_id,
        </if>
        <if test="repairNum != null">
            repair_num,
        </if>
        <if test="repairedNum != null">
            repaired_num,
        </if>
        <if test="scrapNum != null">
            scrap_num,
        </if>
        <if test="status != null">
            status,
        </if>
        <if test="createBy != null and createBy != ''">
            create_by,
        </if>
        <if test="remark != null and remark != ''">
            remark,
        </if>
        <if test="backId != null">
            back_id,
        </if>
        <if test="level != null and level != ''">
            level,
        </if>
        <if test="parentId != null">
            parent_id,
        </if>
        <if test="isDs != null">
            is_ds,
        </if>
        create_time
        )
        values (
        <if test="newTaskId != null">
            #{newTaskId},
        </if>
        <if test="maId != null">
            #{maId},
        </if>
        <if test="typeId != null">
            #{typeId},
        </if>
        <if test="repairNum != null">
            #{repairNum},
        </if>
        <if test="repairedNum != null">
            #{repairedNum},
        </if>
        <if test="scrapNum != null">
            #{scrapNum},
        </if>
        <if test="status != null">
            #{status},
        </if>
        <if test="createBy != null and createBy != ''">
            #{createBy},
        </if>
        <if test="remark != null and remark != ''">
            #{remark},
        </if>
        <if test="backId != null">
            #{backId},
        </if>
        <if test="level != null and level != ''">
            #{level},
        </if>
        <if test="parentId != null">
            #{parentId},
        </if>
        <if test="isDs != null">
            #{isDs},
        </if>
        NOW()
        )
    </insert>

    <update id="updateRepairedNum">
        update repair_apply_details
        set  repaired_num = #{repairNum},
            repairer = #{repairer},
            update_by = #{userId},
            update_time = now()
        where id = #{id}
    </update>

    <update id="updateRepairNum">
        update repair_apply_details
        set  repair_num = #{repairNum},
             update_time = now()
        where id = #{id}
    </update>

    <update id="updateThisRepairedAndScrapNum">
        update
            repair_apply_details
        set
            this_repaired_num = ifnull(this_repaired_num,0) + #{thisRepairedNum},
            this_scrap_num = ifnull(this_scrap_num,0) + #{thisScrapNum},
            update_time = now()
        where
            id = #{id}
    </update>

    <update id="updateRepairedNumAndStatus">
        update repair_apply_details
        set repaired_num = ifnull(repaired_num,0) + #{repairNum},
             status = #{status},repairer = #{repairer},update_by = #{userId},update_time = now()
        where
            id = #{id}
            and (ifnull(repaired_num,0) + #{repairNum}) &lt;= repair_num
    </update>

    <update id="updateRepairedNumTwo">
        update repair_apply_details
        set repaired_num = ifnull(repaired_num,0) + #{repairNum},update_by = #{userId},update_time = now()
        where id = #{id}
        and (ifnull(repaired_num,0) + #{repairNum}) &lt;= repair_num
    </update>

    <update id="updateRepairedNumTwoAndStatus">
        update repair_apply_details
        set repaired_num = #{repairNum},status = #{status},update_by = #{userId},update_time = now()
        where id = #{id}
        and (ifnull(repaired_num,0) + #{repairNum}) &lt;= repair_num
    </update>

    <update id="updateScrapNum">
        update repair_apply_details
        set  scrap_num = #{scrapNum},
            update_by = #{userId},
            update_time = now()
        where id = #{id}
    </update>

    <update id="updateScrapNumAndStatus">
        update repair_apply_details
        set  scrap_num = #{scrapNum},
             status = #{status},
             update_by = #{userId},
             update_time = now()
        where id = #{id}
    </update>

    <update id="batchQualified">
        update repair_apply_details
        set status = '1',
        repaired_num = repair_num - ifnull(scrap_num, 0),
        update_by = #{userName},
        update_time = now(),
        repairer = #{userName}
        where id in
            <foreach item="id" collection="ids" open="(" separator="," close=")">
                #{id}
            </foreach>
    </update>

    <update id="updateTaskStatus">
        update tm_task
        set task_status = #{taskStatus},
        update_by = #{userId},
        update_time = now()
        where task_id in
        <foreach item="task" collection="taskList" open="(" separator="," close=")">
            #{task.taskId}
        </foreach>
    </update>

    <update id="updateSingleTaskStatus">
        update tm_task
        set task_status = #{taskStatus},
            update_by = #{userId},
            update_time = now()
        where task_id = #{task.taskId}
    </update>

    <delete id="deleteByTaskId">
        delete from repair_apply_details where task_id = #{taskId}
    </delete>

    <delete id="deleteRepairById">
        delete from repair_apply_details where id = #{id}
    </delete>

    <select id="getRepairTaskInfoByTaskId" resultType="com.bonus.material.repair.domain.RepairTask">
        SELECT
            rd.task_id as taskId,
            rd.repairer,rd.repaired_num,rd.scrap_num,
            tt.CODE AS repairCode,
            tt.create_time AS createTime,
            tt.task_status AS repairStatusCode,
            tt.company_id AS companyId,
            tt.remark,
            bui.unit_name AS backUnit,
            bpi.pro_name AS backPro,
            su.nick_name AS createName,
            bai.CODE AS backCode,
            GROUP_CONCAT(DISTINCT mt2.type_name) as type
        FROM
            repair_apply_details rd
        LEFT JOIN ma_type mt on rd.type_id = mt.type_id
        LEFT JOIN ma_type mt2 on mt.parent_id = mt2.type_id
        LEFT JOIN tm_task tt on rd.task_id = tt.task_id
        LEFT JOIN back_apply_info bai ON rd.back_id = bai.id
        LEFT JOIN tm_task_agreement tta ON rd.task_id = tta.task_id
        LEFT JOIN bm_agreement_info bai2 ON tta.agreement_id = bai2.agreement_id
        LEFT JOIN bm_unit bui ON bai2.unit_id = bui.unit_id
        LEFT JOIN bm_project bpi ON bai2.project_id = bpi.pro_id and bpi.del_flag = '0'
        left join sys_user su on rd.create_by = su.user_id
        where rd.task_id = #{taskId}
        GROUP BY rd.task_id
    </select>

    <select id="getRepairTaskList" resultType="com.bonus.material.repair.domain.RepairTask">
        SELECT
            rd.task_id as taskId,
            su2.nick_name as repairer,
            tt.CODE AS repairCode,
            tt.create_time AS createTime,
            tt.task_status AS repairStatusCode,
            tt.company_id AS companyId,
            tt.remark,tt.create_by as createName,
            bui.unit_name AS backUnit,
            bpi.pro_name AS backPro,
            bai.CODE AS backCode,
            bai.back_person as backPerson,
            GROUP_CONCAT(DISTINCT mt2.type_name) as type,
            rd.level as level,
            GROUP_CONCAT(DISTINCT mt4.type_id) as firstId,
            rd.status as dataStatus,
            rad2.num,
            rd.back_id as backId
        FROM
            repair_apply_details rd
        LEFT JOIN ma_type mt on rd.type_id = mt.type_id
        LEFT JOIN ma_type mt2 on mt.parent_id = mt2.type_id
        LEFT JOIN tm_task tt on rd.task_id = tt.task_id
        LEFT JOIN back_apply_info bai ON rd.back_id = bai.id
        LEFT JOIN tm_task_agreement tta ON rd.task_id = tta.task_id
        LEFT JOIN bm_agreement_info bai2 ON tta.agreement_id = bai2.agreement_id
        LEFT JOIN bm_unit bui ON bai2.unit_id = bui.unit_id
        LEFT JOIN bm_project bpi ON bai2.project_id = bpi.pro_id and bpi.del_flag = '0'
        left join sys_user su on rd.create_by = su.user_id
        left join sys_user su2 on su2.user_id = rd.repairer
        left join ma_type mt3 ON mt2.parent_id = mt3.type_id and mt3.del_flag = '0'
        left join ma_type mt4 ON mt3.parent_id = mt4.type_id and mt4.del_flag = '0'
        LEFT JOIN (
        SELECT
        task_id,
        SUM(`status`) as num
        FROM
        repair_apply_details
        WHERE
        is_ds='1'
        GROUP BY task_id
        ) rad2 on rad2.task_id=rd.task_id
        <if test="userId != null">
            JOIN ma_type_repair mtr ON mtr.type_id = rd.type_id AND mtr.user_id = #{userId}
        </if>
        <where>
            <if test="backUnit != null and backUnit != ''">
                AND bui.unit_id = #{backUnit}
            </if>
            <if test="backPro != null and backPro != ''">
                AND bpi.pro_id = #{backPro}
            </if>
            <if test="type != null and type != ''">
                AND mt2.type_id = #{type}
            </if>
            <if test="backCode != null and backCode != ''">
                AND locate(#{backCode}, bai.CODE) > 0
            </if>
            <if test="repairStatus != null and repairStatus != ''">
                AND tt.task_status = #{repairStatus}
            </if>
            <if test="startTime != null and startTime != '' and endTime != null and endTime != ''">
                AND tt.create_time BETWEEN CONCAT(#{startTime}, ' 00:00:00') AND CONCAT(#{endTime}, ' 23:59:59')
            </if>
            <if test="appTaskStatus != null and appTaskStatus == 0">
                and (tt.task_status = 3 or tt.task_status = 4)
            </if>
            <if test="appTaskStatus != null and appTaskStatus == 1">
                and (tt.task_status = 1 or tt.task_status = 2)
            </if>
            and is_ds=0
        </where>
        GROUP BY rd.task_id,bui.unit_name,bpi.pro_name,bai.code,su.nick_name
        order by tt.create_time desc
    </select>

    <select id="exportRepairTaskList" resultType="com.bonus.material.repair.domain.RepairTask">
        SELECT
            rd.task_id,
            tt.CODE AS repairCode,
            bui.unit_name AS backUnit,
            bpi.pro_name AS backPro,
            su.nick_name AS createName,
            tt.create_time AS createTime,
            bai.CODE AS backCode,
            tt.task_status AS repairStatusCode,
            tt.company_id AS companyId,
            mt2.type_name AS type,
            mt.type_name AS typeName,
            mm.ma_code AS CODE,
            rd.repair_num AS repairNum,
            rd.repaired_num AS repairedNum,
            rd.scrap_num AS scrapNum,
            case rd.status when '0' then '未完成' when '1' then '已完成' else '' end as status,
            su2.nick_name as repairer,
            rd.update_time as updateTime
        FROM
            repair_apply_details rd
                LEFT JOIN ma_type mt ON rd.type_id = mt.type_id
                LEFT JOIN ma_type mt2 ON mt.parent_id = mt2.type_id
                LEFT JOIN tm_task tt ON rd.task_id = tt.task_id
                LEFT JOIN back_apply_info bai ON rd.back_id = bai.id
                LEFT JOIN tm_task_agreement tta ON rd.task_id = tta.task_id
                LEFT JOIN bm_agreement_info bai2 ON tta.agreement_id = bai2.agreement_id
                LEFT JOIN bm_unit bui ON bai2.unit_id = bui.unit_id
                LEFT JOIN bm_project bpi ON bai2.project_id = bpi.pro_id and bpi.del_flag = '0'
                LEFT JOIN sys_user su ON rd.create_by = su.user_id
                left join sys_user su2 on rd.repairer = su2.user_id
                LEFT JOIN ma_machine mm ON mm.ma_id = rd.ma_id
        where 1=1
        <if test="keyWord != null and keyWord != ''">
            AND (locate(#{keyWord}, su.nick_name) > 0
            or locate(#{keyWord}, tt.CODE) > 0)
        </if>
        <if test="backUnit != null and backUnit != ''">
            AND bui.unit_id = #{backUnit}
        </if>
        <if test="backPro != null and backPro != ''">
            AND bpi.pro_id = #{backPro}
        </if>
        <if test="type != null and type != ''">
            AND mt2.type_id = #{type}
        </if>
        <if test="backCode != null and backCode != ''">
            AND locate(#{backCode}, bai.CODE) > 0
        </if>
        <if test="repairStatus != null and repairStatus != ''">
            AND tt.task_status = #{repairStatus}
        </if>
        <if test="startTime != null and startTime != '' and endTime != null and endTime != ''">
            AND tt.create_time BETWEEN CONCAT(#{startTime}, ' 00:00:00') AND CONCAT(#{endTime}, ' 23:59:59')
        </if>
        <if test="dataCondition != null and dataCondition.size()>0">
            AND rd.task_id in
            <foreach collection="dataCondition" item="taskId" index="index" open="(" separator="," close=")">
                #{taskId}
            </foreach>
        </if>
        ORDER BY
            tt.create_time DESC
    </select>

    <select id="getRepairDeviceList" resultType="com.bonus.material.repair.domain.vo.RepairDeviceVO">
    <![CDATA[
        select
            rad.id as id,
            rad.task_id as taskId,
            rad.ma_id as maId,
            mt2.type_name as typeName,
            mt2.type_id as typeNameId,
            mt.type_name as type,
            mt.unit_name as unitName,
            mt.manage_type as manageType,
            mm.ma_code as code,
            ifnull(rad.repair_num, 0) as repairNum,
            sum(ifnull(rad.repaired_num,0) + ifnull(rad.this_repaired_num,0)) as repairedNum,
            sum(ifnull(rad.scrap_num,0) + ifnull(rad.this_scrap_num,0)) as scrapNum,
            rad.status as status,
            rad.status as completeNum,
            su.nick_name as repairer,
            rad.update_time as updateTime,
            rad.type_id as typeId,
            rad.back_id as backId,
            rad.level as level,
            rad.parent_id as parentId,
            rad.create_time,
            bai.CODE AS backCode,
            mt4.type_id AS firstId,
            ( SELECT COUNT(*) FROM repair_cost rc WHERE rc.repair_id = rad.id ) AS totalCostRecords,
             ( SELECT COALESCE(SUM(rc.costs), 0) FROM repair_cost rc WHERE rc.repair_id = rad.id ) AS totalCost,
            rad2.`status` as dataStatus,
            mt.unit_value AS unitValue
        from
            repair_apply_details rad
            left join ma_type mt on rad.type_id = mt.type_id
            left join ma_machine mm on mm.ma_id = rad.ma_id
            left join sys_user su on rad.repairer = su.user_id
            left join ma_type mt2 on mt.parent_id = mt2.type_id
            LEFT JOIN back_apply_info bai ON rad.back_id = bai.id
            left join ma_type mt3 ON mt2.parent_id = mt3.type_id and mt3.del_flag = '0'
            left join ma_type mt4 ON mt3.parent_id = mt4.type_id and mt4.del_flag = '0'
            left join repair_apply_details rad2 on rad2.task_id=rad.task_id and rad2.ma_id <=>  rad.ma_id and rad2.type_id=rad.type_id and rad2.is_ds='1'
              ]]>
           <if test="userId != null">
            JOIN ma_type_repair mtr
            ON mtr.type_id = rad.type_id
            AND mtr.user_id = #{userId}
            </if>
        where
            rad.task_id = #{taskId}
        and rad.is_ds=0
        <if test="companyId != null and companyId != ''">
            and rad.company_id = #{companyId}
        </if>
        <if test="keyword != null and keyword != ''">
            AND (locate(#{keyword}, mm.ma_code) > 0
            or locate(#{keyword}, su.nick_name) > 0
            or locate(#{keyword}, mt2.type_name) > 0
            or locate(#{keyword}, mt.type_name) > 0)
        </if>
        <if test="type != null and type != ''">
            AND mt.type_id = #{type}
        </if>
        <if test="typeName != null and typeName != ''">
            AND mt2.type_id = #{typeName}
        </if>
        GROUP BY rad.id
        order by rad.create_time desc
    </select>

<!--    <select id="getRepairMaTypeList" resultType="com.bonus.material.repair.domain.vo.RepairDeviceListVo">-->
<!--        select-->
<!--            rad.id as id,-->
<!--            rad.task_id as taskId,-->
<!--            rad.ma_id as maId,-->
<!--            mt2.type_name as typeName,-->
<!--            mt2.type_id as typeNameId,-->
<!--            mt.type_name as type,-->
<!--            mt.unit_name as unitName,-->
<!--            mt.manage_type as manageType,-->
<!--            mm.ma_code as code,-->
<!--            rad.repair_num as repairNum,-->
<!--            rad.repaired_num as repairedNum,-->
<!--            rad.scrap_num as scrapNum,-->
<!--            rad.status as status,-->
<!--            su.nick_name as repairer,-->
<!--            rad.update_time as updateTime,-->
<!--            rad.type_id as typeId,-->
<!--            rad.create_time,-->
<!--            count(rc.id) AS totalCostRecords,-->
<!--            sum(rc.costs) AS totalCost-->
<!--        from repair_apply_details rad-->
<!--        left join ma_type mt on rad.type_id = mt.type_id-->
<!--        left join ma_machine mm on mm.ma_id = rad.ma_id-->
<!--        left join sys_user su on rad.repairer = su.user_id-->
<!--        left join ma_type mt2 on mt.parent_id = mt2.type_id-->
<!--        left join repair_cost rc ON rad.id = rc.repair_id-->
<!--        where rad.task_id = #{taskId}-->
<!--        <if test="companyId != null and companyId != ''">-->
<!--            and rad.company_id = #{companyId}-->
<!--        </if>-->
<!--        <if test="keyword != null and keyword != ''">-->
<!--            AND (locate(#{keyword}, mm.ma_code) > 0-->
<!--            or locate(#{keyword}, su.nick_name) > 0-->
<!--            or locate(#{keyword}, mt2.type_name) > 0-->
<!--            or locate(#{keyword}, mt.type_name) > 0)-->
<!--        </if>-->
<!--        <if test="type != null and type != ''">-->
<!--            AND mt.type_id = #{type}-->
<!--        </if>-->
<!--        <if test="typeName != null and typeName != ''">-->
<!--            AND mt2.type_id = #{typeName}-->
<!--        </if>-->
<!--        GROUP BY rad.id-->
<!--        order by rad.create_time desc-->
<!--    </select>-->

    <select id="getById" resultType="com.bonus.material.repair.domain.RepairTaskDetails">
        select rad.id as id,
               rad.repair_num as repairNum,
               rad.repaired_num as repairedNum,
               rad.scrap_num as scrapNum
        from repair_apply_details rad
        where rad.id = #{id}
    </select>

    <select id="selectUserList" resultType="com.bonus.system.api.domain.SysUser">
        SELECT
            su.user_id AS userId,
            su.nick_name AS nickName
        FROM
            sys_user su
                LEFT JOIN sys_user_role sur on su.user_id = sur.user_id
                LEFT JOIN sys_role sr on sur.role_id = sr.role_id
        WHERE sr.role_key = 'wx'
    </select>

    <select id="getAgreementId" resultType="java.lang.Long">
        select agreement_id
        from tm_task_agreement
        where task_id = #{taskId}
        limit 1
    </select>

    <select id="getUnFinish" resultType="java.lang.Integer">
        select count(*)
        from repair_apply_details
        where task_id = #{taskId} and status = '0'
    </select>

    <select id="selectPartPrice" resultType="java.math.BigDecimal">
        select ifnull(buy_price,0) from ma_part_type where pa_id = #{partId}
    </select>

    <!--获取修试后入库列表-->
    <select id="getRepairedList" resultType="com.bonus.material.repair.domain.vo.RepairInputDetailsVo">
        SELECT b.id,
        b.repairCode,
        b.maTypeName,
        b.projectName,
        b.unitName,
        b.wxName,
        b.wxTime,
        b.taskStatus
        FROM (
        SELECT ANY_VALUE(rid.task_id) AS id,
        ANY_VALUE(tt.`code`) AS repairCode,
        ANY_VALUE(GROUP_CONCAT(DISTINCT a.typeName2)) AS maTypeName,
        ANY_VALUE(GROUP_CONCAT(DISTINCT a.typeId2)) AS typeId2,
        bpl.pro_name projectName,
        bui.unit_name unitName,
        ANY_VALUE(us.user_name) AS wxName,
        ANY_VALUE(tt.create_time) AS wxTime,
        tt.task_status AS taskStatus
        FROM repair_input_details rid
        LEFT JOIN repair_apply_details rad on rid.repair_id=rad.id
        LEFT JOIN sys_user us on us.user_id=rad.repairer
        LEFT JOIN tm_task tt ON rid.task_id = tt.task_id
        LEFT JOIN tm_task_agreement tta ON tt.task_id = tta.task_id
        LEFT JOIN bm_agreement_info bai ON tta.agreement_id = bai.agreement_id
        LEFT JOIN bm_project bpl ON bai.project_id = bpl.pro_id
        LEFT JOIN bm_unit bui ON bai.unit_id = bui.unit_id
        LEFT JOIN tm_task tt2 ON rad.task_id = tt2.task_id
        LEFT JOIN (
        SELECT mt.type_id AS typeId,mt.type_name AS typeName,mt.manage_type,mt2.type_id AS typeId2,mt2.type_name AS typeName2
        FROM ma_type mt
        LEFT JOIN ma_type mt2 ON mt2.type_id = mt.parent_id AND mt2.`level` = '3'
        LEFT JOIN ma_type mt3 ON mt2.parent_id = mt3.type_id AND mt3.`level` = '2'
        WHERE mt.`level` = '4'
        )a ON rid.type_id = a.typeId
        GROUP BY rid.task_id
        ORDER BY tt.create_time DESC
        ) b
        <where>
            <if test="deviceTypeId!=null and deviceTypeId!=''">
                b.typeId2 = #{deviceTypeId}
            </if>
            <if test="wxTime!=null and wxTime!=''">
                AND b.wxTime BETWEEN CONCAT(#{wxTime},' 00:00:00') AND CONCAT(#{wxTime},' 23:59:59')
            </if>
            <if test="keyWord!=null and keyWord!=''">
                AND (
                INSTR(b.repairCode,#{keyWord}) > 0 OR
                INSTR(b.wxName,#{keyWord}) > 0
                )
            </if>
        </where>
    </select>

    <!--获取修试后入库-详情列表-->
    <select id="getRepairedDetailList" resultType="com.bonus.material.repair.domain.vo.RepairInputDetailsVo">
        SELECT rid.id,
        rid.ma_id AS maId,
        rid.type_id AS typeId,
        a.typeName,
        a.typeName2,
        rid.repair_num AS repairNum,
        a.manage_type AS manageType,
        mm.ma_code AS maCode,
        rid.update_by AS updateBy,
        rid.update_time AS updateTime,
        rid.remark,
        CASE rid.`status` WHEN '0' THEN '进行中' WHEN '1' THEN '已入库' WHEN '2' THEN '驳回' ELSE '进行中' END AS `status`
        FROM repair_input_details rid
        LEFT JOIN ma_machine mm ON rid.ma_id = mm.ma_id
        LEFT JOIN (
        SELECT mt.type_id AS typeId,mt2.type_id AS typeId2,mt.type_name AS typeName,mt2.type_name AS typeName2,mt.manage_type
        FROM ma_type mt
        LEFT JOIN ma_type mt2 ON mt2.type_id = mt.parent_id AND mt2.`level` = '3'
        LEFT JOIN ma_type mt3 ON mt2.parent_id = mt3.type_id AND mt3.`level` = '2'
        LEFT JOIN ma_type mt4 ON mt3.parent_id = mt4.type_id AND mt4.`level` = '1'
        WHERE mt.`level` = '4'
        )a ON rid.type_id = a.typeId
        WHERE rid.task_id = #{taskId}
        <if test="keyWord!=null and keyWord!=''">
            AND (
            INSTR(rid.update_by,#{keyWord}) > 0 OR
            INSTR(mm.ma_code,#{keyWord}) > 0
            )
        </if>
        <if test="deviceTypeId!=null and deviceTypeId!=''">
            AND a.typeId2 = #{deviceTypeId}
        </if>
        <if test="typeId!=null and typeId!=''">
            AND a.typeId = #{typeId}
        </if>
        ORDER BY rid.create_time DESC
    </select>

    <update id="updateStatusByRepairScrapNum">
        update
            repair_apply_details
        set status = IF((ifnull(repaired_num, 0) + ifnull(scrap_num, 0) >= repair_num), 1, 0)
        where id = #{id}
    </update>

    <select id="getRepairedScrapNumByTaskId" resultType="int">
        SELECT
            SUM(IFNULL(repaired_num,0) + IFNULL(this_repaired_num,0) + IFNULL(scrap_num,0) + IFNULL(this_scrap_num,0) ) as repairNum
        FROM
            repair_apply_details
        WHERE
            task_id = #{taskId}
    </select>

    <select id="getDetailsList" resultType="com.bonus.material.repair.domain.RepairPartDetails">
        SELECT
            mt1.type_name as typeName,
            mt.type_name as typeModelName,
            rar.type_id as typeId,
            rar.task_id as taskId,
            mm.ma_code as maCode,
            rar.repair_num as repairNum,
            rar.scrap_num as scrapNum,
            rar.create_by as createBy,
            rar.create_time as createTime,
            a.repairer as repairer
        FROM
            repair_apply_record rar
                LEFT JOIN ma_type mt ON rar.type_id = mt.type_id
                AND mt.del_flag = '0'
                LEFT JOIN ma_type mt1 ON mt.parent_id = mt1.type_id
                AND mt1.del_flag = '0'
                LEFT JOIN ma_machine mm ON rar.ma_id = mm.ma_id
                LEFT JOIN ( SELECT GROUP_CONCAT( DISTINCT repairer ) AS repairer, task_id, type_id FROM repair_apply_details GROUP BY type_id, task_id ) a ON a.task_id = rar.task_id
                AND a.type_id = rar.type_id
        WHERE
            rar.task_id = #{taskId} and rar.type_id = #{typeId}
    </select>

    <select id="getAuditDetailsById" resultType="com.bonus.material.repair.domain.RepairTaskDetails">
        SELECT
            rad.id,
            rad.ma_id AS maId,
            rad.type_id AS typeId,
            rad.repair_num AS repairNum,
            rad.repaired_num AS repairedNum,
            rad.scrap_num AS scrapNum,
            rad.company_id AS companyId
        FROM
            repair_audit_details rad
        WHERE
            rad.repair_id = #{id}
          AND rad.`status` != '2'
    </select>

    <select id="getRepairTaskDetails" resultType="com.bonus.material.repair.domain.RepairTask">
        select
        rad.task_id as taskId,
        rad.status as status,
        rad.level as level,
        rad.parent_id as parentId
        from repair_apply_details rad
        where rad.task_id in (
        <foreach collection="list" item="item" separator=",">
            #{item.taskId}
        </foreach>
        )
        GROUP BY rad.task_id
    </select>

    <select id="getRepairDetailsById" resultType="com.bonus.material.repair.domain.RepairTaskDetails">
        SELECT
            rad.id AS id,
            rad.ma_id AS maId,
            rad.type_id AS typeId,
            sum( rad.repair_num ) AS repairNum,
            sum( rad.repaired_num ) AS repairedNum,
            sum( rad.scrap_num ) AS scrapNum,
            tt.task_id AS taskId,
            tt.CODE AS taskCode,
            rad.back_id AS backId,
            rad.STATUS AS STATUS,
            rad.LEVEL AS LEVEL
        FROM
            repair_apply_details rad
                LEFT JOIN tm_task tt ON rad.task_id = tt.task_id
        WHERE
            rad.parent_id = #{id}
        GROUP BY
            rad.ma_id, rad.type_id
    </select>

    <select id="selectRepairPartList" resultType="com.bonus.material.repair.domain.vo.RepairPartVo">
        SELECT
            tt.`code` AS repairCode,
            bu.unit_name AS backUnitName,
            bp.pro_name AS backProName,
            mt2.type_name AS typeName,
            mt1.type_name AS typeModelName,
            mm.ma_code AS maCode,
            mt1.unit_name AS unitName,
            rad.repair_num AS repairNum,
            rad.task_id AS taskId,
            rad.type_id AS typeId,
            rad.ma_id AS maId,
            rad.update_time AS repairTime
        FROM
            repair_apply_details rad
                LEFT JOIN repair_audit_details rd ON rad.id = rd.repair_id
                LEFT JOIN tm_task tt ON tt.task_id = rad.task_id
                LEFT JOIN tm_task_agreement tta ON tta.task_id = tt.task_id
                LEFT JOIN bm_agreement_info bagi ON bagi.agreement_id = tta.agreement_id
                AND bagi.`status` = '1'
                LEFT JOIN bm_project bp ON bp.pro_id = bagi.project_id
                AND bp.del_flag = '0'
                LEFT JOIN bm_unit bu ON bu.unit_id = bagi.unit_id
                AND bu.del_flag = '0'
                LEFT JOIN ma_type mt1 ON mt1.type_id = rad.type_id
                AND mt1.del_flag = '0'
                LEFT JOIN ma_type mt2 ON mt2.type_id = mt1.parent_id
                AND mt2.del_flag = '0'
                LEFT JOIN ma_machine mm ON rad.ma_id = mm.ma_id
        WHERE
            rd.`status` = '1'
        <if test="startTime != null and startTime != '' and endTime != null and endTime != ''">
            <![CDATA[and DATE_FORMAT( rad.update_time, '%Y-%m-%d' ) BETWEEN #{startTime} AND #{endTime} ]]>
        </if>
        <if test="typeName != null and typeName != ''">
            and mt2.type_name like CONCAT('%', #{typeName}, '%')
        </if>
        <if test="typeModelName != null and typeModelName != ''">
            and mt1.type_name like CONCAT('%', #{typeModelName}, '%')
        </if>
        <if test="unitId != null">
            and bu.unit_id = #{unitId}
        </if>
        <if test="proId != null">
            and bp.pro_id = #{proId}
        </if>
        ORDER BY rad.update_time DESC
    </select>

    <select id="selectRepairPartInfo" resultType="com.bonus.material.repair.domain.vo.RepairPartVo">
        SELECT
            IFNULL( SUM( rar.part_num ), 0 ) AS partNum,
            GROUP_CONCAT(
            DISTINCT
            CASE
            WHEN rar.part_name IS NOT NULL OR rar.part_id IS NOT NULL
            THEN CONCAT_WS(',', rar.part_name, CASE WHEN rar.part_id IS NOT NULL THEN mpt1.pa_name END)
            ELSE NULL
            END
             ) AS partName,
            GROUP_CONCAT( DISTINCT rar.create_by ) AS repairPerson,
            GROUP_CONCAT( DISTINCT CASE WHEN rar.part_id IS NOT NULL THEN mpt.pa_name END ) AS partModelName
        FROM
            repair_apply_record rar
                LEFT JOIN ma_part_type mpt ON rar.part_id = mpt.pa_id
                AND mpt.del_flag = '0'
                LEFT JOIN ma_part_type mpt1 ON mpt.parent_id = mpt1.pa_id
                AND mpt1.del_flag = '0'
        WHERE
            rar.`status` = '1'
          AND rar.task_id = #{taskId}
        <if test="typeId != null">
            AND rar.type_id = #{typeId}
        </if>
        <if test="maId != null">
            AND rar.ma_id = #{maId}
        </if>
    </select>

    <select id="selectSecondRepairPartList" resultType="com.bonus.material.repair.domain.vo.RepairPartInfo">
        SELECT
            GROUP_CONCAT(
            DISTINCT
            CASE
            WHEN rar.part_name IS NOT NULL OR rar.part_id IS NOT NULL
            THEN CONCAT_WS(',', rar.part_name, CASE WHEN rar.part_id IS NOT NULL THEN mpt1.pa_name END)
            ELSE NULL
            END) AS partName,
            GROUP_CONCAT( DISTINCT CASE WHEN rar.part_id IS NOT NULL THEN mpt.pa_name END ) AS partModelName,
            IFNULL( SUM( rar.part_num ), 0 ) AS partNum,
            CASE
                WHEN rar.part_id IS NOT NULL THEN
                    rar.part_price
                END AS partPrice,
            SUM(
                    CASE
                        WHEN rar.part_type = 1
                            AND rar.part_id IS NOT NULL THEN
                            rar.part_num * rar.part_price
                        WHEN rar.part_type = 1
                            AND rar.part_id IS NULL THEN
                            rar.part_price ELSE 0
                        END
                ) AS partTotalPrice,
            SUM(
                    CASE
                        WHEN rar.part_type = 0
                            AND rar.part_id IS NOT NULL THEN
                            rar.part_num * rar.part_price
                        WHEN rar.part_type = 0
                            AND rar.part_id IS NULL THEN
                            rar.part_price ELSE 0
                        END
                ) AS partNoTotalPrice
        FROM
            repair_apply_record rar
                LEFT JOIN ma_part_type mpt ON rar.part_id = mpt.pa_id
                AND mpt.del_flag = '0'
                LEFT JOIN ma_part_type mpt1 ON mpt.parent_id = mpt1.pa_id
                AND mpt1.del_flag = '0'
        WHERE
            rar.`status` = '1'
          AND rar.task_id = #{taskId}
        <if test="typeId != null">
            AND rar.type_id = #{typeId}
        </if>
        <if test="maId != null">
            AND rar.ma_id = #{maId}
        </if>
        GROUP BY
            rar.part_id,
            rar.part_name
        HAVING
        partName IS NOT NULL
    </select>
    <select id="getDetailsListApp" resultType="com.bonus.material.repair.domain.RepairPartDetails">
        SELECT DISTINCT a.*,
               rad.id       as repairId,
               rid.`status` as checkStatus,
               sad.`status` as scrapStatus,
               CASE
                   WHEN rid.`status` = 0 THEN '待入库'
                   WHEN rid.`status` = 1 THEN '已入库'
                   WHEN sad.`status` = 0 THEN '待报废'
                   WHEN sad.`status` = 1 THEN '已报废'
                   ELSE '未知状态'
                   END      AS status
        FROM (SELECT  mt1.type_name as typeName,
                      mt.type_name as typeModelName,
                      mt.manage_type as manageType,
                      rar.type_id as typeId,
                      rar.task_id as taskId,
                      mm.ma_id as maId,
                      mm.ma_code as maCode,
                      rar.repair_num as repairNum,
                      rar.scrap_num as scrapNum,
                      rar.create_by as createBy,
                      rar.create_time as createTime,
                      GROUP_CONCAT(DISTINCT su.nick_name) as repairer,
                      mpt2.pa_id as partId,
                      GROUP_CONCAT(DISTINCT mpt2.pa_name) as partName
              FROM repair_apply_record rar
                       LEFT JOIN ma_type mt ON rar.type_id = mt.type_id AND mt.del_flag = '0'
                       LEFT JOIN ma_type mt1 ON mt.parent_id = mt1.type_id AND mt1.del_flag = '0'
                       LEFT JOIN ma_machine mm ON rar.ma_id = mm.ma_id
                       LEFT JOIN (SELECT GROUP_CONCAT(DISTINCT repairer) AS repairer,
                                         task_id,
                                         type_id
                                  FROM repair_apply_details
                                  WHERE is_ds = 0
                                  GROUP BY type_id, task_id) a ON a.task_id = rar.task_id AND a.type_id = rar.type_id
                       LEFT JOIN sys_user su ON su.user_id = a.repairer
                       LEFT JOIN ma_part_type mpt ON mpt.pa_id = rar.part_id
                       LEFT JOIN ma_part_type mpt2 ON mpt2.pa_id = mpt.parent_id
              WHERE rar.task_id = #{taskId}
                AND rar.type_id = #{typeId}
                and rar.is_ds = 0
              GROUP BY mm.ma_code,
                       mpt2.pa_id) a
                 LEFT JOIN repair_apply_details rad
                           on rad.ma_id = a.maId and rad.task_id = a.taskId and rad.type_id = a.typeId and rad.is_ds = 0
                 LEFT JOIN repair_input_details rid on rid.repair_id = rad.id and rad.is_ds = 0
                 LEFT JOIN repair_audit_details rads on rads.repair_id = rad.id and rads.ma_id = a.maId
                 LEFT JOIN scrap_apply_details sad on sad.parent_id = rads.id
        <where>
            <if test="keyWord != null and  keyWord != ''">
                AND a.typeName = #{keyWord}
            </if>
            <if test="keyWord != null and keyWord != ''">
                AND a.typeModelName = #{keyWord}
            </if>
        </where>
    </select>
    <select id="getLossPart" resultType="com.bonus.material.repair.domain.vo.RepairPartInfo">
    <![CDATA[
        SELECT rpd.part_id  as partId,
               rpd.part_num as partNum,
               rpd.ds_num as dsNum
        FROM repair_part_details rpd
                 LEFT JOIN repair_apply_details rad
                           ON rad.task_id = rpd.task_id
                               AND rad.type_id = rpd.type_id
                               AND rad.ma_id <=> rpd.ma_id
        AND rad.is_ds = 1
    LEFT JOIN repair_apply_details rad2
        ON rad2.task_id = rad.task_id
            AND rad2.type_id = rad.type_id
            AND rad2.ma_id <=> rad.ma_id
        WHERE
            rad2.id = #{id}
          AND rpd.is_ds = 1
        ]]>
    </select>
    <select id="getPartCount" resultType="com.bonus.material.repair.domain.vo.RepairPartInfo">
        SELECT SUM(repaired_num + this_repaired_num + scrap_num + this_scrap_num) as partNum
        FROM repair_apply_details
        WHERE id = #{id}
    </select>
    <select id="getCostCount" resultType="java.lang.Integer">
        SELECT COUNT(*)
        FROM repair_cost
        WHERE repair_id = #{id}
    </select>

    <select id="getRepairCodeList" resultType="com.bonus.material.repair.domain.RepairTaskDetails">
        SELECT
            rad.id as id,
            rad.task_id as taskId,
            rad.type_id as typeId,
            rad.ma_id as maId,
            mm.ma_code as code,
            mt.type_name as type,
            mt2.type_name as typeName
        FROM
            repair_apply_details rad
                LEFT JOIN ma_machine mm on mm.ma_id=rad.ma_id
                LEFT JOIN ma_type mt on mt.type_id=rad.type_id
                LEFT JOIN ma_type mt2 on mt2.type_id=mt.parent_id
        WHERE
            rad.task_id=#{taskId}
          and rad.type_id=#{typeId}
          and rad.is_ds=0
    </select>

    <select id="getTestRecordData" resultType="com.bonus.material.repair.domain.RepairTaskDetails">
        SELECT
            rad.id,
            rad.type_id as typeId,
            mt.type_name as type,
            mt2.type_name as typeName,
            CONCAT(bai.`code`, '-', rad.`level`) as `code`,
            mm.ma_code as maCode,
            su.nick_name as repairer,
            DATE_FORMAT(rad.update_time,'%Y-%m-%d') as createTime,
            mt.rated_load as ratedLoad,
            mt.test_load as testLoad,
            mt.holding_time as holdingTime,
            rad.scrap_num as scrapNum
        FROM
            repair_apply_details rad
                LEFT JOIN ma_type mt on mt.type_id=rad.type_id
                LEFT JOIN ma_type mt2 on mt2.type_id=mt.parent_id
                LEFT JOIN back_apply_info bai on bai.id=rad.back_id
                LEFT JOIN ma_machine mm on mm.ma_id=rad.ma_id
                LEFT JOIN sys_user su on su.user_id=rad.repairer
        WHERE
            rad.id=#{id}
    </select>

    <select id="getPartData" resultType="com.bonus.material.ma.domain.PartType">
        <![CDATA[
        SELECT rar.part_id  as id,
               mpt2.pa_name as partName

        FROM repair_apply_record rar
                 LEFT JOIN repair_apply_details rad
                           on rad.task_id = rar.task_id and rad.type_id = rar.type_id and rad.ma_id <=> rar.ma_id
                 LEFT JOIN ma_part_type mpt on mpt.pa_id = rar.part_id
                 LEFT JOIN ma_part_type mpt2 on mpt2.pa_id = mpt.parent_id
        WHERE rad.id = #{id}
          and rar.is_ds = 0
          and rar.part_id IS NOT NULL
          and mpt2.pa_name IS NOT NULL
        ]]>
    </select>

    <select id="getRepairedScrapNumById" resultType="java.lang.Integer">
        SELECT
            SUM(repaired_num + scrap_num) as num
        FROM
            repair_apply_details
        WHERE
            id = #{id}
    </select>
    <select id="getPartNum" resultType="java.lang.Integer">
        SELECT SUM(part_num) as partNum
        FROM pa_person_storage
        WHERE part_id = #{partId}
        GROUP BY part_id
    </select>
    <select id="getPartList" resultType="com.bonus.material.repair.domain.RepairPart">
        SELECT id,
               part_id  AS partId,
               part_num AS partNum
        FROM pa_person_storage
        WHERE part_id = #{partId}
          AND is_active = '1'
          AND part_num > 0
        ORDER BY part_num DESC
    </select>

    <select id="selectInfo" resultType="com.bonus.material.repair.domain.RepairTask">
        SELECT
            task_id as taskId,
            SUM(`status`) as num
        FROM
            repair_apply_details
        WHERE
            is_ds='1' and back_id = #{backId}
        GROUP BY task_id
        ORDER BY create_time
        LIMIT 1
    </select>
    <select id="getAppRepairMaTypeListByTaskIdAndTypeId"
            resultType="com.bonus.material.repair.domain.vo.RepairDeviceVO">
        <![CDATA[
        select
            rad.id as id,
            rad.task_id as taskId,
            rad.ma_id as maId,
            mt2.type_name as typeName,
            mt2.type_id as typeNameId,
            mt.type_name as type,
            mt.unit_name as unitName,
            mt.manage_type as manageType,
            mm.ma_code as code,
            ifnull(rad.repair_num, 0) as repairNum,
            sum(ifnull(rad.repaired_num,0) + ifnull(rad.this_repaired_num,0)) as repairedNum,
            sum(ifnull(rad.scrap_num,0) + ifnull(rad.this_scrap_num,0)) as scrapNum,
            rad.status as status,
            su.nick_name as repairer,
            rad.update_time as updateTime,
            rad.type_id as typeId,
            rad.back_id as backId,
            rad.level as level,
            rad.parent_id as parentId,
            rad.create_time,
            bai.CODE AS backCode,
            mt4.type_id AS firstId,
            ( SELECT COUNT(*) FROM repair_cost rc WHERE rc.repair_id = rad.id ) AS totalCostRecords,
             ( SELECT COALESCE(SUM(rc.costs), 0) FROM repair_cost rc WHERE rc.repair_id = rad.id ) AS totalCost,
            rad2.`status` as dataStatus,
            mt.unit_value AS unitValue
        from
            repair_apply_details rad
            left join ma_type mt on rad.type_id = mt.type_id
            left join ma_machine mm on mm.ma_id = rad.ma_id
            left join sys_user su on rad.repairer = su.user_id
            left join ma_type mt2 on mt.parent_id = mt2.type_id
            LEFT JOIN back_apply_info bai ON rad.back_id = bai.id
            left join ma_type mt3 ON mt2.parent_id = mt3.type_id and mt3.del_flag = '0'
            left join ma_type mt4 ON mt3.parent_id = mt4.type_id and mt4.del_flag = '0'
            left join repair_apply_details rad2 on rad2.task_id=rad.task_id and rad2.ma_id <=>  rad.ma_id and rad2.type_id=rad.type_id and rad2.is_ds='1'
              ]]>
        <if test="userId != null">
            JOIN ma_type_repair mtr
            ON mtr.type_id = rad.type_id
            AND mtr.user_id = #{userId}
        </if>
        where
        rad.task_id = #{taskId}
        and rad.type_id=#{typeId}
        and rad.is_ds=0
        <if test="companyId != null and companyId != ''">
            and rad.company_id = #{companyId}
        </if>
        <if test="keyword != null and keyword != ''">
            and mm.ma_code like CONCAT('%', #{keyword}, '%')
        </if>
        <if test="type != null and type != ''">
            AND mt.type_id = #{type}
        </if>
        <if test="typeName != null and typeName != ''">
            AND mt2.type_id = #{typeName}
        </if>
        GROUP BY rad.id
        order by rad.create_time desc
    </select>
    <select id="getRepairInspection" resultType="com.bonus.material.repair.domain.vo.RepairInspection">
        SELECT tt.`code` AS repairCode,
        bu.unit_name AS backUnitName,
        bp.pro_name AS projectName,
        mt2.type_name AS typeName,
        mt1.type_name AS typeModelName,
        mt1.sampling_ratio * SUM(rad.repair_num) / 100 AS num,
        mt1.sampling_ratio AS samplingRatio,
        mt1.rated_load AS ratedLoad,
        mt1.test_load AS testLoad,
        mt1.holding_time AS holdingTime,
        mm.ma_code AS maCode,
        mt1.unit_name AS unitName,
        SUM(rad.repair_num) AS repairNum,
        SUM(rad.repair_num) AS expNum,
        rad.task_id AS taskId,
        rad.type_id AS typeId,
        rad.ma_id AS maId,
        rad.create_time AS repairTime
        FROM repair_apply_details rad
        LEFT JOIN repair_audit_details rd ON rad.id = rd.repair_id
        LEFT JOIN tm_task tt ON tt.task_id = rad.task_id
        LEFT JOIN tm_task_agreement tta ON tta.task_id = tt.task_id
        LEFT JOIN bm_agreement_info bagi ON bagi.agreement_id = tta.agreement_id
        AND bagi.`status` = '1'
        LEFT JOIN bm_project bp ON bp.pro_id = bagi.project_id
        AND bp.del_flag = '0'
        LEFT JOIN bm_unit bu ON bu.unit_id = bagi.unit_id
        AND bu.del_flag = '0'
        LEFT JOIN ma_type mt1 ON mt1.type_id = rad.type_id
        AND mt1.del_flag = '0'
        LEFT JOIN ma_type mt2 ON mt2.type_id = mt1.parent_id
        AND mt2.del_flag = '0'
        LEFT JOIN ma_machine mm ON rad.ma_id = mm.ma_id
        WHERE rd.`status` = '1'
        <if test="startTime != null and startTime != '' and endTime != null and endTime != ''">
            <![CDATA[and DATE_FORMAT( rad.create_time, '%Y-%m-%d' ) BETWEEN #{startTime} AND #{endTime} ]]>
        </if>
        <if test="unitId != null and unitId != ''">
            and bu.unit_id = #{unitId}
        </if>
        <if test="proId != null and proId != ''">
            and bp.pro_id = #{proId}
        </if>
        <if test="typeName != null and typeName != ''">
            and mt2.type_name like CONCAT('%', #{typeName}, '%')
        </if>
        <if test="keyWord != null and keyWord != ''">
            and (mt2.type_name like CONCAT('%', #{keyWord}, '%') OR tt.`code` like CONCAT('%', #{keyWord}, '%') OR
            mt1.type_name like CONCAT('%', #{keyWord}, '%'))
        </if>
        GROUP BY typeName, typeModelName, repairCode
    </select>
    <select id="getTestRecord" resultType="com.bonus.material.repair.domain.vo.TestRecord">
        SELECT
        rad.id AS id,
        tt.`code` AS repairCode,
        bu.unit_name AS backUnitName,
        bp.pro_name AS projectName,
        mt2.type_name AS typeName,
        mt1.type_name AS typeModelName,
        rad.create_time AS repairTime ,
        mm.ma_code AS maCode
        FROM
        repair_apply_details rad
        LEFT JOIN repair_audit_details rd ON rad.id = rd.repair_id
        LEFT JOIN tm_task tt ON tt.task_id = rad.task_id
        LEFT JOIN tm_task_agreement tta ON tta.task_id = tt.task_id
        LEFT JOIN bm_agreement_info bagi ON bagi.agreement_id = tta.agreement_id
        AND bagi.`status` = '1'
        LEFT JOIN bm_project bp ON bp.pro_id = bagi.project_id
        AND bp.del_flag = '0'
        LEFT JOIN bm_unit bu ON bu.unit_id = bagi.unit_id
        AND bu.del_flag = '0'
        LEFT JOIN ma_type mt1 ON mt1.type_id = rad.type_id
        AND mt1.del_flag = '0'
        LEFT JOIN ma_type mt2 ON mt2.type_id = mt1.parent_id
        AND mt2.del_flag = '0'
        LEFT JOIN ma_machine mm ON rad.ma_id = mm.ma_id
        WHERE
        rd.`status` = '1' and mt1.manage_type='0'
        <if test="startTime != null and startTime != '' and endTime != null and endTime != ''">
            <![CDATA[and DATE_FORMAT( rad.create_time, '%Y-%m-%d' ) BETWEEN #{startTime} AND #{endTime} ]]>
        </if>
        <if test="unitId != null and unitId != ''">
            and bu.unit_id = #{unitId}
        </if>
        <if test="proId != null and proId != ''">
            and bp.pro_id = #{proId}
        </if>
        <if test="typeName != null and typeName != ''">
            and mt2.type_name like CONCAT('%', #{typeName}, '%')
        </if>
        <if test="keyWord != null and keyWord != ''">
            and (mt2.type_name like CONCAT('%', #{keyWord}, '%') OR tt.`code` like CONCAT('%', #{keyWord}, '%') OR
            mt1.type_name like CONCAT('%', #{keyWord}, '%') OR mm.ma_code like CONCAT('%', #{keyWord}, '%'))
        </if>
        GROUP BY typeName, typeModelName, repairCode,maCode
    </select>
    <select id="getTestRecordDetails" resultType="com.bonus.material.repair.domain.RepairTaskDetails">
        SELECT
            rad.id,
            rad.type_id as typeId,
            mt.type_name as type,
            mt2.type_name as typeName,
            CONCAT(bai.`code`, '-', rad.`level`) as `code`,
            mm.ma_code as maCode,
            su.nick_name as repairer,
            DATE_FORMAT(rad.update_time,'%Y-%m-%d') as createTime,
            mt.rated_load as ratedLoad,
            mt.test_load as testLoad,
            mt.holding_time as holdingTime,
            rad.scrap_num as scrapNum
        FROM
            repair_apply_details rad
                LEFT JOIN ma_type mt on mt.type_id=rad.type_id
                LEFT JOIN ma_type mt2 on mt2.type_id=mt.parent_id
                LEFT JOIN back_apply_info bai on bai.id=rad.back_id
                LEFT JOIN ma_machine mm on mm.ma_id=rad.ma_id
                LEFT JOIN sys_user su on su.user_id=rad.repairer
        WHERE
            rad.id=#{id}
    </select>
    <select id="getPartDetails" resultType="com.bonus.material.ma.domain.PartType">
        SELECT rar.part_id  as id,
               mpt2.pa_name as partName

        FROM repair_apply_record rar
                 LEFT JOIN repair_apply_details rad
                           on rad.task_id = rar.task_id and rad.type_id = rar.type_id and rad.ma_id = rar.ma_id
                 LEFT JOIN ma_part_type mpt on mpt.pa_id = rar.part_id
                 LEFT JOIN ma_part_type mpt2 on mpt2.pa_id = mpt.parent_id
                 LEFT JOIN ma_part_type mpt3 on mpt2.parent_id = mpt.parent_id
        WHERE rad.id = #{id}
          and rar.is_ds = 0
          and rar.part_id IS NOT NULL
          and mpt2.pa_name IS NOT NULL
    </select>
    <select id="getAppRepairMaTypeListNew" resultType="com.bonus.material.repair.domain.vo.RepairDeviceVO">
        <![CDATA[
        select
            rad.id as id,
            rad.task_id as taskId,
            rad.ma_id as maId,
            mt2.type_name as typeName,
            mt2.type_id as typeNameId,
            mt.type_name as type,
            mt.unit_name as unitName,
            mt.manage_type as manageType,
            mm.ma_code as code,
            ifnull(rad.repair_num, 0) as repairNum,
            sum(ifnull(rad.repaired_num,0) + ifnull(rad.this_repaired_num,0)) as repairedNum,
            sum(ifnull(rad.scrap_num,0) + ifnull(rad.this_scrap_num,0)) as scrapNum,
            rad.status as status,
            rad.status as completeNum,
            su.nick_name as repairer,
            rad.update_time as updateTime,
            rad.type_id as typeId,
            rad.back_id as backId,
            rad.level as level,
            rad.parent_id as parentId,
            rad.create_time,
            bai.CODE AS backCode,
            mt4.type_id AS firstId,
            ( SELECT COUNT(*) FROM repair_cost rc WHERE rc.repair_id = rad.id ) AS totalCostRecords,
             ( SELECT COALESCE(SUM(rc.costs), 0) FROM repair_cost rc WHERE rc.repair_id = rad.id ) AS totalCost,
            rad2.`status` as dataStatus,
            mt.unit_value AS unitValue
        from
            repair_apply_details rad
            left join ma_type mt on rad.type_id = mt.type_id
            left join ma_machine mm on mm.ma_id = rad.ma_id
            left join sys_user su on rad.repairer = su.user_id
            left join ma_type mt2 on mt.parent_id = mt2.type_id
            LEFT JOIN back_apply_info bai ON rad.back_id = bai.id
            left join ma_type mt3 ON mt2.parent_id = mt3.type_id and mt3.del_flag = '0'
            left join ma_type mt4 ON mt3.parent_id = mt4.type_id and mt4.del_flag = '0'
            left join repair_apply_details rad2 on rad2.task_id=rad.task_id and rad2.ma_id <=>  rad.ma_id and rad2.type_id=rad.type_id and rad2.is_ds='1'
              ]]>
        <if test="userId != null">
            JOIN ma_type_repair mtr
            ON mtr.type_id = rad.type_id
            AND mtr.user_id = #{userId}
        </if>
        where
        rad.task_id = #{taskId}
        and rad.is_ds=0
        and (
            rad.repaired_num!=0 or
            rad.this_repaired_num!=0 or
            rad.scrap_num!=0 or
            rad.this_scrap_num!=0
        )
        <if test="companyId != null and companyId != ''">
            and rad.company_id = #{companyId}
        </if>
        <if test="keyword != null and keyword != ''">
            AND (locate(#{keyword}, mm.ma_code) > 0
            or locate(#{keyword}, su.nick_name) > 0
            or locate(#{keyword}, mt2.type_name) > 0
            or locate(#{keyword}, mt.type_name) > 0)
        </if>
        <if test="type != null and type != ''">
            AND mt.type_id = #{type}
        </if>
        <if test="typeName != null and typeName != ''">
            AND mt2.type_id = #{typeName}
        </if>
        GROUP BY rad.id
        order by rad.create_time desc
    </select>
    <select id="getDetailsListAppTwo" resultType="com.bonus.material.repair.domain.RepairPartDetails">
        <![CDATA[
        SELECT mm.ma_code                          as maCode,
               sdd.dict_label as maStatus,
               mt.type_name                        as typeModelName,
               mt1.type_name                       as typeName,
                CASE
	                WHEN rar.create_by is not null THEN
		            rar.create_by
	                ELSE
		            su.nick_name
                    END createBy,
                CASE
	                WHEN rar.create_time is not null THEN
		            rar.create_time
	                ELSE
		            rad.update_time
                    END createTime,
               CASE
                   WHEN rad.repairer REGEXP '^[0-9]+$' THEN su2.nick_name
                   ELSE rad.repairer
                   END                             AS repairer,
               mpt2.pa_id                          as partId,
               GROUP_CONCAT(DISTINCT mpt2.pa_name) as partName
        FROM repair_apply_details rad
                 LEFT JOIN ma_machine mm on mm.ma_id = rad.ma_id
                 LEFT JOIN sys_dict_data sdd on mm.ma_status=sdd.dict_value and sdd.dict_type='ma_machine_status'
                 LEFT JOIN ma_type mt on mt.type_id = rad.type_id
                 LEFT JOIN ma_type mt1 on mt1.type_id = mt.parent_id
                 LEFT JOIN sys_user su on rad.update_by = su.user_id
                 LEFT JOIN sys_user su2 on su2.user_id = rad.repairer
                 LEFT JOIN repair_apply_record rar
                           on rar.task_id = rad.task_id and rar.type_id = rad.type_id and rad.ma_id<=>rar.ma_id and rar.is_ds='0'
        LEFT JOIN ma_part_type mpt
        ON mpt.pa_id = rar.part_id
            LEFT JOIN ma_part_type mpt2 ON mpt2.pa_id = mpt.parent_id
           ]]>
        WHERE rad.task_id = #{taskId}
        and rad.type_id = #{typeId}
        and (
        rad.repaired_num!=0
        or
        rad.this_repaired_num!=0
        or
        rad.scrap_num!=0
        or
        rad.this_repaired_num!=0
        )
        and rad.is_ds = '0'
        <if test="keyWord!=null and keyWord!=''">
            AND mm.ma_code LIKE CONCAT('%', #{keyWord}, '%')
        </if>
        GROUP BY rad.task_id, rad.type_id, rad.ma_id
    </select>

    <update id="updateRepairedAndScrapNum">
        update
            repair_apply_details
        set
            repaired_num = ifnull(repaired_num,0) + #{thisRepairedNum},
            scrap_num = ifnull(scrap_num,0) + #{thisScrapNum},
            update_time = now()
        where
            id = #{id}
    </update>

    <update id="updateRepairer">
        update
            repair_apply_details
        set
            repairer = #{repairer},
            <if test="remark != '' and remark != null">
                remark = #{remark},
            </if>
            update_time = now()
        where
            id = #{id}
    </update>

    <update id="updateStorageNum">
        update
            pa_person_storage
        set
            part_num = part_num - #{partNum}
        where
            part_id = #{partId}
         and creator = #{createBy}
    </update>
    <update id="updateStatus">
        update
            repair_apply_details
        set
            status = '1',
            update_by = #{createBy},
            update_time = now()
        where
            id = #{id}
    </update>
    <update id="updatePartNum">
        update
            pa_person_storage
        set
            part_num = #{partNum}
        where
            id=#{id}
    </update>
    <update id="updateMaMachine">
        UPDATE ma_machine
        SET this_check_time = NOW(),
        next_check_time = DATE_SUB(DATE_ADD(NOW(), INTERVAL 1 YEAR), INTERVAL 1 DAY),
        check_man = #{userName},
        update_time = NOW()
        WHERE ma_id IN (
        SELECT DISTINCT rad.ma_id
        FROM repair_apply_details rad
        INNER JOIN ma_type mt ON mt.type_id = rad.type_id
        WHERE mt.manage_type = 0
        AND mt.jiju_type = 1
        AND rad.id IN
        <foreach item="id" collection="ids" open="(" separator="," close=")">
            #{id}
        </foreach>
        
        )

    </update>
</mapper>
