<?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.scrap.mapper.ScrapApplyDetailsMapper">
    <resultMap type="com.bonus.material.scrap.domain.ScrapApplyDetails" id="ScrapApplyDetailsResult">
        <result property="id"    column="id"    />
        <result property="taskId"    column="task_id"    />
        <result property="parentId"    column="parent_id"    />
        <result property="maId"    column="ma_id"    />
        <result property="typeId"    column="type_id"    />
        <result property="scrapNum"    column="scrap_num"    />
        <result property="scrapSource"    column="scrap_source"    />
        <result property="scrapType"    column="scrap_type"    />
        <result property="status"    column="status"    />
        <result property="auditBy"    column="audit_by"    />
        <result property="auditTime"    column="audit_time"    />
        <result property="auditRemark"    column="audit_remark"    />
        <result property="createBy"    column="create_by"    />
        <result property="createTime"    column="create_time"    />
        <result property="updateBy"    column="update_by"    />
        <result property="updateTime"    column="update_time"    />
        <result property="remark"    column="remark"    />
        <result property="companyId"    column="company_id"    />
        <result property="fileName"    column="file_name"    />
        <result property="fileUrl"    column="file_url"    />
    </resultMap>

    <sql id="selectScrapApplyDetailsVo">
        select id, task_id, parent_id, ma_id, type_id, scrap_num, scrap_source, scrap_type, status, audit_by, audit_time,
               audit_remark, create_by, create_time, update_by, update_time, remark, company_id, file_name, file_url
        from scrap_apply_details
    </sql>

    <select id="selectScrapApplyDetailsList" parameterType="com.bonus.material.scrap.domain.ScrapApplyDetails" resultType="com.bonus.material.scrap.domain.vo.ScrapTaskListVo">
        SELECT
            sad.task_id as taskId, sad.create_time as createTime,sad.update_time,sad.company_id,
            tt.`code` AS scrapCode, tt2.`code` as repairCode ,tt.task_status AS taskStatus,tt.task_type as taskType,tt.company_id AS companyId,tt.remark,
            bui.unit_name AS backUnit,
            bpi.pro_name AS backPro,
            sad.create_by AS createName,
            tta.agreement_id as agreementId,
            GROUP_CONCAT(DISTINCT mt2.type_name) as type,
            CASE tt.task_status
                   when 0 then '报废审核进行中'
                   when 1 then '报废审核通过'
                   when 2 then '报废审核驳回'
                   else '未知'
            END as taskStatusName,
            su1.nick_name as auditByName,
            sad.audit_time as auditTime
        FROM
            scrap_apply_details sad
        LEFT JOIN ma_type mt on sad.type_id = mt.type_id
        LEFT JOIN ma_type mt2 on mt.parent_id = mt2.type_id
        LEFT JOIN tm_task tt on sad.task_id = tt.task_id
        LEFT JOIN tm_task_agreement tta ON sad.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 su1 on sad.audit_by = su1.user_id
        left join repair_audit_details rad ON sad.parent_id = rad.id
        left join tm_task tt2 ON tt2.task_id = rad.task_id
        where
            sad.scrap_source = '2'
            <if test="typeId != null "> and type_id = #{typeId}</if>
            <if test="appTaskStatus != null and appTaskStatus == 0">
                and tt.task_status = #{appTaskStatus}
            </if>
            <if test="appTaskStatus != null and appTaskStatus == 1">
                and (tt.task_status = 1 or tt.task_status = 2)
            </if>
            <if test="auditBy != null "> and audit_by = #{auditBy}</if>
            <if test="taskStatus != null "> and tt.task_status = #{taskStatus}</if>
            <if test="startTime != null and startTime != '' and endTime != null and endTime != ''">
                <![CDATA[and DATE_FORMAT( sad.create_time, '%Y-%m-%d' ) BETWEEN #{startTime} AND #{endTime} ]]>
            </if>
        GROUP BY sad.task_id,bui.unit_name,bpi.pro_name
        order by tt.create_time desc
    </select>



    <select id="selectRepairQuestListByTaskId" resultType="com.bonus.material.scrap.domain.ScrapApplyDetails">
        select
            sad.id as id,sad.task_id as taskId,sad.parent_id as parentId,sad.ma_id as maId,
            sad.status as status,rad.repair_id as repairId,
            sad.scrap_source as scrapSource, ifnull(sad.scrap_num,0) as scrapNum,
            sad.audit_by,sad.audit_remark,sad.audit_time as auditTime,
            sad.update_time as updateTime,sad.type_id as typeId,
            sad.create_by,sad.create_time,sad.file_name,sad.file_url,
            mt2.type_name as typeName,mt2.type_id as typeNameId,
            mt.type_name as typeModelName,mt.unit_name as unitName,mt.manage_type as manageType,
            mm.ma_code as code,
            su.nick_name as scraper,
            CASE sad.status
                when 0 then '报废审核进行中'
                when 1 then '报废审核通过'
                when 2 then '报废审核驳回'
                else '未知'
             END as statusName,
            ifnull(rad.repair_num,0) as repairNum,
            ifnull(rad.repaired_num,0) as repairedNum,
            mt.buy_price as buyPrice,
            rar.scrap_reason as scrapReason,
            rar.scrap_type as scrapType
        from
            scrap_apply_details sad
                left join ma_type mt on sad.type_id = mt.type_id
                left join ma_machine mm on mm.ma_id = sad.ma_id
                left join sys_user su on sad.create_by = su.user_id
                left join ma_type mt2 on mt.parent_id = mt2.type_id
                left join repair_audit_details rad on sad.parent_id = rad.id
                LEFT JOIN repair_apply_details ra on rad.repair_id = ra.id
                LEFT JOIN repair_apply_record rar on rar.task_id = ra.task_id
                and (case when mt.manage_type = 0 then rar.ma_id = ra.ma_id
                          when mt.manage_type = 1 then rar.type_id = ra.type_id
                          else false end) and rar.repair_type = '3'
        where
        sad.task_id = #{taskId}
        <if test="keyWord != null  and keyWord != ''">
            and (
            mt2.type_name like concat('%', #{keyWord}, '%') or
            mt.type_name like concat('%', #{keyWord}, '%') or
            mm.ma_code like concat('%', #{keyWord}, '%') or
            su.nick_name like concat('%', #{keyWord}, '%') or
            rar.scrap_reason like concat('%', #{keyWord}, '%')
            )
        </if>
        GROUP BY sad.id
        order by sad.create_time desc
    </select>
    
    <select id="selectScrapApplyDetailsById" parameterType="Long" resultMap="ScrapApplyDetailsResult">
        <include refid="selectScrapApplyDetailsVo"/>
        where id = #{id}
    </select>
        
    <insert id="insertScrapApplyDetails" parameterType="com.bonus.material.scrap.domain.ScrapApplyDetails" useGeneratedKeys="true" keyProperty="id">
        insert into scrap_apply_details
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="taskId != null">task_id,</if>
            <if test="parentId != null">parent_id,</if>
            <if test="maId != null">ma_id,</if>
            <if test="typeId != null">type_id,</if>
            <if test="scrapNum != null">scrap_num,</if>
            <if test="scrapSource != null">scrap_source,</if>
            <if test="scrapType != null">scrap_type,</if>
            <if test="status != null">status,</if>
            <if test="auditBy != null">audit_by,</if>
            <if test="auditTime != null">audit_time,</if>
            <if test="auditRemark != null">audit_remark,</if>
            <if test="createBy != null">create_by,</if>
            <if test="createTime != null">create_time,</if>
            <if test="updateBy != null">update_by,</if>
            <if test="updateTime != null">update_time,</if>
            <if test="remark != null">remark,</if>
            <if test="companyId != null">company_id,</if>
            <if test="fileName != null">file_name,</if>
            <if test="fileUrl != null">file_url,</if>
            <if test="scrapReason != null and scrapReason != ''">scrap_reason,</if>
         </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="taskId != null">#{taskId},</if>
            <if test="parentId != null">#{parentId},</if>
            <if test="maId != null">#{maId},</if>
            <if test="typeId != null">#{typeId},</if>
            <if test="scrapNum != null">#{scrapNum},</if>
            <if test="scrapSource != null">#{scrapSource},</if>
            <if test="scrapType != null">#{scrapType},</if>
            <if test="status != null">#{status},</if>
            <if test="auditBy != null">#{auditBy},</if>
            <if test="auditTime != null">#{auditTime},</if>
            <if test="auditRemark != null">#{auditRemark},</if>
            <if test="createBy != null">#{createBy},</if>
            <if test="createTime != null">#{createTime},</if>
            <if test="updateBy != null">#{updateBy},</if>
            <if test="updateTime != null">#{updateTime},</if>
            <if test="remark != null">#{remark},</if>
            <if test="companyId != null">#{companyId},</if>
            <if test="fileName != null">#{fileName},</if>
            <if test="fileUrl != null">#{fileUrl},</if>
            <if test="scrapReason != null and scrapReason != ''">#{scrapReason},</if>
         </trim>
    </insert>

    <insert id="insertRad">
        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="scrapNum != null">
            repair_num,
        </if>
        status,
        <if test="createBy != null and createBy != ''">
            create_by,
        </if>
        <if test="remark != null and remark != ''">
            remark,
        </if>
        <if test="companyId != null">
            company_id,
        </if>
        <if test="backId != null">
            back_id,
        </if>
        create_time
        )
        values (
        <if test="newTaskId != null">
            #{newTaskId},
        </if>
        <if test="maId != null">
            #{maId},
        </if>
        <if test="typeId != null">
            #{typeId},
        </if>
        <if test="scrapNum != null">
            #{scrapNum},
        </if>
        0,
        <if test="createBy != null and createBy != ''">
            #{createBy},
        </if>
        <if test="remark != null and remark != ''">
            #{remark},
        </if>
        <if test="companyId != null">
            #{companyId},
        </if>
        <if test="backId != null">
            #{backId},
        </if>
        NOW()
        )
    </insert>

    <update id="updateScrapApplyDetails" parameterType="com.bonus.material.scrap.domain.ScrapApplyDetails">
        update scrap_apply_details
        <trim prefix="SET" suffixOverrides=",">
            <if test="taskId != null">task_id = #{taskId},</if>
            <if test="parentId != null">parent_id = #{parentId},</if>
            <if test="maId != null">ma_id = #{maId},</if>
            <if test="typeId != null">type_id = #{typeId},</if>
            <if test="scrapNum != null">scrap_num = #{scrapNum},</if>
            <if test="scrapSource != null">scrap_source = #{scrapSource},</if>
            <if test="scrapType != null">scrap_type = #{scrapType},</if>
            <if test="status != null">status = #{status},</if>
            <if test="auditBy != null">audit_by = #{auditBy},</if>
            <if test="auditTime != null">audit_time = #{auditTime},</if>
            <if test="auditRemark != null">audit_remark = #{auditRemark},</if>
            <if test="createBy != null">create_by = #{createBy},</if>
            <if test="createTime != null">create_time = #{createTime},</if>
            <if test="updateBy != null">update_by = #{updateBy},</if>
            <if test="updateTime != null">update_time = #{updateTime},</if>
            <if test="remark != null">remark = #{remark},</if>
            <if test="companyId != null">company_id = #{companyId},</if>
            <if test="fileName != null">file_name = #{fileName},</if>
            <if test="fileUrl != null">file_url = #{fileUrl},</if>
        </trim>
        where id = #{id}
    </update>

    <update id="updateStatus">
        update scrap_apply_details
        set status = #{status},
            audit_by = #{auditBy},
            audit_time = #{auditTime}
        where id = #{id}
    </update>

    <update id="updateMaStatus">
        update ma_machine
        set ma_status = #{status}
        where ma_id = #{maId}
    </update>

    <update id="ledgerApprove">
        update scrap_apply_details
        set ledger_status = #{ledgerStatus},
            ledger_by = #{ledgerBy},
            ledger_time = #{ledgerTime},
            reject_reason = #{rejectReason}
        where id = #{id}
    </update>

    <update id="updateStorageNum">
        update ma_type
        set storage_num = storage_num - IFNULL(#{scrapNum}, 0)
        where type_id = #{typeId}
    </update>

    <update id="updateTaskStatus">
        update scrap_apply_details
        set status = #{status},
            audit_by = #{auditBy},
            audit_time = #{auditTime}
        where task_id = #{taskId}
    </update>

    <update id="updateStorageNumAdd">
        update ma_type
        set storage_num = storage_num + IFNULL(#{scrapNum}, 0)
        where type_id = #{typeId}
    </update>

    <delete id="deleteScrapApplyDetailsById" parameterType="Long">
        delete from scrap_apply_details where id = #{id}
    </delete>

    <delete id="deleteScrapApplyDetailsByIds" parameterType="String">
        delete from scrap_apply_details where id in 
        <foreach item="id" collection="array" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>

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

    <select id="getByRepairId" resultType="com.bonus.material.repair.domain.RepairAuditDetails">
        select task_id as taskId,
               ma_id as maId,
               type_id as typeId
        from repair_apply_details
        where id = #{repairId}
    </select>

    <select id="getGyoupRepairRecord" resultType="com.bonus.material.repair.domain.RepairRecord">
        select sum(scrap_num) as scrapNum,
        scrap_reason as scrapReason,
        scrap_type as scrapType,
        file_ids as fileIds
        from repair_apply_record rar
        where repair_type = '3'
        <if test="taskId != null and taskId != ''">
            and rar.task_id = #{taskId}
        </if>
        <if test="maId != null and maId != ''">
            and rar.ma_id = #{maId}
        </if>
        <if test="typeId != null and typeId != ''">
            and rar.type_id = #{typeId}
        </if>
        group by scrap_type
    </select>

    <select id="selectBackIdByTaskId" resultType="java.lang.Long">
        SELECT
            ra.back_id
        FROM
            scrap_apply_details sad
                LEFT JOIN repair_audit_details rad ON sad.parent_id = rad.id
                LEFT JOIN repair_apply_details ra ON rad.repair_id = ra.id
        WHERE
            sad.parent_id = #{parentId}
    </select>

    <select id="selectScrapByTaskId" resultType="com.bonus.material.scrap.domain.ScrapApplyDetails">
        SELECT
        task_id as taskId,
        ma_id as maId,
        type_id as typeId,
        GROUP_CONCAT(DISTINCT scrap_reason) AS scrapReason,
        GROUP_CONCAT(DISTINCT scrap_type) AS scrapType,
        GROUP_CONCAT(DISTINCT create_by) AS createBy
        FROM
        repair_apply_record
        WHERE repair_type = '3' and task_id = #{taskId} and type_id = #{typeId}
        <if test="maId != null">
            and ma_id = #{maId}
        </if>
    </select>

    <select id="selectTotalScrapApplyDetailsList"
            resultType="com.bonus.material.scrap.domain.vo.ScrapTotalListVo">
        SELECT
        GROUP_CONCAT( sad.id ) AS ids,
        GROUP_CONCAT( sad.task_id ) AS taskIds,
        mt2.type_name AS typeName,
        mt.type_id AS typeId,
        mt.type_name AS typeModelName,
        mt.unit_name AS unitName,
        mt.manage_type AS manageType,
        sum( sad.scrap_num ) AS scrapNum,
        mt.buy_price AS buyPrice,
        sad.scrap_type AS scrapType,
        GROUP_CONCAT( DISTINCT sad.create_by ) AS createName,
        DATE_FORMAT( sad.create_time, '%Y-%m' ) AS month,
        sad.ledger_status AS ledgerStatus,
        sad.scrap_source AS scrapSource
        FROM
        scrap_apply_details sad
        LEFT JOIN ma_type mt ON sad.type_id = mt.type_id
        LEFT JOIN ma_type mt2 ON mt.parent_id = mt2.type_id
        WHERE sad.`status` = '1' and sad.ledger_status = '0'
        <if test="keyWord != null  and keyWord != ''">
            AND (
            mt2.type_name like concat('%', #{keyWord}, '%') or
            mt.type_name like concat('%', #{keyWord}, '%') or
            sad.scrap_type like concat('%', #{keyWord}, '%')
            )
        </if>
        <if test="month != null and month != ''">
            <![CDATA[
            AND DATE_FORMAT( sad.create_time, '%Y-%m' ) = DATE_FORMAT(#{month}, '%Y-%m')
            ]]>
        </if>
        GROUP BY
        sad.type_id,
        sad.scrap_type,
        DATE_FORMAT(
        sad.create_time,
        '%Y-%m'),
        sad.scrap_source
    </select>

    <select id="selectInventoryList" resultType="com.bonus.material.scrap.domain.vo.ScrapTaskListVo">
        SELECT
            tt.task_id as taskId,
            GROUP_CONCAT( sad.id ) AS ids,
            tt.code AS scrapCode,
            GROUP_CONCAT( DISTINCT mt1.type_name ) AS type,
            sad.create_by AS createName,
            sad.create_time AS createTime,
            tt.task_status  AS taskStatus
        FROM
            scrap_apply_details sad
                LEFT JOIN ma_type mt ON sad.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 tm_task tt on sad.task_id = tt.task_id
        AND tt.task_type = 15
        where sad.scrap_source = '3'
        <if test="taskStatus != null "> and tt.task_status = #{taskStatus}</if>
        <if test="startTime != null and startTime != '' and endTime != null and endTime != ''">
            <![CDATA[and DATE_FORMAT( sad.create_time, '%Y-%m-%d' ) BETWEEN #{startTime} AND #{endTime} ]]>
        </if>
        GROUP BY sad.task_id
        ORDER BY sad.create_time DESC
    </select>

    <select id="getMonthMaxOrderByDate" resultType="java.lang.Integer">
        select
               COALESCE(max(month_order), 0) from scrap_apply_details
        where
            month(create_time) = #{month} and year(create_time) = #{year}
    </select>

    <select id="getDetailsList" resultType="com.bonus.material.scrap.domain.ScrapApplyDetails">
        SELECT
            sad.task_id AS taskId,
            mt.type_id AS typeId,
            mt1.type_name AS maTypeName,
            mt.type_name AS typeName,
            mt.unit_name AS unitName,
            SUM(sad.scrap_num) AS scrapNum,
            GROUP_CONCAT( DISTINCT sad.ma_id ) AS maIds,
            GROUP_CONCAT( DISTINCT mm.ma_code ) AS maCode,
            mt.manage_type AS manageType,
            sad.scrap_reason AS scrapReason
        FROM
            scrap_apply_details sad
                LEFT JOIN ma_type mt ON sad.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 sad.ma_id = mm.ma_id
        where
            sad.task_id = #{taskId}
        <if test="typeId != null">
            AND sad.type_id = #{typeId}
        </if>
        <if test="keyWord != null  and keyWord != ''">
            AND (
            mt1.type_name like concat('%', #{keyWord}, '%') or
            mt.type_name like concat('%', #{keyWord}, '%')
            )
        </if>
        GROUP BY
            sad.type_id
    </select>

    <select id="getScrapList" resultType="com.bonus.material.scrap.domain.vo.ScrapTotalListVo">
        SELECT
        mt2.type_name AS typeName,
        mt.type_id AS typeId,
        mt.type_name AS typeModelName,
        mt.unit_name AS unitName,
        mt.manage_type AS manageType,
        sad.scrap_num AS scrapNum,
        mt.buy_price AS buyPrice,
        sad.create_by  AS createName,
        DATE_FORMAT( sad.ledger_time, '%Y-%m' ) AS month,
        sad.ledger_status AS ledgerStatus
        FROM
        scrap_apply_details sad
        LEFT JOIN ma_type mt ON sad.type_id = mt.type_id
        LEFT JOIN ma_type mt2 ON mt.parent_id = mt2.type_id
        WHERE sad.`status` = '1' and sad.ledger_status = '1'
        <if test="startTime != null and startTime != '' and endTime != null and endTime != ''">
            <![CDATA[
            AND DATE_FORMAT( sad.create_time, '%Y-%m' ) BETWEEN DATE_FORMAT(#{startTime}, '%Y-%m') AND DATE_FORMAT(#{endTime}, '%Y-%m')
            ]]>
        </if>
    </select>

    <select id="getScrapDetailsList" resultType="com.bonus.material.scrap.domain.vo.ScrapDetailsListVo">
        SELECT
            mt2.type_name AS typeName,
            mt.type_id AS typeId,
            mt.type_name AS typeModelName,
            mt.unit_name AS unitName,
            mt.manage_type AS manageType,
            sum( sad.scrap_num ) AS scrapNum,
            mt.buy_price AS buyPrice,
            sad.scrap_type AS scrapType,
            GROUP_CONCAT( DISTINCT su.nick_name ) AS auditName,
            DATE_FORMAT( sad.ledger_time, '%Y-%m-%d' ) AS month,
        sad.ledger_status AS ledgerStatus,
        sad.scrap_source AS scrapSource
        FROM
            scrap_apply_details sad
            LEFT JOIN ma_type mt ON sad.type_id = mt.type_id
            LEFT JOIN ma_type mt2 ON mt.parent_id = mt2.type_id
            LEFT JOIN sys_user su on sad.ledger_by = su.user_id
        WHERE sad.`status` = '1' and sad.ledger_status = '1'
            and DATE_FORMAT( sad.ledger_time, '%Y-%m' ) = #{month}
        <if test="keyWord != null  and keyWord != ''">
            AND (
            mt2.type_name like concat('%', #{keyWord}, '%') or
            mt.type_name like concat('%', #{keyWord}, '%') or
            sad.scrap_type like concat('%', #{keyWord}, '%')
            )
        </if>
        <if test="startTime != null and startTime != '' and endTime != null and endTime != ''">
            <![CDATA[
            AND DATE_FORMAT( sad.ledger_time, '%Y-%m-%d' ) BETWEEN DATE_FORMAT(#{startTime}, '%Y-%m-%d') AND DATE_FORMAT(#{endTime}, '%Y-%m-%d')
            ]]>
        </if>
        GROUP BY
            sad.type_id,
            sad.scrap_type,
            sad.scrap_source
    </select>

    <select id="selectMaTypeList" resultType="com.bonus.material.ma.domain.Type">
        select
        m.type_id as typeId,
        CASE m.manage_type
        WHEN 0 THEN
        IFNULL(subquery0.num, 0)
        ELSE
        IFNULL(m.storage_num, 0)
        END as storageNum
        from ma_type m
        left join (SELECT mt.type_id,
        mt2.type_name AS             typeName,
        mt.type_name  AS             typeModelName,
        count(mm.ma_id) num
        FROM ma_machine mm
        LEFT JOIN ma_type mt ON mt.type_id = mm.type_id
        LEFT JOIN ma_type mt2 ON mt2.type_id = mt.parent_id
        WHERE mm.ma_code is not null and mm.ma_status in (1)
        GROUP BY mt.type_id) AS subquery0 ON subquery0.type_id = m.type_id
        where
        m.del_flag = '0'
        AND m.type_id = #{typeId}
    </select>

</mapper>