<?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.hzs.sale.order.mapper.SaOrderItemsMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="SaOrderItems" type="com.hzs.common.domain.sale.order.SaOrderItems">
        <id column="PK_ID" property="pkId"/>
        <result column="PK_ORDER" property="pkOrder"/>
        <result column="PK_PRODUCT" property="pkProduct"/>
        <result column="PK_WARES" property="pkWares"/>
        <result column="PK_WARES_DETAIL" property="pkWaresDetail"/>
        <result column="PK_WARES_SPECS_SKU" property="pkWaresSpecsSku"/>
        <result column="PRICE" property="price"/>
        <result column="PK_RATE" property="pkRate"/>
        <result column="ACHIEVEMENT" property="achievement"/>
        <result column="QUANTITY" property="quantity"/>
        <result column="WARES_QUANTITY" property="waresQuantity"/>
        <result column="PK_GRADE" property="pkGrade"/>
        <result column="PK_AWARDS" property="pkAwards"/>
        <result column="ORDER_STATUS" property="orderStatus"/>
        <result column="DEL_FLAG" property="delFlag"/>
        <result column="PK_CREATOR" property="pkCreator"/>
        <result column="CREATION_TIME" property="creationTime"/>
        <result column="PK_MODIFIED" property="pkModified"/>
        <result column="MODIFIED_TIME" property="modifiedTime"/>
        <result column="IS_GIFT" property="isGift"/>
        <result column="SPECS_NAME" property="specsName"/>
        <result column="EXCHANGE_GOODS" property="exchangeGoods"/>
        <result column="LOGISTICS_CODE" property="logisticsCode"/>
        <result column="LOGISTICS_COMPANY" property="logisticsCompany"/>
        <result column="IS_MAKER_GIFT" property="isMakerGift"/>
        <result column="PK_SPECIAL_CURRENCY" property="pkSpecialCurrency"/>
        <result column="SHIPPING_CHANNEL" property="shippingChannel"/>
        <result column="PK_SUPPLIER" property="pkSupplier"/>
        <result column="SKU_CODE" property="skuCode"/>
    </resultMap>

    <!-- 未合单列表 -->
    <select id="queryDeliverUnhandledList" resultType="com.hzs.sale.deliver.vo.DeliverUnhandledVO">
        <if test="param.pkIdList != null and param.pkIdList.size > 0">
            <foreach collection="param.pkIdList" item="item" index="index" separator=" UNION ALL ">
                <if test="index % 500 == 0">
                    select soi.pk_id,
                    soi.pk_order,
                    bp.cover,
                    bp.product_code,
                    bp.product_name,
                    soi.specs_name,
                    bc.pk_transaction_key classify,
                    soi.is_gift,
                    soi.quantity,
                    so.order_code,
                    cm.member_code,
                    cm.member_name,
                    cm.phone,
                    so.rec_name,
                    so.rec_phone,
                    so.rec_province,
                    so.rec_city,
                    so.rec_county,
                    so.rec_address,
                    so.delivery_way,
                    so.order_amount,
                    bwe.operate_scope,
                    bp.shipping_channel,
                    so.tran_type,
                    bwe.pre_sale_status,
                    so.order_type,
                    soi.order_status,
                    so.pay_type,
                    so.remark,
                    soi.creation_time,
                    so.pay_time,
                    bs.name storehouse_name,
                    bu.name unit_name
                    from SA_ORDER so
                    left join sa_order_items soi
                    on soi.pk_order = so.pk_id
                    inner join cu_member cm
                    on cm.pk_id = so.pk_member
                    inner join bd_product bp
                    on bp.pk_id = soi.pk_product
                    and bp.product_attr = 1
                    and so.pk_country = #{pkCountry}
                    left join bd_wares_extend bwe
                    on bwe.pk_wares = soi.pk_wares
                    left join BD_CLASSIFY bc
                    on bc.pk_id = bp.pk_classify
                    left join bd_unit bu
                    on bu.pk_id = bp.unit
                    left join bd_storehouse bs
                    on bs.pk_id = so.pk_storehouse
                    <include refid="deliverUnhandledQuery"/>
                    <if test="param.fhck != null and param.fhck != ''">
                        and bs.name like #{param.fhck} || '%'
                    </if>
                    <if test="param.pkStorehouse != null ">
                        and bs.pk_id = #{param.pkStorehouse}
                    </if>
                    and soi.pk_id in
                    <foreach collection="param.pkIdList" item="subItem" index="subItem_index" open="(" close=")" separator=",">
                        <if test="subItem_index gte index and subItem_index lt index + 500">
                            #{subItem}
                        </if>
                    </foreach>
                    <!-- 在售 -->
                    and (bwe.pre_sale_status = 0
                    <if test="param.pkWaresList != null and param.pkWaresList.size > 0">
                        or soi.pk_wares in
                        <foreach collection="param.pkWaresList" item="item" separator="," open="(" close=")">
                            #{item}
                        </foreach>
                    </if>
                    )
                    <!-- 地区权限处理 -->
                    <if test="param.areaScopeList != null and param.areaScopeList.size > 0">
                        and so.rec_province in
                        <foreach collection="param.areaScopeList" item="item" open="(" close=")" separator=",">
                            #{item}
                        </foreach>
                    </if>
                    <!-- 体系权限处理 -->
                    <if test="param.vertexIdList != null and param.vertexIdList.size > 0">
                        and cm.pk_vertex in
                        <foreach collection="param.vertexIdList" item="item" open="(" close=")" separator=",">
                            #{item}
                        </foreach>
                    </if>
                </if>
            </foreach>
            order by creation_time desc, order_code desc
        </if>

        <if test="param.pkIdList == null or param.pkIdList.size == 0">
            select soi.pk_id,
            soi.pk_order,
            bp.cover,
            bp.product_code,
            bp.product_name,
            soi.specs_name,
            bc.pk_transaction_key classify,
            soi.is_gift,
            soi.quantity,
            so.order_code,
            cm.member_code,
            cm.member_name,
            cm.phone,
            so.rec_name,
            so.rec_phone,
            so.rec_province,
            so.rec_city,
            so.rec_county,
            so.rec_address,
            so.delivery_way,
            so.order_amount,
            bwe.operate_scope,
            bp.shipping_channel,
            so.tran_type,
            bwe.pre_sale_status,
            so.order_type,
            soi.order_status,
            so.pay_type,
            so.remark,
            soi.creation_time,
            so.pay_time,
            bs.name storehouse_name,
            bu.name unit_name,
            so.SYSTEM_TYPE
            from SA_ORDER so
            left join sa_order_items soi
            on soi.pk_order = so.pk_id
            inner join cu_member cm
            on cm.pk_id = so.pk_member
            inner join bd_product bp
            on bp.pk_id = soi.pk_product
            and bp.product_attr = 1
            and so.pk_country = #{pkCountry}
            left join bd_wares_extend bwe
            on bwe.pk_wares = soi.pk_wares
            left join BD_CLASSIFY bc
            on bc.pk_id = bp.pk_classify
            left join bd_unit bu
            on bu.pk_id = bp.unit
            left join bd_storehouse bs
            on bs.pk_id = so.pk_storehouse
            <include refid="deliverUnhandledQuery"/>
            <if test="param.systemType != null">
                and so.SYSTEM_TYPE = #{param.systemType}
            </if>
            <if test="param.fhck != null and param.fhck != ''">
                and bs.name like #{param.fhck} || '%'
            </if>
            <if test="param.pkStorehouse != null ">
                and bs.pk_id = #{param.pkStorehouse}
            </if>
            <if test="param.pkIdList != null and param.pkIdList.size > 0">
                and soi.pk_id in
                <foreach collection="param.pkIdList" item="item" open="(" close=")" separator=",">
                    #{item}
                </foreach>
            </if>
            <!-- 在售 -->
            and (bwe.pre_sale_status = 0
            <if test="param.pkWaresList != null and param.pkWaresList.size > 0">
                or soi.pk_wares in
                <foreach collection="param.pkWaresList" item="item" separator="," open="(" close=")">
                    #{item}
                </foreach>
            </if>
            )
            <!-- 地区权限处理 -->
            <if test="param.areaScopeList != null and param.areaScopeList.size > 0">
                and so.rec_province in
                <foreach collection="param.areaScopeList" item="item" open="(" close=")" separator=",">
                    #{item}
                </foreach>
            </if>
            <!-- 体系权限处理 -->
            <if test="param.vertexIdList != null and param.vertexIdList.size > 0">
                and cm.pk_vertex in
                <foreach collection="param.vertexIdList" item="item" open="(" close=")" separator=",">
                    #{item}
                </foreach>
            </if>
            order by soi.creation_time desc, so.order_code desc
        </if>
    </select>

    <!-- 未合单查询条件 -->
    <sql id="deliverUnhandledQuery">
        where so.del_flag = 0
        and so.pk_country = #{pkCountry}
        and soi.del_flag = 0
        <!-- 2024.05.08 物流清单发货时，带有供应商的明细不显示 -->
        and soi.pk_supplier is null
        <if test="param.orderStatusList != null">
            and soi.order_status in
            <foreach collection="param.orderStatusList" item="item" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        <if test="param.orderCode != null and param.orderCode != ''">
            and so.order_code like '%' || #{param.orderCode} || '%'
        </if>
        <if test="param.memberCode != null and param.memberCode != ''">
            and cm.member_code like #{param.memberCode} || '%'
        </if>
        <if test="param.memberName != null and param.memberName != ''">
            and cm.member_name like #{param.memberName} || '%'
        </if>
        <if test="param.phone != null and param.phone != ''">
            and cm.phone like #{param.phone} || '%'
        </if>
        <if test="param.orderType != null ">
            and so.order_type = #{param.orderType}
        </if>
        <if test="param.orderStatus != null ">
            and soi.order_status = #{param.orderStatus}
        </if>
        <!-- 预售状态 -->
        <if test="param.preSaleStatus != null ">
            and bwe.pre_sale_status = #{param.preSaleStatus}
        </if>
        <!-- 发货方式（快递、自提等） -->
        <choose>
            <when test="param.deliveryWayList != null and param.deliveryWayList.size > 0">
                and so.delivery_way in
                <foreach collection="param.deliveryWayList" item="item" open="(" close=")" separator=",">
                    #{item}
                </foreach>
            </when>
            <otherwise>
                <if test="param.deliveryWay != null ">
                    and so.delivery_way = #{param.deliveryWay}
                </if>
            </otherwise>
        </choose>
        <!-- 运输方式（陆、海、空） -->
        <choose>
            <when test="param.transportTypeList != null and param.transportTypeList.size > 0">
                and so.tran_type in
                <foreach collection="param.transportTypeList" item="item" open="(" close=")" separator=",">
                    #{item}
                </foreach>
            </when>
            <otherwise>
                <if test="param.transportType != null">
                    and so.tran_type = #{param.transportType}
                </if>
            </otherwise>
        </choose>
        <if test="param.payType != null ">
            and so.pay_type = #{param.payType}
        </if>
        <!-- 供应方式（自营、非自营） -->
        <if test="param.operateScope != null ">
            and bwe.operate_scope = #{param.operateScope}
        </if>
        <if test="param.recName != null and param.recName != '' ">
            and so.rec_name like '%' || #{param.recName} || '%'
        </if>
        <if test="param.recPhone != null and param.recPhone != '' ">
            and so.rec_phone like '%' || #{param.recPhone} || '%'
        </if>
        <if test="param.recProvince != null ">
            and so.rec_province = #{param.recProvince}
        </if>
        <if test="param.recCity != null ">
            and so.rec_city = #{param.recCity}
        </if>
        <if test="param.recCounty != null ">
            and so.rec_county = #{param.recCounty}
        </if>
        <if test="param.recAddress != null and param.recAddress != '' ">
            and so.rec_address like #{param.recAddress} || '%'
        </if>
        <if test="param.creationTime != null and param.creationTime.length > 1">
            and soi.creation_time >= #{param.creationTime[0]}
            and #{param.creationTime[1]} >= soi.creation_time
        </if>
        <if test="param.payTime != null and param.payTime.length > 1">
            and so.pay_time >= #{param.payTime[0]}
            and #{param.payTime[1]} >= so.pay_time
        </if>
        <if test="param.shippingChannel != null">
            and bp.shipping_channel = #{param.shippingChannel}
        </if>
        <if test="param.isGift != null">
            and soi.is_gift = #{param.isGift}
        </if>
        <if test="param.pkClassify != null">
            and bp.pk_classify = #{param.pkClassify}
        </if>
        <if test="param.productName != null and param.productName != ''">
            and bp.product_name like '%' || #{param.productName} || '%'
        </if>
        <if test="param.specsName != null and param.specsName != ''">
            and soi.specs_name like #{param.specsName} || '%'
        </if>
    </sql>

    <!-- 查询发货单排除产品（根据订单明细ID） -->
    <select id="queryExcludeProductByIdList" resultType="com.hzs.sale.deliver.vo.DeliverExcludeProductVO">
        select soi.*, bp.product_name, 0 product_stock
        from (select soi.PK_PRODUCT,
        max(soi.SPECS_NAME) SPECS_NAME,
        sum(soi.quantity) quantity
        from sa_order_items soi
        where soi.del_flag = 0
        and soi.order_status = 1
        and soi.pk_country = #{pkCountry}
        and
        (
        soi.pk_id in
        <foreach collection="idList" item="item" index="index" open="(" close=")">
            <if test="index != 0">
                <choose>
                    <when test="index % 500 == 0">) or soi.pk_id IN (</when>
                    <otherwise>,</otherwise>
                </choose>
            </if>
            #{item}
        </foreach>
        )
        group by soi.PK_PRODUCT, soi.PK_WARES_SPECS_SKU) soi
        inner join bd_product bp
        on bp.pk_id = soi.pk_product
        and bp.product_attr = 1
        order by product_name
    </select>

    <!-- 查询发货单排除产品（根据列表查询条件） -->
    <select id="queryExcludeProductByQueryParam" resultType="com.hzs.sale.deliver.vo.DeliverExcludeProductVO">
        select soi.*, bp.product_name, 0 product_stock
        from (select soi.PK_PRODUCT,
        max(soi.SPECS_NAME) SPECS_NAME,
        sum(soi.quantity) quantity
        from SA_ORDER so
        inner join SA_ORDER_ITEMS soi
        on so.pk_id = soi.pk_order
        inner join cu_member cm
        on cm.pk_id = so.pk_member
        and cm.del_flag = 0
        inner join BD_WARES_EXTEND bwe
        on bwe.pk_wares = soi.pk_wares
        <include refid="deliverUnhandledQuery"/>
        group by soi.PK_PRODUCT, soi.PK_WARES_SPECS_SKU) soi
        inner join bd_product bp
        on bp.pk_id = soi.pk_product
        order by product_name
    </select>

    <!-- 合单全部数据（根据查询条件） -->
    <select id="queryMergeByQueryParam" resultType="com.hzs.common.domain.sale.ext.SaOrderItemsExt">
        select so.pk_id pk_order,
        so.order_code,
        soi.pk_id,
        soi.pk_product,
        soi.pk_wares_specs_sku,
        soi.pk_wares_detail,
        soi.quantity,
        soi.specs_name,
        soi.specs_name_id,
        so.rec_name,
        so.rec_phone,
        so.rec_province,
        so.rec_city,
        so.rec_county,
        so.rec_address,
        so.tran_type
        from SA_ORDER so
        left join SA_ORDER_ITEMS soi
        on soi.pk_order = so.pk_id
        inner join cu_member cm
        on cm.pk_id = so.pk_member
        inner join bd_product bp
        on bp.pk_id = soi.pk_product
        and bp.product_attr = 1
        and so.pk_country = #{pkCountry}
        left join bd_wares_extend bwe
        on bwe.pk_wares = soi.pk_wares
        <include refid="deliverUnhandledQuery"/>
        <!-- 排除产品 -->
        <if test="param.excludeIdList != null and param.excludeIdList.size > 0">
            and soi.pk_product not in
            <foreach collection="param.excludeIdList" item="item" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        <!-- 在售 -->
        and (bwe.pre_sale_status = 0
        <if test="param.pkWaresList != null and param.pkWaresList.size > 0">
            or soi.pk_wares in
            <foreach collection="param.pkWaresList" item="item" separator="," open="(" close=")">
                #{item}
            </foreach>
        </if>
        )
        <!-- 地区权限处理 -->
        <if test="param.areaScopeList != null and param.areaScopeList.size > 0">
            and so.rec_province in
            <foreach collection="param.areaScopeList" item="item" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        <!-- 体系权限处理 -->
        <if test="param.vertexIdList != null and param.vertexIdList.size > 0">
            and so.pk_vertex in
            <foreach collection="param.vertexIdList" item="item" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        order by soi.creation_time desc, so.order_code desc
    </select>

    <!-- 合单数据（根据订单条件） -->
    <select id="queryMergeByIdList" resultType="com.hzs.common.domain.sale.ext.SaOrderItemsExt">
        select so.pk_id pk_order,
        so.order_code,
        soi.pk_id,
        soi.pk_product,
        soi.pk_wares_specs_sku,
        soi.pk_wares_detail,
        soi.quantity,
        soi.specs_name,
        soi.specs_name_id,
        so.rec_name,
        so.rec_phone,
        so.rec_province,
        so.rec_city,
        so.rec_county,
        so.rec_address,
        so.tran_type,
        bp.product_name
        from SA_ORDER so
        inner join SA_ORDER_ITEMS soi
        on soi.pk_order = so.pk_id
        inner join cu_member cm
        on cm.pk_id = so.pk_member
        inner join bd_product bp
        on bp.pk_id = soi.pk_product
        and bp.product_attr = 1
        and so.pk_country = #{pkCountry}
        left join bd_wares_extend bwe
        on bwe.pk_wares = soi.pk_wares
        where so.del_flag = 0
        and so.pk_country = #{pkCountry}
        and soi.del_flag = 0
        and soi.order_status = 1
        <!-- 指定订单 -->
        and
        (soi.pk_id in
        <foreach collection="idList" item="item" index="index" open="(" close=")">
            <if test="index != 0">
                <choose>
                    <when test="index % 500 == 0">) or soi.pk_id IN (</when>
                    <otherwise>,</otherwise>
                </choose>
            </if>
            #{item}
        </foreach>
        )
        <!-- 预售状态 -->
        <if test="param.preSaleStatus != null ">
            and bwe.pre_sale_status = #{param.preSaleStatus}
        </if>
        <!-- 发货方式（快递、自提等） -->
        <if test="param.deliveryWayList != null and param.deliveryWayList.size > 0">
            and so.delivery_way in
            <foreach collection="param.deliveryWayList" item="item" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        <!-- 运输方式（陆、海、空） -->
        <if test="param.transportTypeList != null and param.transportTypeList.size > 0">
            and so.tran_type in
            <foreach collection="param.transportTypeList" item="item" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        <!-- 供应方式（自营、非自营） -->
        <if test="param.operateScope != null ">
            and bwe.operate_scope = #{param.operateScope}
        </if>
        <!-- 排除产品 -->
        <if test="param.excludeIdList != null and param.excludeIdList.size > 0">
            and soi.pk_product not in
            <foreach collection="param.excludeIdList" item="item" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        <!-- 地区权限处理 -->
        <if test="param.areaScopeList != null and param.areaScopeList.size > 0">
            and so.rec_province in
            <foreach collection="param.areaScopeList" item="item" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        <!-- 体系权限处理 -->
        <if test="param.vertexIdList != null and param.vertexIdList.size > 0">
            and so.pk_vertex in
            <foreach collection="param.vertexIdList" item="item" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        order by soi.creation_time desc, so.order_code desc
    </select>

    <!-- 批量更新状态 -->
    <update id="updateStatusBatch">
        update SA_ORDER_ITEMS
        set ORDER_STATUS = #{orderStatus},
        PK_MODIFIED = #{userId},
        MODIFIED_TIME = sysdate
        where del_flag = 0
        and pk_country = #{pkCountry}
        and
        (pk_id in
        <foreach collection="idList" item="item" index="index" open="(" close=")">
            <if test="index != 0">
                <choose>
                    <when test="index % 500 == 0">) or pk_id IN (</when>
                    <otherwise>,</otherwise>
                </choose>
            </if>
            #{item}
        </foreach>
        )
    </update>

    <!-- 更新订单明细从已合单更新为已付款 -->
    <update id="updateToPayByPkOrder">
        update SA_ORDER_ITEMS
        set ORDER_STATUS = 1,
        PK_MODIFIED = #{userId},
        MODIFIED_TIME = sysdate
        where del_flag = 0
        and pk_country = #{pkCountry}
        and ORDER_STATUS = 2
        and pk_order in
        <foreach collection="pkOrderList" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
    </update>

    <!-- 根据发货单更新状态 -->
    <update id="updateStatusByDeliverList">
        MERGE INTO SA_ORDER_ITEMS soi
        using (
        select
        sdi.pk_order_items,
        sd.logistics_code,
        sd.logistics_company
        from sa_deliver sd
        left join sa_deliver_items sdi
        on sdi.pk_deliver = sd.pk_id
        where sd.del_flag = 0
        and sd.pk_country = #{pkCountry}
        and sd.pk_id in
        <foreach collection="deliverIdList" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
        and sdi.del_flag = 0
        ) tmp
        ON (tmp.pk_order_items = soi.pk_id)
        WHEN MATCHED THEN
        update
        set soi.logistics_code = tmp.LOGISTICS_CODE,
        soi.logistics_company = tmp.LOGISTICS_COMPANY,
        soi.ORDER_STATUS = #{orderStatus},
        soi.PK_MODIFIED = #{userId},
        soi.MODIFIED_TIME = sysdate
    </update>

    <update id="updateOrderItems">
        update SA_ORDER_ITEMS
        set del_flag     = 1,
            pk_modified=#{pkModified},
            modified_time=#{modifiedTime}
        where pk_country = #{pkCountry}
          and pk_order = #{pkId}
          and del_flag = 0
    </update>

    <!-- 根据订单ID查询订单明细列表（前台使用，尽量只查能用到的） -->
    <select id="queryListByOrderId" resultType="com.hzs.common.domain.sale.ext.SaOrderItemsExt">
        select
        soi.pk_id pkId,
        soi.PK_WARES_SPECS_SKU,
        soi.pk_order,
        bp.cover,
        bp.product_name,
        soi.specs_name,
        soi.price,
        soi.achievement,
        soi.ass_achievement,
        soi.quantity,
        soi.is_gift,
        soi.order_status,
        soi.PK_WARES pkWares,
        soi.creation_time,
        bw.wares_code
        from sa_order_items soi
        inner join bd_product bp
        on bp.pk_id = soi.pk_product
        left join bd_wares bw
        on bw.pk_id = soi.pk_wares
        where soi.del_flag = 0
        and soi.pk_order in
        <foreach collection="orderIdList" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
        order by creation_time desc, order_status, is_gift desc
    </select>

    <!--    根据订单ID查询订单商品明细列表-->
    <select id="waresListByOrderId" resultType="com.hzs.sale.order.vo.WaresOrderVo">
        select COUNT(t.pk_order) quantity,
        t.pk_order as pkOrder,
        t.PK_WARES pkWares,
        t.COVER1 as cover1,
        t.WARES_NAME as waresName,
        t.WARES_CODE as waresCode
        from (
        select soi.PK_ID,
        soi.pk_order,
        soi.PK_WARES,
        bw.COVER1,
        bw.WARES_NAME,
        bw.WARES_CODE,
        soi.price,
        soi.is_gift
        from sa_order_items soi
        inner join BD_WARES bw
        on bw.pk_id = soi.PK_WARES
        where soi.del_flag = 0
        and soi.pk_order in
        <foreach collection="orderIdList" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
        ) t
        GROUP BY t.COVER1,t.pk_order,
        t.WARES_NAME,
        t.PK_WARES,
        t.WARES_CODE
    </select>

    <!-- 根据订单明细ID查询订单明细列表 -->
    <select id="queryListByItemId" resultType="com.hzs.common.domain.sale.ext.SaOrderItemsExt">
        select soi.*,
        bp.product_name,
        so.order_code,
        cm.member_code,
        cm.member_name,
        so.rec_name,
        so.rec_phone,
        so.rec_province,
        so.rec_city,
        so.rec_county,
        so.rec_address
        from sa_order_items soi
        inner join sa_order so
        on so.pk_id = soi.pk_order
        inner join cu_member cm
        on cm.pk_id = so.pk_member
        inner join bd_product bp
        on bp.pk_id = soi.pk_product
        where soi.del_flag = 0
        and soi.pk_id in
        <foreach collection="itemIdList" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
        <if test="pkCountry != null">
            and soi.pk_country = #{pkCountry}
        </if>
        <if test="statusList != null and statusList.size > 0">
            and soi.order_status in
            <foreach collection="statusList" item="item" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        order by so.creation_time desc, so.order_code desc
    </select>


    <select id="selectByInvestmentList" resultType="com.hzs.sale.order.vo.WaresOrderVo">
        select
        so.ORDER_CODE orderCode,
        so.ORDER_TYPE orderType,
        oi.QUANTITY quantity,
        cm.MEMBER_CODE memberCode,
        cm.MEMBER_NAME memberName,
        cm.PHONE phone,
        so.REC_NAME recName,
        so.REC_PHONE recPhone,
        so.REC_PROVINCE recProvince,
        so.REC_CITY recCity,
        so.REC_COUNTY recCountry,
        so.REC_ADDRESS recAddress,
        so.ORDER_AMOUNT orderAmount,
        so.POSTAGE postage,
        so.ORDER_ACHIEVE orderAchieve,
        so.DELIVERY_WAY deliveryWay,
        we.OPERATE_SCOPE operateScope,
        so.TRAN_TYPE tranType,
        we.PRE_SALE_STATUS preSaleStatus,
        oi.ORDER_STATUS orderStatus,
        so.PAY_TYPE payType,
        so.REMARK remark,
        so.CREATION_TIME creationTime,
        so.PAY_TIME payTime,
        bp.COVER cover1,
        bp.PRODUCT_NAME waresName,
        bp.PRODUCT_CODE waresCode,
        oi.SPECS_NAME specsName,
        bp.WEIGHT weight,
        bp.SHIPPING_CHANNEL shippingChannel,
        oi.LOGISTICS_CODE logisticsCode,
        oi.LOGISTICS_COMPANY logisticsCompany,
        m.MEMBER_CODE buyMemberCode,
        m.MEMBER_NAME buyMemberName,
        oi.PRICE productPrice,
        so.ORDER_ASS_ACHIEVE orderAssAchieve,
        bw.WARES_CODE commodityCode,
        bw.WARES_NAME commodityName,
        oi.WARES_QUANTITY waresQuantity,
        oi.SKU_CODE skuCode,
        oi.IS_MAKER_GIFT isMakerGift,
        ver.VERTEX_NAME vertexName
        from sa_order_items oi
        left join sa_order so on oi.PK_ORDER = so.PK_ID
        left join cu_member m on m.PK_ID = so.PK_CREATOR
        left join cu_member cm on cm.PK_ID = so.PK_MEMBER
        left join bd_vertex ver on ver.PK_ID = cm.PK_VERTEX and ver.del_flag = 0
        left join bd_wares_extend we on we.PK_WARES = oi.PK_WARES
        left join bd_wares bw on bw.PK_ID = we.PK_WARES
        left join bd_product bp on bp.PK_ID = oi.PK_PRODUCT
        where oi.del_flag = 0 and so.del_flag = 0
        <if test="addPurchaseFlag != null and addPurchaseFlag == 0">
            and oi.pk_order in (
                select distinct soi.pk_order
                from sa_order_items soi
                where soi.is_maker_gift = 3
                and soi.del_flag = 0
            )
        </if>
        <if test="buyMemberCode != null and buyMemberCode != ''">
            and m.MEMBER_CODE like #{buyMemberCode}||'%'
        </if>
        <if test="buyMemberName != null and buyMemberName != ''">
            and m.MEMBER_NAME like #{buyMemberName}||'%'
        </if>
        <if test="vertexId != null">
            and cm.PK_VERTEX = #{vertexId}
        </if>
        <if test="pkCountry != null">
            and so.PK_COUNTRY = #{pkCountry}
        </if>
        <if test="commodityCode != null and commodityCode != ''">
            and bw.WARES_CODE like #{commodityCode} || '%'
        </if>
        <if test="commodityName != null and commodityName != ''">
            and bw.WARES_NAME like #{commodityName} || '%'
        </if>
        <if test="logisticsCode != null and logisticsCode != ''">
            and oi.LOGISTICS_CODE like #{logisticsCode} || '%'
        </if>
        <if test="waresName != null and waresName != ''">
            and bp.PRODUCT_NAME like '%' || #{waresName} || '%'
        </if>
        <if test="waresCode != null and waresCode != ''">
            and bp.PRODUCT_CODE like #{waresCode} || '%'
        </if>
        <if test="orderCode != null and orderCode != ''">
            and so.ORDER_CODE like '%' || #{orderCode} || '%'
        </if>
        <if test="memberCode != null and memberCode != ''">
            and cm.MEMBER_CODE like #{memberCode} || '%'
        </if>
        <if test="memberName != null and memberName != ''">
            and cm.MEMBER_NAME like #{memberName} || '%'
        </if>
        <if test="phone != null and phone != ''">
            and cm.PHONE like #{phone} || '%'
        </if>
        <if test="orderType != null">
            and so.ORDER_TYPE = #{orderType}
        </if>
        <if test="shippingChannel != null">
            and bp.SHIPPING_CHANNEL = #{shippingChannel}
        </if>
        <if test="orderStatus != null">
            and so.ORDER_STATUS = #{orderStatus}
        </if>
        <if test="preSaleStatus != null">
            and we.PRE_SALE_STATUS = #{preSaleStatus}
        </if>
        <if test="deliveryWay != null and deliveryWay != ''">
            and so.DELIVERY_WAY = #{deliveryWay}
        </if>
        <if test="tranType != null">
            and so.TRAN_TYPE = #{tranType}
        </if>
        <if test="payType != null">
            and so.PAY_TYPE = #{payType}
        </if>
        <if test="operateScope != null">
            and we.OPERATE_SCOPE = #{operateScope}
        </if>
        <if test="recName != null and recName != ''">
            and so.REC_NAME like '%' || #{recName} || '%'
        </if>
        <if test="recPhone != null and recPhone != ''">
            and so.REC_PHONE like '%' || #{recPhone} || '%'
        </if>
        <if test="recProvince != null">
            and so.REC_PROVINCE = #{recProvince}
        </if>
        <if test="recCity != null">
            and so.REC_CITY = #{recCity}
        </if>
        <if test="recCountry != null">
            and so.REC_COUNTY = #{recCountry}
        </if>
        <if test="recAddress != null and recAddress != ''">
            and so.REC_ADDRESS = #{recAddress}
        </if>
        <if test="skuCode != null and skuCode != ''">
            and oi.SKU_CODE like #{skuCode} || '%'
        </if>
        <if test="startCreateDate != null">
            and
            to_char(oi.CREATION_TIME, 'yyyy-mm-dd hh24:mi:ss') &gt;= to_char(#{startCreateDate}, 'yyyy-mm-dd hh24:mi:ss')
        </if>
        <if test="endCreateDate != null">
            and
            to_char(oi.CREATION_TIME, 'yyyy-mm-dd hh24:mi:ss') &lt;= to_char(#{endCreateDate}, 'yyyy-mm-dd hh24:mi:ss')
        </if>
        <if test="startPayDate != null">
            and
            to_char(so.PAY_TIME, 'yyyy-mm-dd hh24:mi:ss') &gt;= to_char(#{startPayDate}, 'yyyy-mm-dd hh24:mi:ss')
        </if>
        <if test="endPayDate != null">
            and
            to_char(so.PAY_TIME, 'yyyy-mm-dd hh24:mi:ss') &lt;= to_char(#{endPayDate}, 'yyyy-mm-dd hh24:mi:ss')
        </if>
        order by so.CREATION_TIME desc
    </select>

    <!-- 定时关闭订单 -->
    <update id="closeOrder">
        update SA_ORDER_ITEMS
        set DEL_FLAG      = 1,
            MODIFIED_TIME = SYSDATE
        where (sysdate - interval '${data}' hour) > CREATION_TIME
          and ORDER_STATUS = 0
          and DEL_FLAG = 0
          and PK_COUNTRY = #{pkCountry}
          and pk_order in (select pk_id
                           from sa_order
                           where (sysdate - interval '${data}' hour) > CREATION_TIME
                             and ORDER_STATUS = 0
                             and DEL_FLAG = 0
                             and PK_COUNTRY = #{pkCountry}
                             and ORDER_TYPE = #{orderType})
    </update>

    <update id="updateOrderItemsByMemberList">
        update SA_ORDER_ITEMS
        set DEL_FLAG = 1,
        PK_MODIFIED = #{pkApprove},
        MODIFIED_TIME = #{currentDateTime}
        where del_flag= 0 and pk_order in (
        select pk_id from SA_ORDER
        where del_flag= 0 and order_type in (1,4,7,20,21,24) and pk_member in
        <foreach collection="memberList" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
        )
    </update>

    <select id="selectByList" resultType="com.hzs.common.domain.sale.ext.SaOrderItemsExt">
        select oi.*,
               bp.PRODUCT_NAME      productName,
               oi.SPECS_NAME        specsName,
               oi.QUANTITY          quantity,
               oi.PRICE             price,
               sd.LOGISTICS_CODE    logisticsCode,
               sd.LOGISTICS_COMPANY logisticsCompany,
               sd.DELIVER_TIME      deliverTime,
               bw.PRE_SALE_STATUS   preSaleStatus,
               bw.OPERATE_SCOPE     operateScope
        from sa_order_items oi
                 left join BD_PRODUCT bp on bp.PK_ID = oi.PK_PRODUCT
                 left join SA_DELIVER_ITEMS di on di.PK_ORDER_ITEMS = oi.PK_ID
                 left join SA_DELIVER sd on sd.PK_ID = di.PK_DELIVER
                 left join BD_WARES_EXTEND bw on bw.PK_WARES = oi.PK_WARES
        where oi.PK_ORDER = #{pkOrder}
    </select>

    <!-- 根据订单ID查询商品和产品信息-->
    <select id="getOrderItemsParams" resultType="com.hzs.sale.order.param.OrderItemsParam">
        select DISTINCT
        soi.pk_order pkOrder,
        soi.QUANTITY quantity,
        bw.wares_code waresCode
        from sa_order_items soi
        inner join bd_wares bw
        on soi.pk_wares = bw.pk_id
        where soi.del_flag = 0
        and soi.pk_order in
        <foreach collection="orderIdList" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
    </select>

    <!-- 查询订单发货信息 -->
    <select id="queryDeliverByOrder" resultMap="SaOrderItems">
        select distinct soi.logistics_code, soi.logistics_company
        from sa_order_items soi
        where soi.del_flag = 0
          and soi.pk_order = #{pkOrder}
    </select>

    <!-- 批量插入订单明细数据 -->
    <insert id="insertBach">
        INSERT ALL
        <foreach collection="orderItemsList" item="item" separator=" ">
            into SA_ORDER_ITEMS (
            PK_ORDER, PK_PRODUCT, QUANTITY, PK_RATE,
            PK_GRADE, PK_AWARDS, ORDER_STATUS,
            SPECS_NAME, SPECS_NAME_ID, WARES_QUANTITY,
            PK_CREATOR, CREATION_TIME, PK_COUNTRY
            )
            values (
            #{item.pkOrder}, #{item.pkProduct}, #{item.quantity}, #{item.pkRate, jdbcType=NUMERIC},
            #{item.pkGrade}, #{item.pkAwards}, #{item.orderStatus},
            #{item.specsName}, #{item.specsNameId}, #{item.waresQuantity},
            #{item.pkCreator}, #{item.creationTime}, #{item.pkCountry}
            )
        </foreach>
        SELECT 1 FROM dual
    </insert>

    <!-- 校验订单商品是否下架 -->
    <select id="checkOrderItemsPutOn" resultType="int">
        select count(1)
        from sa_order so
                 left join sa_order_items soi
                           on soi.pk_order = so.pk_id
                 inner join bd_wares_extend bwe
                            on bwe.pk_wares = soi.pk_wares
        where so.del_flag = 0
          and soi.del_flag = 0
          and so.order_code = #{orderCode}
          and bwe.is_put_on = 1
    </select>

    <!-- 抵扣订单明细插入 -->
    <insert id="copyDeductionItems">
        insert into sa_order_items
        (PK_ID, PK_ORDER,
         PK_PRODUCT, PK_WARES,
         PRICE, PK_RATE,
         ACHIEVEMENT, QUANTITY,
         PK_GRADE, PK_AWARDS,
         ORDER_STATUS, DEL_FLAG,
         CREATION_TIME, MODIFIED_TIME,
         PK_COUNTRY,
         PK_WARES_SPECS_SKU, PK_WARES_DETAIL,
         IS_GIFT,
         PK_CREATOR, PK_MODIFIED,
         SPECS_NAME, EXCHANGE_GOODS,
         ASS_ACHIEVEMENT, SPECS_NAME_ID,
         WARES_QUANTITY,
         LOGISTICS_CODE, LOGISTICS_COMPANY,
         IS_MAKER_GIFT, PK_SPECIAL_CURRENCY,
         SKU_CODE, SHIPPING_CHANNEL,
         PK_SUPPLIER)
        select SA_ORDER_ITEMS_SEQ.NEXTVAL, soi.*
        from (select #{pkOrderNew} PK_ORDER,
                     PK_PRODUCT,
                     PK_WARES,
                     PRICE,
                     PK_RATE,
                     ACHIEVEMENT,
                     QUANTITY,
                     PK_GRADE,
                     PK_AWARDS,
                     ORDER_STATUS,
                     0,
                     CREATION_TIME,
                     #{nowDate},
                     PK_COUNTRY,
                     PK_WARES_SPECS_SKU,
                     PK_WARES_DETAIL,
                     IS_GIFT,
                     PK_CREATOR,
                     #{userId},
                     SPECS_NAME,
                     EXCHANGE_GOODS,
                     ASS_ACHIEVEMENT,
                     SPECS_NAME_ID,
                     WARES_QUANTITY,
                     LOGISTICS_CODE,
                     LOGISTICS_COMPANY,
                     IS_MAKER_GIFT,
                     PK_SPECIAL_CURRENCY,
                     SKU_CODE,
                     SHIPPING_CHANNEL,
                     PK_SUPPLIER
              from sa_order_items soi
              where soi.del_flag = 1
                and soi.pk_order = #{pkOrderOld}
                and soi.modified_time =
                    (select max(soi.modified_time)
                     from sa_order_items soi
                     where soi.del_flag = 1
                       and soi.pk_order = #{pkOrderOld})
             ) soi
    </insert>

    <select id="selectByWaresCodeList" resultType="com.hzs.sale.order.param.OrderItemsParam">
        select soi.QUANTITY quantity, so.PK_ID pkId, bw.WARES_CODE waresCode
        from sa_order_items soi
                 inner join sa_order so on so.PK_ID = soi.PK_ORDER
                 left join bd_wares bw on bw.pk_id = soi.PK_WARES
        where soi.DEL_FLAG = 0
          and so.DEL_FLAG = 0
          and bw.del_flag = 0
          and so.ORDER_CODE = #{orderCode}
    </select>

</mapper>
