<?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.dk.mdm.mapper.sale.OrderMapper">

    <!-- 通用设置 -->
    <!-- 通用查询列 -->
    <sql id="Base_Column_List">
        order_id, order_no, order_type, org_id, staff_id, cus_id, address_area, address_name, address_no, address_gcj02, address_full, contact_name, contact_phone, sales_channel, delivery_date, sum_quantity, sum_standard, sum_amount, sale_discount, order_status, out_status, outing_qty, outing_amt, out_qty, out_amt, return_qty, return_amt, amt_receivable, amt_handle, amt_residue, remarks, annex_paths, make_staff, make_time, flg_valid, cp_id
    </sql>

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.dk.mdm.model.pojo.sale.Order">
        <id column="order_id" property="orderId"/>
            <result column="order_no" property="orderNo"/>
            <result column="order_type" property="orderType"/>
            <result column="org_id" property="orgId" typeHandler="UuidTypeHandler"/>
            <result column="staff_id" property="staffId" typeHandler="UuidTypeHandler"/>
            <result column="cus_id" property="cusId" typeHandler="UuidTypeHandler"/>
            <result column="address_area" property="addressArea" typeHandler="JsonTypeHandler"/>
            <result column="address_name" property="addressName"/>
            <result column="address_no" property="addressNo"/>
            <result column="address_gcj02" property="addressGcj02" typeHandler="JsonTypeHandler"/>
            <result column="address_full" property="addressFull"/>
            <result column="contact_name" property="contactName"/>
            <result column="contact_phone" property="contactPhone"/>
            <result column="sales_channel" property="salesChannel" typeHandler="UuidTypeHandler"/>
            <result column="delivery_date" property="deliveryDate" typeHandler="TimestampTypeHandler"/>
            <result column="sum_quantity" property="sumQuantity"/>
            <result column="sum_standard" property="sumStandard"/>
            <result column="sum_amount" property="sumAmount"/>
            <result column="sale_discount" property="saleDiscount"/>
            <result column="order_status" property="orderStatus"/>
            <result column="out_status" property="outStatus"/>
            <result column="outing_qty" property="outingQty"/>
            <result column="outing_amt" property="outingAmt"/>
            <result column="out_qty" property="outQty"/>
            <result column="out_amt" property="outAmt"/>
            <result column="return_qty" property="returnQty"/>
            <result column="return_amt" property="returnAmt"/>
            <result column="amt_receivable" property="amtReceivable"/>
            <result column="amt_handle" property="amtHandle"/>
            <result column="amt_residue" property="amtResidue"/>
            <result column="remarks" property="remarks"/>
            <result column="annex_paths" property="annexPaths" typeHandler="JsonTypeHandler"/>
            <result column="make_staff" property="makeStaff" typeHandler="UuidTypeHandler"/>
            <result column="make_time" property="makeTime" typeHandler="TimestampTypeHandler"/>
            <result column="flg_valid" property="flgValid"/>
            <result column="cp_id" property="cpId"/>
    </resultMap>

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMapResponse" type="com.dk.mdm.model.response.sale.OrderResponse">
        <id column="order_id" property="orderId"/>
            <result column="order_no" property="orderNo"/>
            <result column="order_type" property="orderType"/>
            <result column="org_id" property="orgId" typeHandler="UuidTypeHandler"/>
            <result column="staff_id" property="staffId" typeHandler="UuidTypeHandler"/>
            <result column="cus_id" property="cusId" typeHandler="UuidTypeHandler"/>
            <result column="address_area" property="addressArea" typeHandler="JsonTypeHandler"/>
            <result column="address_name" property="addressName"/>
            <result column="orgName" property="orgName"/>
            <result column="orderTypeName" property="orderTypeName"/>
            <result column="staffName" property="staffName"/>
            <result column="cusCode" property="cusCode"/>
            <result column="cusName" property="cusName"/>
            <result column="cusPhone" property="cusPhone"/>
            <result column="cusFrom" property="cusFrom"/>
            <result column="cusFromName" property="cusFromName"/>
            <result column="channelName" property="channelName"/>
            <result column="orderStatusName" property="orderStatusName"/>
            <result column="outStatusName" property="outStatusName"/>
            <result column="makeStaffName" property="makeStaffName"/>
            <result column="address_no" property="addressNo"/>
            <result column="address_gcj02" property="addressGcj02" typeHandler="JsonTypeHandler"/>
            <result column="address_full" property="addressFull"/>
            <result column="contact_name" property="contactName"/>
            <result column="contact_phone" property="contactPhone"/>
            <result column="sales_channel" property="salesChannel" typeHandler="UuidTypeHandler"/>
            <result column="delivery_date" property="deliveryDate" typeHandler="TimestampTypeHandler"/>
            <result column="sum_quantity" property="sumQuantity"/>
            <result column="sum_standard" property="sumStandard"/>
            <result column="sum_amount" property="sumAmount"/>
            <result column="sale_discount" property="saleDiscount"/>
            <result column="order_status" property="orderStatus"/>
            <result column="out_status" property="outStatus"/>
            <result column="outing_qty" property="outingQty"/>
            <result column="outing_amt" property="outingAmt"/>
            <result column="out_qty" property="outQty"/>
            <result column="out_amt" property="outAmt"/>
            <result column="return_qty" property="returnQty"/>
            <result column="return_amt" property="returnAmt"/>
            <result column="amt_receivable" property="amtReceivable"/>
            <result column="amt_handle" property="amtHandle"/>
            <result column="amt_residue" property="amtResidue"/>
            <result column="remarks" property="remarks"/>
            <result column="annex_paths" property="annexPaths" typeHandler="JsonTypeHandler"/>
            <result column="make_staff" property="makeStaff" typeHandler="UuidTypeHandler"/>
            <result column="make_time" property="makeTime" typeHandler="TimestampTypeHandler"/>
            <result column="flg_valid" property="flgValid"/>
            <result column="cp_id" property="cpId"/>
           <result column="orderItemResponseList" property="orderItemResponseList" typeHandler="JsonTypeHandler"/>
