<?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.deliver.mapper.SaDeliverMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.hzs.common.domain.sale.deliver.SaDeliver">
        <id column="PK_ID" property="pkId"/>
        <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="PK_COUNTRY" property="pkCountry"/>
        <result column="DELIVER_CODE" property="deliverCode"/>
        <result column="LOGISTICS_CODE" property="logisticsCode"/>
        <result column="LOGISTICS_COMPANY" property="logisticsCompany"/>
        <result column="REC_NAME" property="recName"/>
        <result column="REC_PHONE" property="recPhone"/>
        <result column="REC_PROVINCE" property="recProvince"/>
        <result column="REC_CITY" property="recCity"/>
        <result column="REC_COUNTY" property="recCounty"/>
        <result column="DELIVER_STATUS" property="deliverStatus"/>
        <result column="DELIVER_TIME" property="deliverTime"/>
        <result column="PRINT_STATUS" property="printStatus"/>
        <result column="PRINT_TIME" property="printTime"/>
        <result column="REC_ADDRESS" property="recAddress"/>
        <result column="TRAN_TYPE" property="tranType"/>
        <result column="DAY_BATCH" property="dayBatch"/>
        <result column="BATCH_NUMBER" property="batchNumber"/>
    </resultMap>

    <!-- 出货单打印结果映射 -->
    <resultMap id="deliverPrintMap" type="com.hzs.sale.deliver.vo.DeliverPrintVO">
        <result column="DELIVER_CODE" property="deliverCode"/>
        <result column="PRINT_TIME" property="printTime"/>
        <result column="REC_NAME" property="recName"/>
        <result column="REC_PHONE" property="recPhone"/>
        <result column="REC_PROVINCE" property="recProvince"/>
        <result column="REC_CITY" property="recCity"/>
        <result column="REC_COUNTY" property="recCounty"/>
        <result column="REC_ADDRESS" property="recAddress"/>
        <collection property="itemList" ofType="com.hzs.sale.deliver.vo.DeliverPrintItemVO">
            <result column="PRODUCT_NAME" property="productName"/>
            <result column="SPECS_NAME" property="specsName"/>
            <result column="QUANTITY" property="quantity"/>
            <result column="PRICE" property="price"/>
            <result column="ORDER_CODE" property="orderCode"/>
            <result column="ORDER_TYPE" property="orderType"/>
            <result column="UNIT_TRANSACTION" property="unitTransaction"/>
            <result column="HOUSE_NAME" property="houseName"/>
        </collection>
    </resultMap>

    <!-- 发货单 + 发货单明细 -->
    <resultMap id="deliverExtMap" type="com.hzs.common.domain.sale.ext.SaDeliverExt" extends="BaseResultMap">
        <collection property="saDeliverItemsExtList" ofType="com.hzs.common.domain.sale.ext.SaDeliverItemsExt">
            <result column="ITEMS_ID" property="pkId"/>
            <result column="PK_ORDER" property="pkOrder"/>
            <result column="PK_ORDER_ITEMS" property="pkOrderItems"/>
            <result column="PK_PRODUCT" property="pkProduct"/>
            <result column="QUANTITY" property="quantity"/>
            <result column="PK_WARES_SPECS_SKU" property="pkWaresSpecsSku"/>
            <result column="PK_WARES_DETAIL" property="pkWaresDetail"/>
            <result column="EXCHANGE_GOODS" property="exchangeGoods"/>
            <result column="SPECS_NAME" property="specsName"/>
            <result column="SPECS_NAME_ID" property="specsNameId"/>
        </collection>
    </resultMap>

    <!-- 出货单打印列表 -->
    <select id="deliverPrintList" resultMap="deliverPrintMap">
        select sd.deliver_code,
        sd.print_time,
        sd.rec_name,
        sd.rec_phone,
        sd.rec_province,
        sd.rec_city,
        sd.rec_county,
        sd.rec_address,
        sdi.order_code,
        sdi.order_type,
        sdi.product_name,
        sdi.specs_name,
        sdi.quantity,
        sdi.price,
        sdi.unit_transaction,
        sdi.house_name
        from SA_DELIVER sd
        left join (
        select sdi.pk_deliver,
        bp.product_name,
        sdi.specs_name,
        max(so.order_code) order_code,
        max(so.order_type) order_type,
        sum(sdi.quantity) quantity,
        sum(sdi.quantity * soi.price) price,
        sum(bu.pk_transaction) unit_transaction,
        max(bs.name) house_name
        from SA_DELIVER_ITEMS sdi
        inner join SA_ORDER_ITEMS soi
        on soi.pk_id = sdi.pk_order_items
        inner join SA_ORDER so
        on so.pk_id = sdi.pk_order
        inner join BD_PRODUCT bp
        on bp.pk_id = sdi.pk_product
        left join BD_UNIT bu
        on bu.pk_id = bp.unit
        left join bd_storehouse bs
        on bs.PK_ID = so.pk_storehouse
        where sdi.del_flag = 0
        and sdi.pk_country = #{pkCountry}
        and sdi.pk_deliver in
        <foreach collection="idList" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
        group by sdi.pk_deliver, bp.product_name, sdi.specs_name
        ) 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="idList" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
        order by sd.deliver_code desc, sdi.order_code desc
    </select>

    <!-- 新发货单打印 -->
    <select id="deliverPrintNew" resultType="com.hzs.sale.deliver.vo.DeliverPrintNewVO">
        select sd.deliver_code,
        bs.name house_name,
        so.pay_time,
        sd.rec_name,
        sd.rec_phone,
        sd.print_time,
        sd.rec_province,
        sd.rec_city,
        sd.rec_county,
        sd.rec_address,
        sd.day_batch,
        sd.batch_number,
        cm.member_code,
        cm.member_name,
        so.order_code,
        bp.product_code,
        bp.product_name,
        sdi.specs_name,
        bu.pk_transaction unitTransaction,
        sdi.quantity,
        (sdi.quantity * soi.price) price
        from sa_deliver sd
        left join sa_deliver_items sdi
        on sdi.pk_deliver = sd.pk_id
        and sdi.del_flag = 0
        left join sa_order so
        on so.pk_id = sdi.pk_order
        and so.del_flag = 0
        left join bd_storehouse bs
        on bs.pk_id = so.pk_storehouse
        left join cu_member cm
        on cm.pk_id = so.pk_member
        left join sa_order_items soi
        on soi.pk_id = sdi.pk_order_items
        and soi.del_flag = 0
        left join bd_product bp
        on sdi.pk_product = bp.pk_id
        left join bd_unit bu
        on bu.pk_id = bp.unit
        where sd.del_flag = 0
        and sd.pk_country = #{pkCountry}
        and (sd.pk_id in
        <foreach collection="idList" item="item" index="index" open="(" close=")">
            <if test="index != 0">
                <choose>
                    <when test="index % 500 == 0">) or sd.pk_id IN (</when>
                    <otherwise>,</otherwise>
                </choose>
            </if>
            #{item}
        </foreach>
        )
        order by sd.deliver_code, cm.member_code, so.order_code, bp.product_code
    </select>

    <!-- 根据发货单明细数量删除发货单 -->
    <update id="deleteDeliverByItemsCount">
        update SA_DELIVER sd
        set sd.del_flag      = 1,
            sd.PK_MODIFIED   = #{userId},
            sd.MODIFIED_TIME = sysdate
        where sd.del_flag = 0
          and sd.pk_id = #{pkDeliver}
          and (select nvl(count(sdi.pk_deliver), 0)
               from SA_DELIVER_ITEMS sdi
               where sdi.del_flag = 0
                 and sdi.pk_country = #{pkCountry}
                 and sdi.pk_deliver = #{pkDeliver}) = 0
    </update>

    <!-- 立即发货列表 -->
    <select id="deliverList" resultType="com.hzs.sale.deliver.vo.DeliverVO">
        select sd.pk_id,
        sdi.pk_id deliver_items_id,
        sd.deliver_code,
        bp.cover,
        bp.product_code,
        bp.product_name,
        bp.shipping_channel,
        soi.specs_name,
        soi.quantity,
        so.order_code,
        so.order_type,
        cm.member_code,
        cm.member_name,
        cm.phone,
        so.rec_name,
        so.rec_phone,
        sd.rec_province,
        sd.rec_city,
        sd.rec_county,
        sd.rec_address,
        so.creation_time,
        so.pay_time,
        sd.print_time,
        sd.deliver_time,
        sd.deliver_status,
        sd.logistics_company,
        sd.logistics_code,
        so.delivery_way,
        bwe.operate_scope,
        so.tran_type,
        nvl2(so.pk_original_order, 0, 1) second_deliver,
        bs.name storehouseName,
        bu.name unit_name,
        so.SYSTEM_TYPE,
        bv.vertex_name
        from SA_DELIVER sd
        left join SA_DELIVER_ITEMS sdi
        on sdi.pk_deliver = sd.pk_id
        inner join SA_ORDER so
        on so.pk_id = sdi.pk_order
        and so.del_flag = 0
        inner join SA_ORDER_ITEMS soi
        on soi.pk_order = sdi.pk_order
        and soi.pk_id = sdi.pk_order_items
        inner join BD_PRODUCT bp
        on bp.pk_id = soi.pk_product
        left join BD_WARES_EXTEND bwe
        on bwe.pk_wares = soi.pk_wares
        left join bd_unit bu
        on bu.pk_id = bp.unit
        inner join cu_member cm
        on cm.pk_id = so.pk_member
        left join bd_storehouse bs
        on bs.pk_id = so.pk_storehouse
        left join bd_vertex bv
        on bv.pk_id = cm.pk_vertex
        where sd.del_flag = 0
        and sd.pk_country = #{pkCountry}
        and sdi.del_flag = 0
        <if test="param.systemAll == null or param.systemAll == 1">
            <if test="param.systemType != null">
                and so.SYSTEM_TYPE = #{param.systemType}
            </if>
        </if>
        <if test="param.pkIdList != null and param.pkIdList.size > 0">
            and (sd.pk_id in
            <foreach collection="param.pkIdList" item="item" index="index" open="(" close=")">
                <if test="index != 0">
                    <choose>
                        <when test="index % 500 == 0">) or sd.pk_id IN (</when>
                        <otherwise>,</otherwise>
                    </choose>
                </if>
                #{item}
            </foreach>
            )
        </if>
        <if test="param.pkDeliver != null">
            and sd.pk_id = #{param.pkDeliver}
        </if>
        <if test="param.pkStorehouse != null ">
            and bs.pk_id = #{param.pkStorehouse}
        </if>
        <if test="param.pkDeliverItems != null">
            and sdi.pk_id = #{param.pkDeliverItems}
        </if>
        <if test="param.shippingChannel != null">
            and bp.shipping_channel = #{param.shippingChannel}
        </if>
        <if test="param.deliverIdList != null and param.deliverIdList.size > 0">
            and sd.pk_id in
            <foreach collection="param.deliverIdList" item="item" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        <if test="param.printStatus != null ">
            and sd.print_status = #{param.printStatus}
        </if>
        <if test="param.deliverCode != null and param.deliverCode != ''">
            and sd.deliver_code like '%' || #{param.deliverCode} || '%'
        </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.deliveryStatus != null ">
            and sd.deliver_status = #{param.deliveryStatus}
        </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>
        <!-- 发货方式（快递、自提等） -->
        <if test="param.deliveryWay != null ">
            and so.delivery_way = #{param.deliveryWay}
        </if>
        <!-- 运输方式（陆、海、空） -->
        <if test="param.transportType != null">
            and so.tran_type = #{param.transportType}
        </if>
        <!-- 供应方式（自营、非自营） -->
        <if test="param.operateScope != null ">
            and bwe.operate_scope = #{param.operateScope}
        </if>
        <if test="param.logisticsCompany != null and param.logisticsCompany != ''">
            and sd.logistics_company like #{param.logisticsCompany} || '%'
        </if>
        <if test="param.logisticsCode != null and param.logisticsCode != ''">
            and sd.logistics_code like '%' || #{param.logisticsCode} || '%'
        </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 soi.creation_time >= #{param.creationTime[0]}
            and #{param.creationTime[1]} >= soi.creation_time
        </if>
        <if test="param.payTime != null">
            and so.pay_time >= #{param.payTime[0]}
            and #{param.payTime[1]} >= so.pay_time
        </if>
        <if test="param.printTime != null">
            and sd.print_time >= #{param.printTime[0]}
            and #{param.printTime[1]} >= sd.print_time
        </if>
        <if test="param.deliverTime != null">
            and sd.deliver_time >= #{param.deliverTime[0]}
            and #{param.deliverTime[1]} >= sd.deliver_time
        </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 test="param.pkVertex != null">
            and cm.pk_vertex = #{param.pkVertex}
        </if>
        order by sd.creation_time desc, so.order_code desc
    </select>

    <!-- 批量发货 -->
    <update id="deliverBatch" parameterType="com.hzs.common.domain.sale.deliver.SaDeliver">
        MERGE INTO SA_DELIVER sd
        using (
        select PK_ID,
        LOGISTICS_COMPANY,
        DELIVER_STATUS,
        replace(wm_concat(LOGISTICS_CODE), ',', '/') LOGISTICS_CODE
        from (
        <foreach collection="deliverList" item="item" separator="union">
            select
            #{item.pkId} PK_ID,
            #{item.logisticsCode} LOGISTICS_CODE,
            #{item.logisticsCompany} LOGISTICS_COMPANY,
            #{item.deliverStatus} DELIVER_STATUS
            from dual
        </foreach>
        )
        group by PK_ID, LOGISTICS_COMPANY, LOGISTICS_CODE, DELIVER_STATUS
        ) tmp
        ON (tmp.PK_ID = sd.pk_id and sd.PK_COUNTRY = #{pkCountry})
        WHEN MATCHED THEN
        update
        set sd.logistics_code = tmp.LOGISTICS_CODE,
        sd.logistics_company = tmp.LOGISTICS_COMPANY,
        sd.DELIVER_STATUS = tmp.DELIVER_STATUS,
        sd.DELIVER_TIME = sysdate,
        sd.PK_MODIFIED = #{userId},
        sd.MODIFIED_TIME = sysdate
    </update>

    <!-- 根据订单明细查询发货单 -->
    <select id="queryDeliverByItems" resultMap="BaseResultMap">
        select sd.*
        from SA_DELIVER_ITEMS sdi
                 inner join SA_DELIVER sd
                            on sdi.pk_deliver = sd.pk_id
        where sdi.del_flag = 0
          and sd.del_flag = 0
          and sdi.pk_country = #{pkCountry}
          and sdi.pk_id = #{deliverItemsId}
    </select>

    <!-- 查询订单发货信息 -->
    <select id="queryDeliverByOrder" resultMap="BaseResultMap">
        select distinct sd.logistics_code,
                        sd.logistics_company,
                        sd.rec_phone,
                        sd.creation_time
        from SA_DELIVER_ITEMS sdi
                 inner join SA_DELIVER sd
                            on sd.pk_id = sdi.pk_deliver
        where sdi.del_flag = 0
          and sd.del_flag = 0
          and sdi.pk_order = #{pkOrder}
          and sd.deliver_status in (2, 3, 4)
        order by sd.creation_time
    </select>

    <!-- 查询指定数量序列ID -->
    <select id="querySeqList" resultType="long">
        SELECT SA_DELIVER_SEQ.nextval
        FROM (
                 select level
                 from dual connect by #{param} >= level
             )
    </select>

    <!-- 批量插入 -->
    <insert id="insertBatch">
        MERGE INTO SA_DELIVER
        USING (
        <foreach collection="list" item="item" separator=" union ">
            select
            #{item.pkId} pkId,
            #{item.deliverCode} deliverCode,
            #{item.recName, jdbcType=VARCHAR} recName,
            #{item.recPhone, jdbcType=VARCHAR} recPhone,
            #{item.recProvince,jdbcType=NUMERIC} recProvince,
            #{item.recCity,jdbcType=NUMERIC} recCity,
            #{item.recCounty,jdbcType=NUMERIC} recCounty,
            #{item.recAddress, jdbcType=VARCHAR} recAddress,
            #{item.tranType,jdbcType=NUMERIC} tranType,
            #{item.pkCountry} pkCountry,
            #{item.pkCreator} pkCreator,
            #{item.creationTime} creationTime,
            #{item.pkModified} pkModified,
            #{item.modifiedTime} modifiedTime,
            #{item.dayBatch} dayBatch,
            #{item.batchNumber} batchNumber
            from dual
        </foreach>
        ) tmp
        ON (0 = 1)
        WHEN NOT MATCHED THEN
        insert (PK_ID,
        DELIVER_CODE,
        REC_NAME,
        REC_PHONE,
        REC_PROVINCE,
        REC_CITY,
        REC_COUNTY,
        REC_ADDRESS,
        TRAN_TYPE,
        PK_COUNTRY,
        PK_CREATOR,
        CREATION_TIME,
        PK_MODIFIED,
        MODIFIED_TIME,
        DAY_BATCH,
        BATCH_NUMBER)
        values (
        tmp.pkId,
        tmp.deliverCode,
        tmp.recName,
        tmp.recPhone,
        tmp.recProvince,
        tmp.recCity,
        tmp.recCounty,
        tmp.recAddress,
        tmp.tranType,
        tmp.pkCountry,
        tmp.pkCreator,
        tmp.creationTime,
        tmp.pkModified,
        tmp.modifiedTime,
        tmp.dayBatch,
        tmp.batchNumber)
    </insert>

    <!-- 根据ID查询发货单 -->
    <select id="queryListById" resultMap="BaseResultMap">
        select sd.*
        from sa_deliver sd
        where sd.pk_country = #{pkCountry}
        and (sd.pk_id in
        <foreach collection="idList" item="item" index="index" open="(" close=")">
            <if test="index != 0">
                <choose>
                    <when test="index % 500 == 0">) or sd.pk_id IN (</when>
                    <otherwise>,</otherwise>
                </choose>
            </if>
            #{item}
        </foreach>
        )
        order by sd.pk_id desc
    </select>

    <!-- 查询发货单+明细列表 -->
    <select id="queryDeliverAndItemsList" resultMap="deliverExtMap">
        select sd.*,
        sdi.pk_id ITEMS_ID,
        sdi.pk_order,
        sdi.pk_order_items,
        sdi.pk_product,
        sdi.quantity,
        sdi.pk_wares_specs_sku,
        sdi.pk_wares_detail,
        sdi.exchange_Goods,
        sdi.specs_name,
        sdi.specs_name_id
        from sa_deliver sd
        left join sa_deliver_items sdi
        on sdi.pk_deliver = sd.pk_id
        and sdi.del_flag = 0
        where sd.del_flag = 0
        <if test="pkCountry != null">
            and sd.pk_country = #{pkCountry}
        </if>
        and (sd.pk_id in
        <foreach collection="idList" item="item" index="index" open="(" close=")">
            <if test="index != 0">
                <choose>
                    <when test="index % 500 == 0">) or sd.pk_id IN (</when>
                    <otherwise>,</otherwise>
                </choose>
            </if>
            #{item}
        </foreach>
        )
        order by sd.pk_id
    </select>

    <!-- 获取指定日期最大批次 -->
    <select id="getMaxBatch" resultType="integer">
        select nvl(max(sd.day_batch), 0) last_day_batch
        from sa_deliver sd
        where sd.del_flag = 0
    </select>

    <!-- 获取批量最大数量 -->
    <select id="getBatchMaxNumber" resultType="integer">
        select nvl(max(sd.batch_number), 0) batch_number
        from SA_DELIVER sd
        where sd.del_flag = 0
          and sd.DAY_BATCH = #{dayBatch}
    </select>

    <!-- 批量更新打印状态 -->
    <update id="updatePrintStatusBatch">
        update sa_deliver sd
        set sd.print_status = #{printStatus},
        sd.print_time = sysdate,
        sd.pk_modified = #{userId},
        sd.modified_time = sysdate
        where sd.pk_country = #{pkCountry}
        and (sd.pk_id in
        <foreach collection="idList" item="item" index="index" open="(" close=")">
            <if test="index != 0">
                <choose>
                    <when test="index % 500 == 0">) or sd.pk_id IN (</when>
                    <otherwise>,</otherwise>
                </choose>
            </if>
            #{item}
        </foreach>
        )
    </update>

    <!-- 批量查询发货单数据 -->
    <select id="listDataBatch" resultType="com.hzs.common.domain.sale.deliver.SaDeliver">
        select sd.pk_id, sd.deliver_code
        from sa_deliver sd
        where sd.del_flag = 0
        and (sd.pk_id in
        <foreach collection="idList" item="item" index="index" open="(" close=")">
            <if test="index != 0">
                <choose>
                    <when test="index % 500 == 0">) or sd.pk_id IN (</when>
                    <otherwise>,</otherwise>
                </choose>
            </if>
            #{item}
        </foreach>
        )
    </select>

</mapper>
