<?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.jeeplus.psimanage.foodPurchase.mapper.PsiFoodPurchaseBasicMapper">

    <update id="updateStatusById">
        UPDATE psi_management_food_purchase_basic
        SET status = #{status}
        WHERE id = #{id}
    </update>

    <update id="updateFlowInfoById">
        UPDATE psi_management_food_purchase_basic
        SET status = #{status},
            proc_ins_id = #{procInsId},
            process_definition_id = #{processDefinitionId}
        WHERE id = #{id}
    </update>

    <select id="findChildIds" resultType="java.lang.String">
        SELECT id
        FROM sys_office
        WHERE parent_id = #{department}
    </select>

    <select id="findList" resultType="com.jeeplus.psimanage.foodPurchase.service.dto.PsiFoodPurchaseDto">
        SELECT
            a.id,
            a.create_by_id AS createBy,
            a.create_time,
            a.purchase_no,
            a.handled_by,
            a.handled_by_office,
            a.purchase_time,
            a.total_price,
            a.status AS formalStatus,
            IFNULL(c.status, a.status) AS status,
            c.id AS changeId,
            c.status AS changeStatus,
            c.purchase_time AS changePurchaseTime,
            c.total_price AS changeTotalPrice,
            IFNULL(c.proc_ins_id, a.proc_ins_id) AS procInsId,
            IFNULL(c.process_definition_id, a.process_definition_id) AS processDefinitionId,
            su.name AS handledByName,
            so.name AS handledByOfficeName,
            art.ID_ AS taskId
        FROM psi_management_food_purchase_basic a
        LEFT JOIN psi_management_food_purchase_change c
            ON c.source_basic_id = a.id
            AND c.del_flag = 0
            AND c.status IN ('1', '2', '3', '4')
        LEFT JOIN sys_user su ON a.handled_by = su.id
        LEFT JOIN sys_office so ON a.handled_by_office = so.id
        LEFT JOIN act_ru_task art ON IFNULL(c.proc_ins_id, a.proc_ins_id) = art.PROC_INST_ID_
        ${ew.customSqlSegment}
        ORDER BY a.update_time DESC
    </select>

    <select id="getUserNameByUserId" resultType="java.lang.String">
        SELECT name
        FROM sys_user
        WHERE id = #{handledBy}
    </select>

    <select id="getOfficeNameByOfficeId" resultType="java.lang.String">
        SELECT name
        FROM sys_office
        WHERE id = #{handledByOffice}
    </select>

    <select id="statistics" resultType="java.math.BigDecimal">
        SELECT IFNULL(SUM(a.total_price), 0)
        FROM psi_management_food_purchase_basic a
        ${ew.customSqlSegment}
    </select>
</mapper>