<!--            <collection property="orderItemResponseList" resultMap="orderItemListMap"  />-->
    </resultMap>
    <resultMap id="orderItemListMap" type="java.util.Map">
            <id column="itemId" property="itemId"/>
            <result column="orderId" property="orderId" typeHandler="UuidTypeHandler"/>
            <result column="itemIndex" property="itemIndex"/>
            <result column="orderNo" property="orderNo"/>
            <result column="skuId" property="skuId" typeHandler="UuidTypeHandler"/>
            <result column="itemQty" property="itemQty"/>
            <result column="priceStd" property="priceStd"/>
            <result column="amtStd" property="amtStd"/>
            <result column="priceStandard" property="priceStandard"/>
            <result column="priceSale" property="priceSale"/>
            <result column="itemAmt" property="itemAmt"/>
            <result column="priceDiscount" property="priceDiscount"/>
            <result column="nonStdCode" property="nonStdCode"/>
            <result column="outStatus" property="outStatus"/>
            <result column="outingQty" property="outingQty"/>
            <result column="outingAmt" property="outingAmt"/>
            <result column="outQty" property="outQty"/>
            <result column="outAmt" property="outAmt"/>
            <result column="skuCode" property="skuCode"/>
            <result column="skuName" property="skuName"/>
            <result column="skuModel" property="skuModel"/>
            <result column="returnQty" property="returnQty"/>
            <result column="returnAmt" property="returnAmt"/>
            <result column="remarks" property="remarks"/>
            <result column="flgValid" property="flgValid"/>
            <result column="cpId" property="cpId"/>
            <result column="pricePurchase" property="pricePurchase"/>
            <result column="brandName" property="brandName"/>
            <result column="shortName" property="shortName"/>
    </resultMap>


    <!--小程序用 查询销售订单带明细-->
    <resultMap id="BaseResultMapDetailResponse" type="com.dk.mdm.model.response.sale.OrderResponse">
            <id column="order_id" property="orderId"/>
            <result column="order_no" property="orderNo"/>
            <result column="order_type" property="orderType"/>
            <result column="org_id" property="orgId" typeHandler="UuidTypeHandler"/>
            <result column="staff_id" property="staffId" typeHandler="UuidTypeHandler"/>
            <result column="cus_id" property="cusId" typeHandler="UuidTypeHandler"/>
            <result column="address_area" property="addressArea" typeHandler="JsonTypeHandler"/>
            <result column="address_name" property="addressName"/>
            <result column="address_no" property="addressNo"/>
            <result column="address_gcj02" property="addressGcj02" typeHandler="JsonTypeHandler"/>
            <result column="address_full" property="addressFull"/>
            <result column="contact_name" property="contactName"/>
            <result column="contact_phone" property="contactPhone"/>
            <result column="sales_channel" property="salesChannel" typeHandler="UuidTypeHandler"/>
            <result column="delivery_date" property="deliveryDate" typeHandler="TimestampTypeHandler"/>
            <result column="sum_quantity" property="sumQuantity"/>
            <result column="sum_standard" property="sumStandard"/>
            <result column="sum_amount" property="sumAmount"/>
            <result column="sale_discount" property="saleDiscount"/>
            <result column="order_status" property="orderStatus"/>
            <result column="out_status" property="outStatus"/>
            <result column="outing_qty" property="outingQty"/>
            <result column="outing_amt" property="outingAmt"/>
            <result column="out_qty" property="outQty"/>
            <result column="out_amt" property="outAmt"/>
            <result column="return_qty" property="returnQty"/>
            <result column="return_amt" property="returnAmt"/>
            <result column="amt_receivable" property="amtReceivable"/>
            <result column="amt_handle" property="amtHandle"/>
            <result column="amt_residue" property="amtResidue"/>
            <result column="remarks" property="remarks"/>
            <result column="annex_paths" property="annexPaths" typeHandler="JsonTypeHandler"/>
            <result column="make_staff" property="makeStaff" typeHandler="UuidTypeHandler"/>
            <result column="make_time" property="makeTime" typeHandler="TimestampTypeHandler"/>
            <result column="flg_valid" property="flgValid"/>
            <result column="cp_id" property="cpId"/>
            <result column="org_name" property="orgName"/>
            <result column="staff_name" property="staffName"/>

            <collection property="orderItemResponseList" resultMap="itemListMap" columnPrefix="list_"/>
    </resultMap>
    <!--小程序用 关联映射-->
    <resultMap id="itemListMap" type="java.util.Map">
            <result column="item_id" property="itemId"/>
            <result column="order_id" property="orderId"/>
            <result column="order_no" property="orderNo"/>
            <result column="item_index" property="itemIndex"/>
            <result column="sku_id" property="skuId"/>
            <result column="item_qty" property="itemQty"/>
            <result column="price_std" property="priceStd"/>
            <result column="amt_std" property="amtStd"/>
            <result column="price_sale" property="priceSale"/>
            <result column="item_amt" property="itemAmt"/>
            <result column="price_discount" property="priceDiscount"/>
            <result column="non_std_code" property="nonStdCode"/>
            <result column="out_status" property="outStatus"/>
            <result column="outing_qty" property="outingQty"/>
            <result column="outing_amt" property="outingAmt"/>
            <result column="out_qty" property="outQty"/>
            <result column="out_amt" property="outAmt"/>
            <result column="return_qty" property="returnQty"/>
            <result column="return_amt" property="returnAmt"/>
            <result column="remarks" property="remarks"/>
            <result column="flg_valid" property="flgValid"/>
            <result column="cp_id" property="cpId"/>
            <result column="sku_code" property="skuCode"/>
            <result column="sku_model" property="skuModel"/>
            <result column="sku_name" property="skuName"/>
            <result column="brand_name" property="brandName"/>
            <result column="short_name" property="shortName"/>
            <result column="sku_images" property="skuImages"/>
            <result column="price_purchase" property="pricePurchase"/>
            <result column="price_standard" property="priceStandard"/>
            <result column="order_qty" property="orderQty"/>
            <result column="price_out" property="priceOut"/>
            <result column="inv_id" property="invId"/>
            <result column="wh_id" property="whId"/>
            <result column="inv_qty" property="invQty"/>
            <result column="usable_qty" property="usableQty"/>
            <result column="wh_name" property="whName"/>

    </resultMap>
    <!--小程序用 总单-->
    <sql id="Base_Column_List_Detail_Join">
        t
        .
        order_id
        ,
        t.order_no,
        t.order_type,
        t.org_id,
        t.staff_id,
        t.cus_id,
        t.address_area,
        t.address_name,
        t.address_no,
        t.address_gcj02,
        t.address_full,
        t.contact_name,
        t.contact_phone,
        t.sales_channel,
        t.delivery_date,
        t.sum_quantity,
        t.sum_standard,
        t.sum_amount, t.sale_discount,
        t.order_status, t.out_status,
        t.outing_qty, t.outing_amt, t.out_qty,
        t.out_amt, t.return_qty, t.return_amt,
        t.amt_receivable, amt_handle, amt_residue,
        t.remarks, t.annex_paths, t.make_staff, t.make_time,
        t.flg_valid, t.cp_id,
        tmo.org_name,
        tms.staff_name
    </sql>
    <!--小程序用 明细-->
    <sql id="Base_Column_List_Item_Response_Detail_Join">
        toi.item_id AS list_item_id,
        toi.order_id AS list_order_id,
        t.order_no AS list_order_no,
        toi.item_index AS list_item_index,
        toi.sku_id AS list_sku_id,
        toi.item_qty AS list_item_qty,
        toi.item_qty AS list_order_qty,
        toi.price_std AS list_price_std,
        toi.amt_std AS list_amt_std,
        toi.price_sale AS list_price_sale,
        toi.price_sale AS list_price_out,
        toi.item_amt AS list_item_amt,
        toi.price_discount AS list_price_discount,
        toi.non_std_code AS list_non_std_code,
        toi.out_status AS list_out_status,
        toi.outing_qty AS list_outing_qty,
        toi.outing_amt AS list_outing_amt,
        toi.out_qty AS list_out_qty,
        toi.out_amt AS list_out_amt,
        toi.return_qty AS list_return_qty,
        toi.return_amt AS list_return_amt,
        toi.remarks AS list_remarks,
        toi.flg_valid AS list_flg_valid,
        toi.cp_id AS list_cp_id,
        tmgs.sku_code AS list_sku_code,
        tmgs.sku_model AS list_sku_model,
        tmgs.sku_name AS list_sku_name,
        tmgb.brand_name AS list_brand_name,
        tmgb.short_name AS list_short_name,
        tmgs.sku_images AS list_sku_images,
        tmgs.price_purchase AS list_price_purchase,
        tmgs.price_standard AS list_price_standard,
        i.inv_id  as list_inv_id,
        i.wh_id as list_wh_id,
        i.inv_qty    as list_inv_qty,
        i.usable_qty  as list_usable_qty,
        i.wh_name     as list_wh_name
    </sql>


    <!-- 通用条件列 -->
    <sql id="Condition">
        <where>
            <if test="orderNo != null and orderNo != ''">
                AND t.order_no LIKE concat('%',my_ex.likequery(#{orderNo}),'%')
            </if>
            <if test="orderType != null and orderType != ''">
                AND t.order_type = #{orderType}
            </if>
            <if test="orgId != null and orgId != ''">
                AND t.org_id = #{orgId}
            </if>
            <if test="staffId != null and staffId != ''">
                AND t.staff_id = #{staffId}
            </if>
            <if test="cusId != null and cusId != ''">
                AND t.cus_id = #{cusId}::uuid
            </if>
            <if test="addressArea != null and addressArea != ''">
                AND t.address_area = #{addressArea}
            </if>
            <if test="addressName != null and addressName != ''">
                AND t.address_name = #{addressName}
            </if>
            <if test="addressNo != null and addressNo != ''">
                AND t.address_no = #{addressNo}
            </if>
            <if test="addressGcj02 != null and addressGcj02 != ''">
                AND t.address_gcj02 = #{addressGcj02}
            </if>
            <if test="addressFull != null and addressFull != ''">
                AND t.address_full LIKE concat('%',my_ex.likequery(#{addressFull}),'%')
            </if>
            <if test="contactName != null and contactName != ''">
                AND t.contact_name LIKE concat('%',my_ex.likequery(#{contactName}),'%')
            </if>
            <if test="contactPhone != null and contactPhone != ''">
                AND t.contact_phone LIKE concat('%',my_ex.likequery(#{contactPhone}),'%')
            </if>
            <if test="salesChannel != null and salesChannel != ''">
                AND t.sales_channel = #{salesChannel}
            </if>
            <if test="sumQuantity != null">
                AND t.sum_quantity = #{sumQuantity}
            </if>
            <if test="sumStandard != null">
                AND t.sum_standard = #{sumStandard}
            </if>
            <if test="sumAmount != null">
                AND t.sum_amount = #{sumAmount}
            </if>
            <if test="saleDiscount != null">
                AND t.sale_discount = #{saleDiscount}
            </if>
            <if test="orderStatus != null and orderStatus != ''">
                AND t.order_status = #{orderStatus}
            </if>
            <if test="outStatus != null and outStatus != ''">
                AND t.out_status = #{outStatus}
            </if>
            <if test="outingQty != null">
                AND t.outing_qty = #{outingQty}
            </if>
            <if test="outingAmt != null">
                AND t.outing_amt = #{outingAmt}
            </if>
            <if test="outQty != null">
                AND t.out_qty = #{outQty}
            </if>
            <if test="outAmt != null">
                AND t.out_amt = #{outAmt}
            </if>
            <if test="returnQty != null">
                AND t.return_qty = #{returnQty}
            </if>
            <if test="returnAmt != null">
                AND t.return_amt = #{returnAmt}
            </if>
            <if test="amtReceivable != null">
                AND t.amt_receivable = #{amtReceivable}
            </if>
            <if test="amtHandle != null">
                AND t.amt_handle = #{amtHandle}
            </if>
            <if test="amtResidue != null">
                AND t.amt_residue = #{amtResidue}
            </if>
            <if test="remarks != null and remarks != ''">
                AND t.remarks LIKE concat('%',my_ex.likequery(#{remarks}),'%')
            </if>
            <if test="annexPaths != null and annexPaths != ''">
                AND t.annex_paths = #{annexPaths}
            </if>
            <if test="makeStaff != null and makeStaff != ''">
                AND t.make_staff = #{makeStaff}
            </if>
            <if test="makeTime != null">
                AND t.make_time = #{makeTime}
            </if>
            <if test="cpId != null">
                AND t.cp_id = #{cpId}
            </if>
            <if test="cusPhone != null and cusPhone != ''">
                AND tmc.cus_phone LIKE concat('%',my_ex.likequery(#{cusPhone}),'%')
            </if>
            <if test="cusName != null and cusName != ''">
                AND tmc.cus_name LIKE concat('%',my_ex.likequery(#{cusName}),'%')
            </if>
            <if test="orgIdList != null and orgIdList.size() > 0">
                AND t.org_id  =any(#{orgIdList, typeHandler=uuidListTypeHandler})
            </if>
            <if test="staffIdList != null and staffIdList.size() > 0">
                AND t.staff_id  =any(#{staffIdList, typeHandler=uuidListTypeHandler})
            </if>
            <if test="outStatusList != null and outStatusList.size() > 0">
                AND t.out_status  =any(#{outStatusList, typeHandler=StringListTypeHandler})
            </if>
            <if test="deliveryDateStart != null and deliveryDateEnd != null">
                AND t.delivery_date &gt;= #{deliveryDateStart}::timestamp with time zone
                AND t.delivery_date &lt; #{deliveryDateEnd}::timestamp with time zone + interval '1 day'
            </if>
            <if test="makeTimeStart != null and makeTimeEnd != null">
                AND t.make_time &gt;= #{makeTimeStart}::timestamp with time zone
                AND t.make_time &lt; #{makeTimeEnd}::timestamp with time zone + interval '1 day'
            </if>
            <if test="flgValidList != null and flgValidList.size()>0">
                AND t.flg_valid =any(#{flgValidList, typeHandler=BooleanListTypeHandler})
            </if>
            <if test="staffIds != null and staffIds.size()>0">
                AND t.staff_id = any(#{staffIds, typeHandler=uuidListTypeHandler})
            </if>
            <if test="orgIds != null and orgIds.size()>0">
                AND t.org_id = any(#{orgIds, typeHandler=uuidListTypeHandler})
            </if>
            <if test="createtimeStart != null and createtimeEnd != null">
                AND t.op_create_time &gt;= #{createtimeStart}::timestamp with time zone
                AND t.op_create_time &lt; #{createtimeEnd}::timestamp with time zone + interval '1 day'
            </if>
            <if test="viewVoidedDocuments !=null and viewVoidedDocuments == false">
                AND  t.flg_valid = true
            </if>
            <if test="searchText !=null">
                AND (  t.order_no LIKE concat('%', my_ex.likequery(#{searchText}), '%')
                OR   t.contact_phone LIKE concat('%', my_ex.likequery(#{searchText}), '%')
                OR   t.address_full LIKE concat('%', my_ex.likequery(#{searchText}), '%')
                OR   t.remarks LIKE concat('%', my_ex.likequery(#{searchText}), '%')
                )
            </if>

        </where>
    </sql>

    <sql id="idsForeach">
        <!-- 根据主键orderId批量操作 -->
        WHERE order_id in
        <foreach collection="ids" index="index" item="item" separator="," open="(" close=")">
            #{item}
        </foreach>
    </sql>

    <!-- 查询表t_psi_order，（条件查询+分页）列表 -->
    <select id="selectByCond" resultMap="BaseResultMapResponse">
        SELECT t.order_id,
               t.order_no,
               t.order_type,
               sys.f_get_name_i18n(tdk1.kind_name_i18n, #{i18n}) as "orderTypeName",
               t.org_id,
               tmo.org_name                                      as "orgName",
               t.staff_id,
               tms.staff_name                                    as "staffName",
               t.cus_id,
               tmc.cus_code                                      as "cusCode",
               tmc.cus_name                                      as "cusName",
               tmc.cus_phone                                     as "cusPhone",
               tmc.cus_from                                      as "cusFrom",
               tmdd.data_value                                   as "cusFromName",
               t.address_area,
               t.address_name,
               t.address_no,
               t.address_gcj02,
               t.address_full,
               t.contact_name,
               t.contact_phone,
               t.sales_channel,
               tmsc.channel_name                                 as "channelName",
               t.delivery_date,
               t.sum_quantity,
               t.sum_standard,
               t.sum_amount,
               t.sale_discount,
               t.order_status,
               sys.f_get_name_i18n(tdk2.kind_name_i18n, #{i18n}) as "orderStatusName",
               t.out_status,
               sys.f_get_name_i18n(tdk3.kind_name_i18n, #{i18n}) as "outStatusName",
               t.outing_qty,
               t.outing_amt,
               t.out_qty,
               t.out_amt,
               t.return_qty,
               t.return_amt,
               t.amt_receivable,
               t.amt_handle,
               t.amt_residue,
               t.remarks,
               t.annex_paths,
               makestaff.staff_name                              as "makeStaffName",
               t.make_time,
               t.cp_id,
               t.flg_valid
        FROM dkic_b.t_psi_order as t
                 left join dkic_b.t_mst_sale_channel tmsc on t.sales_channel = tmsc.channel_id
                 left join dkic_b.t_mst_org tmo on t.org_id = tmo.org_id
                 left join dkic_b.t_mst_staff tms on t.staff_id = tms.staff_id
                 left join dkic_b.t_mst_staff as makestaff on t.make_staff = makestaff.staff_id
                 left join dkic_b.t_mst_customer tmc on t.cus_id = tmc.cus_id
                 left join dkic_b.t_mst_dictionary_data tmdd on tmc.cus_from = tmdd.data_id
                 left join sys.t_data_kind as tdk1 on t.order_type = tdk1.kind_code
                 left join sys.t_data_kind as tdk2 on t.order_status = tdk2.kind_code
                 left join sys.t_data_kind as tdk3 on t.out_status = tdk3.kind_code
        <include refid="Condition"/>
        order by t.op_create_time desc
        <if test="pageSize != null and currentPage != null and pageSize != 0 and currentPage != 0">
            limit #{end} offset #{start}
        </if>
    </select>
    <sql id="Base_Column_List_Item_Response_Join">
        toi.item_id AS toi_item_id,
        t.order_id AS toi_order_id,
        t.order_no AS toi_order_no,
        toi.order_id AS toi_order_id,
        toi.item_index AS toi_item_index,
        toi.sku_id AS toi_sku_id,
        toi.item_qty AS toi_item_qty,
        toi.price_std AS toi_price_std,
        toi.amt_std AS toi_amt_std,
        toi.price_sale AS toi_price_sale,
        toi.item_amt AS toi_item_amt,
        toi.price_discount AS toi_price_discount,
        toi.non_std_code AS toi_non_std_code,
        toi.out_status AS toi_out_status,
        toi.outing_qty AS toi_outing_qty,
        toi.outing_amt AS toi_outing_amt,
        toi.out_qty AS toi_out_qty,
        toi.out_amt AS toi_out_amt,
        toi.return_qty AS toi_return_qty,
        toi.return_amt AS toi_return_amt,
        toi.remarks AS toi_remarks,
        toi.flg_valid AS toi_flg_valid,
        toi.cp_id AS toi_cp_id,
        tmgs.sku_code AS toi_sku_code,
        tmgs.sku_model AS toi_sku_model,
        tmgs.sku_name AS toi_sku_name,
        tmgb.brand_name AS toi_brand_name,
        tmgb.short_name AS toi_short_name,
        tmgs.price_purchase AS toi_price_purchase,
        tmgs.price_standard AS toi_price_standard
    </sql>

    <!-- 查询表t_psi_order，（条件查询+分页）列表 -->
    <select id="purSaleSelectByCond" resultType="Map">
        SELECT T
        .order_no AS "orderNo",
        T.order_type AS "orderType",
        sys.f_get_name_i18n ( tdk1.kind_name_i18n, #{ i18n } ) AS "orderTypeName",
        T.org_id AS "orgId",
        tmo.org_name AS "orgName",
        T.staff_id AS "staffId",
        tms.staff_name AS "staffName",
        T.cus_id AS "cusId",
        tmc.cus_code AS "cusCode",
        tmc.cus_name AS "cusName",
        tmc.cus_phone AS "cusPhone",
        tmc.cus_from AS "cusFrom",
        tmdd.data_value AS "dataValue",
        T.address_area AS "addressArea",
        T.address_name AS "addressName",
        T.address_no AS "addressNo",
        T.address_gcj02 AS "addressGcj02",
        T.address_full AS "addressFull",
        T.contact_name AS "contactName",
        T.contact_phone AS "contactPhone",
        T.sales_channel AS "salesChannel",
        tmsc.channel_name AS "channelName",
        T.delivery_date AS "deliveryDate",
        T.sum_quantity AS "sumQuantity",
        T.sum_standard AS "sumStandard",
        T.sum_amount AS "sumAmount",
        T.sale_discount AS "saleDiscount",
        T.order_status AS "orderStatus",
        sys.f_get_name_i18n ( tdk2.kind_name_i18n, #{ i18n } ) AS "orderStatusName",
        T.out_status AS "outStatus",
        sys.f_get_name_i18n ( tdk3.kind_name_i18n, #{ i18n } ) AS "outStatusName",
        T.outing_qty AS "outingQty",
        T.outing_amt AS "outingAmt",
        T.out_qty AS "outQty",
        T.out_amt AS "outAmt",
        T.return_qty AS "returnQty",
        T.return_amt AS "returnAmt",
        T.amt_receivable AS "amtReceivable",
        T.amt_handle AS "amtHandle",
        T.amt_residue AS "amtResidue",
        T.remarks AS "remarks",
        T.annex_paths AS "annexPaths",
        makestaff.staff_name AS "makeStaffName",
        T.make_time AS "annexPaths",
        T.cp_id AS "cpId",
        T.flg_valid AS "flgValid",
        (
        SELECT
        json_agg ( row_to_json ( item ) )
        FROM
        (
        SELECT
        toi.item_id AS "itemId",
        T.order_id AS "orderId",
        T.order_no AS "orderNo",
        toi.order_id AS "orderId",
        toi.item_index AS "itemIndex",
        toi.sku_id AS "skuId",
        toi.item_qty AS "itemQty",
        toi.price_std AS "priceStd",
        toi.amt_std AS "amtStd",
        toi.price_sale AS "priceSale",
        toi.item_amt AS "itemAmt",
        toi.price_discount AS "priceDiscount",
        toi.non_std_code AS "nonStdCode",
        toi.out_status AS "outStatus",
        toi.outing_qty AS "outingQty",
        toi.outing_amt AS "outingAmt",
        toi.out_qty AS "outQty",
        toi.out_amt AS "outAmt",
        toi.return_qty AS "returnQty",
        toi.return_amt AS "returnAmt",
        toi.remarks AS "remarks",
        toi.flg_valid AS "flgValid",
        toi.cp_id AS "cpId",
        tmgs.sku_code AS "skuCode",
        tmgs.sku_model AS "skuModel",
        tmgs.sku_name AS "skuName",
        tmgb.brand_name AS "brandName",
        tmgb.short_name AS "shortName",
        tmgs.price_purchase AS "pricePurchase",
        tmgs.price_standard AS "priceStandard",
        tmgs.sku_images AS "skuImages"
        FROM
        dkic_b.t_psi_order_item toi
        LEFT JOIN dkic_b.t_mst_goods_sku tmgs ON tmgs.sku_id = toi.sku_id
        LEFT JOIN dkic_b.t_mst_goods_brand tmgb ON tmgb.brand_id = tmgs.brand_id
        WHERE
        toi.order_id = T.order_id
        ) item
        )  AS  "orderItemResponseList"
        FROM
        dkic_b.t_psi_order
        AS T LEFT JOIN dkic_b.t_psi_order_item toi ON toi.order_id = T.order_id
        LEFT JOIN dkic_b.t_mst_sale_channel tmsc ON T.sales_channel = tmsc.channel_id
        LEFT JOIN dkic_b.t_mst_org tmo ON T.org_id = tmo.org_id
        LEFT JOIN dkic_b.t_mst_staff tms ON T.staff_id = tms.staff_id
        LEFT JOIN dkic_b.t_mst_staff AS makestaff ON T.make_staff = makestaff.staff_id
        LEFT JOIN dkic_b.t_mst_customer tmc ON T.cus_id = tmc.cus_id
        LEFT JOIN dkic_b.t_mst_dictionary_data tmdd ON tmc.cus_from = tmdd.data_id
        LEFT JOIN sys.t_data_kind AS tdk1 ON T.order_type = tdk1.kind_code
        LEFT JOIN sys.t_data_kind AS tdk2 ON T.order_status = tdk2.kind_code
        LEFT JOIN sys.t_data_kind AS tdk3 ON T.out_status = tdk3.kind_code
        <include refid="Condition"/>
        order by t.op_create_time desc
        <if test="pageSize != null and currentPage != null and pageSize != 0 and currentPage != 0">
            limit #{end} offset #{start}
        </if>
    </select>


    <!-- 查询表t_psi_order，（条件查询）个数 -->
    <select id="countByCond" resultType="Long">
        SELECT
        count(1)
        FROM dkic_b.t_psi_order as t
                left join dkic_b.t_mst_customer tmc on t.cus_id = tmc.cus_id
        left join dkic_b.t_psi_order_item toi on toi.order_id  = t.order_id
        <include refid="Condition"/>
    </select>

    <!-- 根据主键查询表t_psi_order的一行数据 -->
    <select id="selectById" resultMap="BaseResultMapResponse">
        SELECT t.order_id,
               t.order_no,
               t.order_type,
               sys.f_get_name_i18n(tdk1.kind_name_i18n, #{i18n}) as "orderTypeName",
               t.org_id,
               tmo.org_name                                      as "orgName",
               t.staff_id,
               tms.staff_name                                    as "staffName",
               t.cus_id,
               tmc.cus_code                                      as "cusCode",
               tmc.cus_name                                      as "cusName",
               tmc.cus_phone                                     as "cusPhone",
               tmc.cus_from                                      as "cusFrom",
               tmdd.data_value                                   as "cusFromName",
               t.address_area,
               t.address_name,
               t.address_no,
               t.address_gcj02,
               t.address_full,
               t.contact_name,
               t.contact_phone,
               t.sales_channel,
               tmsc.channel_name                                 as "channelName",
               t.delivery_date,
               t.sum_quantity,
               t.sum_standard,
               t.sum_amount,
               t.sale_discount,
               t.order_status,
               sys.f_get_name_i18n(tdk2.kind_name_i18n, #{i18n}) as "orderStatusName",
               t.out_status,
               sys.f_get_name_i18n(tdk3.kind_name_i18n, #{i18n}) as "outStatusName",
               t.outing_qty,
               t.outing_amt,
               t.out_qty,
               t.out_amt,
               t.return_qty,
               t.return_amt,
               t.amt_receivable,
               t.amt_handle,
               t.amt_residue,
               t.remarks,
               t.annex_paths,
               t.make_staff,
               makestaff.staff_name                              as "makeStaffName",
               t.make_time,
               t.cp_id
        FROM dkic_b.t_psi_order as t
                 left join dkic_b.t_mst_sale_channel tmsc on t.sales_channel = tmsc.channel_id
                 left join dkic_b.t_mst_org tmo on t.org_id = tmo.org_id
                 left join dkic_b.t_mst_staff tms on t.staff_id = tms.staff_id
                 left join dkic_b.t_mst_staff as makestaff on t.make_staff = makestaff.staff_id
                 left join dkic_b.t_mst_customer tmc on t.cus_id = tmc.cus_id
                 left join dkic_b.t_mst_dictionary_data tmdd on tmc.cus_from = tmdd.data_id
                 left join sys.t_data_kind as tdk1 on t.order_type = tdk1.kind_code
                 left join sys.t_data_kind as tdk2 on t.order_status = tdk2.kind_code
                 left join sys.t_data_kind as tdk3 on t.out_status = tdk3.kind_code
        WHERE t.order_id = #{id}::uuid
    </select>

    <!-- 根据主键锁定表t_psi_order的一行数据 -->
    <select id="selectByIdForUpdate" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM dkic_b.t_psi_order
        WHERE order_id = #{id}::uuid
        for update
    </select>

    <!-- 根据主键锁定表t_psi_order的多行数据 -->
    <select id="selectByIdsForUpdate" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM dkic_b.t_psi_order
        <include refid="idsForeach"/>
        for update
    </select>

    <insert id="insertBatch">
        insert into dkic_b.t_psi_order
        (
        <trim suffixOverrides=",">
            order_no,
            order_type,
            org_id,
            staff_id,
            cus_id,
            address_area,
            address_name,
            address_no,
            address_gcj02,
            address_full,
            contact_name,
            contact_phone,
            sales_channel,
            delivery_date,
            sum_quantity,
            sum_standard,
            sum_amount,
            sale_discount,
            order_status,
            out_status,
            outing_qty,
            outing_amt,
            out_qty,
            out_amt,
            return_qty,
            return_amt,
            amt_receivable,
            amt_handle,
            amt_residue,
            remarks,
            annex_paths,
            make_staff,
            make_time,
            cp_id,
            op_app_code,
        </trim>
        )
        values
        <foreach collection="list" index="index" item="item" separator=",">
            (
            <trim suffixOverrides=",">
                #{item.orderNo},
                #{item.orderType},
                #{item.orgId}::uuid,
                #{item.staffId}::uuid,
                #{item.cusId}::uuid,
                #{item.addressArea},
                #{item.addressName},
                #{item.addressNo},
                #{item.addressGcj02},
                #{item.addressFull},
                #{item.contactName},
                #{item.contactPhone},
                #{item.salesChannel}::uuid,
                #{item.deliveryDate},
                #{item.sumQuantity},
                #{item.sumStandard},
                #{item.sumAmount},
                #{item.saleDiscount},
                #{item.orderStatus},
                #{item.outStatus},
                #{item.outingQty},
                #{item.outingAmt},
                #{item.outQty},
                #{item.outAmt},
                #{item.returnQty},
                #{item.returnAmt},
                #{item.amtReceivable},
                #{item.amtHandle},
                #{item.amtResidue},
                #{item.remarks},
                #{item.annexPaths},
                #{item.makeStaff}::uuid,
                #{item.makeTime},
                #{item.cpId},
                #{item.opAppCode},
            </trim>
            )
        </foreach>
    </insert>

    <!-- 根据id修改-->
    <update id="updateById" parameterType="com.dk.mdm.model.pojo.sale.Order">
        update dkic_b.t_psi_order
        <set>
            <if test=" et!=null and et.orderType != null">
                order_type =#{et.orderType,jdbcType=VARCHAR},
            </if>
            <if test=" et!=null and et.orgId != null">
                org_id =#{et.orgId,typeHandler=UuidTypeHandler},
            </if>
            <if test=" et!=null and et.staffId != null">
                staff_id =#{et.staffId,typeHandler=UuidTypeHandler},
            </if>
            <if test=" et!=null and et.cusId != null">
                cus_id =#{et.cusId,typeHandler=UuidTypeHandler},
            </if>
            <if test=" et!=null and et.addressArea != null">
                address_area =#{et.addressArea,typeHandler=JsonTypeHandler},
            </if>
            <if test=" et!=null and et.addressName != null">
                address_name =#{et.addressName,jdbcType=VARCHAR},
            </if>
            <if test=" et!=null and et.addressNo != null">
                address_no =#{et.addressNo,jdbcType=VARCHAR},
            </if>
            <if test=" et!=null and et.addressGcj02 != null">
                address_gcj02 =#{et.addressGcj02,typeHandler=JsonTypeHandler},
            </if>
            <if test=" et!=null and et.addressFull != null">
                address_full =#{et.addressFull,jdbcType=VARCHAR},
            </if>
            <if test=" et!=null and et.contactName != null">
                contact_name =#{et.contactName,jdbcType=VARCHAR},
            </if>
            <if test=" et!=null and et.contactPhone != null">
                contact_phone =#{et.contactPhone,jdbcType=VARCHAR},
            </if>
            <if test=" et!=null and et.salesChannel != null">
                sales_channel =#{et.salesChannel,jdbcType=OTHER},
            </if>
            <if test=" et!=null and et.deliveryDate != null">
                delivery_date =#{et.deliveryDate,jdbcType=DATE},
            </if>
            <if test=" et!=null and et.sumQuantity != null">
                sum_quantity =#{et.sumQuantity,jdbcType=NUMERIC},
            </if>
            <if test=" et!=null and et.sumStandard != null">
                sum_standard =#{et.sumStandard,jdbcType=NUMERIC},
            </if>
            <if test=" et!=null and et.sumAmount != null">
                sum_amount =#{et.sumAmount,jdbcType=NUMERIC},
            </if>
            <if test=" et!=null and et.saleDiscount != null">
                sale_discount =#{et.saleDiscount,jdbcType=NUMERIC},
            </if>
            <if test=" et!=null and et.orderStatus != null">
                order_status =#{et.orderStatus,jdbcType=VARCHAR},
            </if>
            <if test=" et!=null and et.outStatus != null">
                out_status =#{et.outStatus,jdbcType=VARCHAR},
            </if>
            <if test=" et!=null and et.outingQty != null">
                outing_qty = outing_qty + #{et.outingQty,jdbcType=NUMERIC},
            </if>
            <if test=" et!=null and et.outingAmt != null">
                outing_amt = outing_amt + #{et.outingAmt,jdbcType=NUMERIC},
            </if>
            <if test=" et!=null and et.outQty != null">
                out_qty =out_qty + #{et.outQty,jdbcType=NUMERIC},
            </if>
            <if test=" et!=null and et.outAmt != null">
                out_amt = out_amt + #{et.outAmt,jdbcType=NUMERIC},
            </if>
            <if test=" et!=null and et.returnQty != null">
                return_qty =#{et.returnQty,jdbcType=NUMERIC},
            </if>
            <if test=" et!=null and et.returnAmt != null">
                return_amt =#{et.returnAmt,jdbcType=NUMERIC},
            </if>
            <if test=" et!=null and et.amtReceivable != null">
                amt_receivable =#{et.amtReceivable,jdbcType=NUMERIC},
            </if>
            <if test=" et!=null and et.amtHandle != null">
                amt_handle =#{et.amtHandle,jdbcType=NUMERIC},
            </if>
            <if test=" et!=null and et.amtResidue != null">
                amt_residue =#{et.amtResidue,jdbcType=NUMERIC},
            </if>
            <if test=" et!=null and et.remarks != null">
                remarks =#{et.remarks,jdbcType=VARCHAR},
            </if>
            <if test=" et!=null and et.annexPaths != null">
                annex_paths =#{et..annexPaths,typeHandler=JsonTypeHandler},
            </if>
            <if test=" et!=null and et.makeStaff != null">
                make_staff =#{et.makeStaff,jdbcType=OTHER},
            </if>
            <if test=" et!=null and et.makeTime != null">
                make_time =#{et.makeTime,jdbcType=TIMESTAMP},
            </if>
            <if test=" et!=null and et.flgValid != null">
                flg_valid =#{et.flgValid,jdbcType=BOOLEAN},
            </if>
            <if test=" et!=null and et.cpId != null">
                cp_id =#{et.cpId,jdbcType=INTEGER},
            </if>
        </set>
        where order_id =#{et.orderId,typeHandler=UuidTypeHandler}
        and sum_quantity >= (out_qty + outing_qty)
    </update>


    <!--  小程序  条件查询(总单带明细)-->
    <select id="selectByCondDetail" resultMap="BaseResultMapDetailResponse">
        SELECT
        <include refid="Base_Column_List_Detail_Join"/>,
        <include refid="Base_Column_List_Item_Response_Detail_Join"/>
        FROM dkic_b.t_psi_order as t
        left join dkic_b.t_psi_order_item toi on toi.order_id  = t.order_id
        inner join dkic_b.t_mst_goods_sku tmgs on tmgs.sku_id  = toi.sku_id
        left join dkic_b.t_mst_goods_brand tmgb on tmgb.brand_id  = tmgs.brand_id
        left join dkic_b.t_mst_org tmo on t.org_id = tmo.org_id
        left join dkic_b.t_mst_staff tms on t.staff_id = tms.staff_id
        left join(SELECT T.*
        FROM (select tpi.inv_id,
        tpi.wh_id,
        tpi.inv_qty,
        tpi.usable_qty,
        tpi.sku_id,
        tpi.non_std_code,
        tpi.cp_id,
        tmw.wh_name,
        rank()
        over (partition by tpi.cp_id,tpi.sku_id,tpi.non_std_code order by tpi.inv_id) as RK
        from dkic_b.t_psi_inventory as tpi
        left join dkic_b.t_mst_warehouse as tmw on tmw.wh_id = tpi.wh_id) T
        WHERE T.RK = 1) as i
        on i.sku_id = toi.sku_id and i.non_std_code = toi.non_std_code and i.cp_id = toi.cp_id
        <include refid="Condition"/>
        order by t.op_create_time desc
        <if test="pageSize != null and currentPage != null and pageSize != 0 and currentPage != 0">
            limit #{end} offset #{start}
        </if>
    </select>

    <!--小程序-->
    <select id="countByCondDetail" resultType="Long">
        SELECT
        count(1)
        FROM dkic_b.t_psi_order as t
        <include refid="Condition"/>
    </select>

    <!--修改退货信息 -->
    <update id="updateReturnMessage" parameterType="com.dk.mdm.model.pojo.sale.Order">
        update dkic_b.t_psi_order
        <set>
            <if test=" returnQty != null">
                return_qty = return_qty + #{returnQty,jdbcType=NUMERIC},
            </if>
            <if test=" returnAmt != null">
                return_amt = return_amt + #{returnAmt,jdbcType=NUMERIC},
            </if>
        </set>
        where order_id = #{orderId,typeHandler=UuidTypeHandler}
        and  out_qty >= return_qty
    </update>

    <!--销售跟踪报表 -->
    <select id="getOrderTrackReport" resultType="java.util.Map">
        SELECT *
        FROM dkic_b.f_query_ord_for_track(#{ordId}::uuid,#{i18n})
    </select>

    <!-- 获取实收金额 -->
    <select id="getFactReceipt" resultType="java.util.Map">
        SELECT COALESCE(sum(t.amt_handle - t.amt_waive), 0) as "sumFactReceipt"
        FROM dkic_b.t_mac_account_item as t
                 inner join dkic_b.t_psi_outbound as tpo on tpo.receivable_id = t.item_id
        where t.flg_valid
          and t.acc_item_type = '账款类型-应收'
          and tpo.from_id = #{id}::uuid
    </select>
</mapper>
