<?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.lossAssessment.mapper.LossAssessmentMapper">
    <resultMap type="com.bonus.material.ma.domain.PartType" id="PartTypeResult">
        <result property="id" column="pa_id"/>
        <result property="paName" column="pa_name"/>
        <result property="parentId" column="parent_id"/>
        <result property="status" column="status"/>
        <result property="storageNum" column="storage_num"/>
        <result property="unitId" column="unit_id"/>
        <result property="unitName" column="unit_name"/>
        <result property="buyPrice" column="buy_price"/>
        <result property="level" column="level"/>
        <result property="warnNum" column="warn_num"/>
        <result property="delFlag" column="del_flag"/>
        <result property="createBy" column="create_by"/>
        <result property="updateBy" column="update_by"/>
        <result property="createTime" column="create_time"/>
        <result property="updateTime" column="update_time"/>
        <result property="remark" column="remark"/>
        <result property="companyId" column="company_id"/>
    </resultMap>

    <resultMap type="com.bonus.material.task.domain.TmTask" id="TmTaskResult">
        <result property="taskId"    column="task_id"    />
        <result property="preTaskId"    column="pre_task_id"    />
        <result property="taskType"    column="task_type"    />
        <result property="taskStatus"    column="task_status"    />
        <result property="code"    column="code"    />
        <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="monthOrder"    column="month_order"    />
        <result property="splitType"    column="split_type"    />
    </resultMap>

    <resultMap type="com.bonus.material.repair.domain.RepairApplyDetails" id="RepairApplyDetailsResult">
        <result property="id"    column="id"    />
        <result property="taskId"    column="task_id"    />
        <result property="maId"    column="ma_id"    />
        <result property="typeId"    column="type_id"    />
        <result property="repairNum"    column="repair_num"    />
        <result property="repairedNum"    column="repaired_num"    />
        <result property="scrapNum"    column="scrap_num"    />
        <result property="status"    column="status"    />
        <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="backId"    column="back_id"    />
        <result property="repairer"    column="repairer"    />
        <result property="preTaskId"    column="pre_task_id"    />
    </resultMap>

    <sql id="selectTmTaskVo">
        select task_id, pre_task_id, task_type, task_status, code, create_by, create_time,
               update_by, update_time, remark, company_id, month_order
        from tm_task
    </sql>

    <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,ds_num,is_ds)
        values (#{taskId}, #{maId}, #{typeId}, #{partId}, #{partNum}, #{partCost}, #{partType}, #{createBy}, now(),
                #{companyId}, #{repairContent},#{dsNum},1)
    </insert>

    <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,is_ds)
        values (#{taskId}, #{maId}, #{typeId}, #{repairNum}, #{scrapNum}, #{repairType}, #{createBy}, now(),
                #{repairContent}, #{companyId}, #{scrapId}, #{scrapReason}, #{scrapType}, #{supplierId}, #{partNum},
                #{partPrice}, #{partType}, #{partName}, #{repairer}, #{fileIds}, #{remark}, #{partId},1)
    </insert>

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

    <insert id="insertRad">
        insert into repair_apply_details
        (
        <if test="taskId != 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>
            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>
        is_ds,
        create_time
        )
        values (
        <if test="taskId != null">
            #{taskId},
        </if>
        <if test="maId != null">
            #{maId},
        </if>
        <if test="typeId != null">
            #{typeId},
        </if>
        <if test="repairNum != null">
            #{repairNum},
        </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>
        0,
        NOW()
        )
    </insert>

    <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="updateRepairer">
        update
        repair_apply_details
        set
        repairer = #{repairer},
        status = 1,
        <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="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="updateStatusByRepairScrapNum">
        update
            repair_apply_details
        set status = 1
        where id = #{id}
    </update>

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

    <update id="updateTaskStatus">
        update tm_task
        set task_status = #{newStatus},
            update_time = NOW()
        where task_id = #{taskId}
    </update>

    <update id="updateIsDs">
        update repair_apply_details
        set is_ds = 0
        where task_id = #{taskId}
    </update>

    <update id="updateStatus">
        update repair_apply_details
        set status = 1
        where task_id = #{taskId}
          and is_ds = 1
    </update>

    <delete id="deleteTask">
        delete from tm_task where task_id = #{taskId}
    </delete>
    <delete id="deleteApplyDetailsByTaskId">
        delete from repair_apply_details where task_id = #{taskId}
    </delete>
    <delete id="deleteRecordByTaskId">
        delete from repair_apply_record where task_id = #{taskId}
    </delete>
    <delete id="deletePartByTaskId">
        delete from repair_part_details where task_id = #{taskId}
    </delete>
    <delete id="deleteCostByTaskId">
        delete from repair_cost where task_id = #{taskId}
    </delete>
    <delete id="delDetailsById">
        delete from repair_apply_details where id = #{id}
    </delete>
    <delete id="delRecord">
        delete from repair_apply_record where task_id = #{taskId} and type_id = #{typeId}
        <if test="maId != null">
            and ma_id = #{maId}
        </if>
    </delete>
    <delete id="delPart">
        delete from repair_part_details where task_id = #{taskId} and type_id = #{typeId}
        <if test="maId != null">
            and ma_id = #{maId}
        </if>
    </delete>
    <delete id="delCost">
        delete from repair_cost where task_id = #{taskId} and type_id = #{typeId}
        <if test="maId != null">
            and ma_id = #{maId}
        </if>
    </delete>

    <select id="getLossAssessmentList" 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,
        GROUP_CONCAT(DISTINCT mt2.type_name) as type,
        rd.level as level,
        SUM(rd.repair_num) as repairNum,
        bai.back_person as backPerson,
        CASE tt.task_status
        WHEN 0 THEN
        0
        ELSE
        1
        END `status`,
        rd.`status` as dataStatus
        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
        <if test="userId != null">
            JOIN ma_type_repair mtr ON mtr.type_id = rd.type_id AND mtr.user_id = #{userId}
        </if>
        where
        rd.is_ds=1
        <if test="appTaskStatus !=null">
          <if test="appTaskStatus==0">
              and tt.task_status = 0
          </if>
            <if test="appTaskStatus==1">
                and (tt.task_status = 1 or tt.task_status = 2 or tt.task_status = 4)
            </if>
        </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>
        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="getRepairDeviceList" resultType="com.bonus.material.repair.domain.vo.RepairDeviceVO">
        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,
        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,
        ( 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
        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
        where
        rad.task_id = #{taskId}
        and is_ds=1
        <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="selectPartPrice" resultType="java.math.BigDecimal">
        select ifnull(buy_price, 0)
        from ma_part_type
        where pa_id = #{partId}
    </select>

    <sql id="selectPartTypeVo">
        select pa_id,
               pa_name,
               parent_id,
               status,
               storage_num,
               unit_id,
               unit_name,
               buy_price,
               level,
               warn_num,
               del_flag,
               create_by,
               update_by,
               create_time,
               update_time,
               remark,
               company_id
        from ma_part_type
    </sql>

    <select id="selectPartTypeByPaId" parameterType="Long" resultMap="PartTypeResult">
        <include refid="selectPartTypeVo"/>
        where pa_id = #{id}
    </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="getRepairDetailsWhichNotSent" resultType="com.bonus.material.repair.domain.RepairTaskDetails">
        select rad.id                as id,
               rad.ma_id             as maId,
               rad.type_id           as typeId,
               rad.repair_num        as repairNum,
               rad.this_repaired_num,
               rad.this_scrap_num,
               rad.repaired_num      as repairedNum,
               rad.this_repaired_num as thisRepairedNum,
               rad.scrap_num         as scrapNum,
               rad.this_scrap_num    as thisScrapNum,
               rad.company_id        as companyId,
               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.task_id = #{taskId}
          and rad.is_ds = 1
    </select>

    <select id="getRepairedScrapNumByTaskId" resultType="java.lang.Integer">
        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="selectTmTaskByTaskId" parameterType="Long" resultMap="TmTaskResult">
        <include refid="selectTmTaskVo"/>
        where task_id = #{taskId}
    </select>

    <select id="getDetailsListApp" 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,
            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=1
                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=1
        GROUP BY
            mm.ma_code,
            mpt2.pa_id
    </select>
    <select id="selectTaskStatus" resultType="java.lang.Integer">
        SELECT task_status as taskStatus
        FROM tm_task
        WHERE task_id = #{taskId}
    </select>
    <select id="selectRepairApplyDetailsById" parameterType="Long" resultMap="RepairApplyDetailsResult">
        SELECT
            rad.id,
            rad.task_id,
            rad.ma_id,
            rad.type_id,
            rad.repair_num,
            rad.repaired_num,
            rad.scrap_num,
            rad.STATUS,
            rad.create_by,
            rad.create_time,
            rad.update_by,
            rad.update_time,
            rad.remark,
            rad.company_id,
            rad.back_id,
            rad.repairer,
            tt.pre_task_id
        FROM
            repair_apply_details rad
                LEFT JOIN tm_task tt on tt.task_id=rad.task_id
        WHERE
        id = #{id}
    </select>


</mapper>
