<?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.yc.ship.module.trade.dal.mysql.order.TradeDetailMapper">
    <resultMap id="tradeDetailMap" type="com.yc.ship.module.trade.service.order.bo.TradeDetailBO">
        <result property="id" column="id"/>
        <result property="orderId" column="order_id"/>
        <result property="hotelOrderId" column="hotel_order_id"/>
        <result property="routePlanId" column="route_plan_id"/>
        <result property="faceimg" column="faceimg"/>
        <result property="voucherCode" column="voucher_code"/>
        <result property="voucherStatus" column="voucher_status"/>
        <result property="useDate" column="use_date"/>
        <result property="validityStartDate" column="validity_start_date"/>
        <result property="validityEndDate" column="validity_end_date"/>
        <result property="usageDays" column="usage_days"/>
        <result property="checkStatus" column="check_status"/>
        <result property="takeStatus" column="take_status"/>
        <result property="refundStatus" column="refund_status"/>
        <result property="verifyTime" column="verify_time"/>
        <result property="activateStatus" column="activate_status"/>
        <result property="activateDays" column="activate_days"/>
        <result property="activateTime" column="activate_time"/>
        <result property="productId" column="product_id"/>
        <result property="productName" column="product_name"/>
        <result property="specType" column="spec_type"/>
        <result property="price" column="price"/>
        <result property="actualPrice" column="actual_price"/>
        <result property="quantityOfOne" column="quantity_of_one"/>
        <result property="useRealName" column="use_real_name"/>
        <result property="productType" column="product_type"/>
        <result property="cateType" column="cate_type"/>

        <collection property="tradeDetailBaseList" ofType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailBaseDO" javaType="java.util.List">
            <result property="id" column="detail_base_id"/>
            <result property="detailId" column="detail_id"/>
            <result property="productBaseId" column="product_base_id"/>
            <result property="productBaseName" column="product_base_name"/>
            <result property="productBaseType" column="product_base_type"/>
            <result property="productResourceId" column="product_resource_id"/>
            <result property="productResourceName" column="product_resource_name"/>
            <result property="supplierProductId" column="supplier_product_id"/>
            <result property="supplierId" column="supplier_id"/>
            <result property="supplierName" column="supplier_name"/>
            <result property="isSystemDirect" column="is_system_direct"/>
            <result property="useStatus" column="use_status"/>
            <result property="checkStatus" column="base_check_status"/>
            <result property="verifyTime" column="base_verify_time"/>
            <result property="price" column="base_price"/>
            <result property="usageCount" column="usage_count"/>
            <result property="productResourcePrice" column="product_resource_price"/>
            <result property="projectId" column="project_id"/>
            <result property="projectName" column="project_name"/>
            <result property="projectCode" column="project_code"/>
            <result property="specificationId" column="specification_id"/>
            <result property="specificationName" column="specification_name"/>
            <result property="specType" column="base_spec_type"/>
            <result property="supplierVoucherCode" column="supplier_voucher_code"/>
            <result property="platSupplierOrderId" column="plat_supplier_order_id"/>
        </collection>
    </resultMap>
    
    
    <select id="selectTradeDetailWithBase" resultMap="tradeDetailMap">
        select td.*,tdb.id detail_base_id,tdb.detail_id,tdb.product_base_id,tdb.product_base_name,tdb.product_base_type,tdb.product_resource_id,tdb.product_resource_name,tdb.supplier_product_id,tdb.supplier_id,
        tdb.supplier_name,tdb.is_system_direct,tdb.use_status,tdb.check_status base_check_status,tdb.verify_time base_verify_time,tdb.price base_price,tdb.usage_count,tdb.product_resource_price,tdb.project_id,tdb.project_name,
        tdb.specification_id,tdb.specification_name,tdb.spec_type base_spec_type,tdb.supplier_voucher_code,tdb.plat_supplier_order_id,tdb.project_code
        from trade_detail td
        left join trade_detail_base tdb on td.id = tdb.detail_id and tdb.deleted = 0
        <where>
            td.order_id = #{orderId} and td.deleted = 0
        <if test="tradeDetailId!=null">
            and  td.id = #{tradeDetailId}
        </if>
        <if test="voucherList!=null">
            and  td.voucher_code in
            <foreach collection="voucherList" item="item" separator=","  open="(" close=")">
               #{item}
            </foreach>
        </if>
        <if test="detailIdList!=null">
            and  td.id in
            <foreach collection="detailIdList" item="item" separator=","  open="(" close=")">
                #{item}
            </foreach>
        </if>
        </where>
    </select>

    <update id="updateRefundingBatch">
        <foreach collection="tradeDetailList" item="item" separator=";"  close=";">
            UPDATE trade_detail SET voucher_status = #{refundStatus}
            WHERE id = #{item.id} AND voucher_status = #{item.voucherStatus}
        </foreach>
    </update>

    <update id="updateStatusAfterAllCheck">
        UPDATE trade_detail d LEFT JOIN ( SELECT detail_id FROM trade_detail_base WHERE use_status != 3 and order_id = #{orderId} GROUP BY detail_id ) b ON d.id = b.detail_id
        SET d.voucher_status = 3 WHERE d.order_id = #{orderId} and d.voucher_status in (1,2,8) and b.detail_id is null and d.voucher_status != 3
    </update>

    <update id="updateVoucherStatus">
        UPDATE trade_detail SET voucher_status = #{voucherStatus} WHERE id = #{tradeDetailId}
    </update>

    <select id="queryDetailCountByOrderId" resultType="java.util.Map">
        select count(*)      as allCount,
               SUM(t.price)    as allAmount,
               SUM(CASE WHEN t.voucher_status = '3' THEN 1 ELSE 0 END) AS checkCount,
               SUM(CASE WHEN t.voucher_status = '8' THEN 1 ELSE 0 END) AS partCount,
               SUM(CASE WHEN t.voucher_status = '1' THEN 1 ELSE 0 END) AS payCount,
               SUM(CASE WHEN t.voucher_status = '2' THEN 1 ELSE 0 END) AS takeCount,
               SUM(CASE WHEN t.voucher_status in ('4','5') THEN 1 ELSE 0 END) AS refundCount,
               SUM(CASE WHEN t.voucher_status in ('4','5') THEN t.price ELSE 0 END) as refundAmount,
               SUM(CASE WHEN t.voucher_status <![CDATA[ <> '5' ]]> AND  t.voucher_status <![CDATA[ <> '4' ]]> AND t.voucher_status > 0 THEN 1 ELSE 0 END) AS realityNum,
               SUM(CASE WHEN t.voucher_status <![CDATA[ <> '5' ]]> AND  t.voucher_status <![CDATA[ <> '4' ]]> AND t.voucher_status > 0 THEN t.price ELSE 0 END) as realityAmount,
               SUM(CASE WHEN  t.voucher_status in ('6','7')  THEN 1 ELSE 0 END) AS outTimeCount

        from trade_detail t
        where t.order_id = #{orderId}
    </select>

    <resultMap id="MiddleWareDtoResultMap" type="com.yc.ship.module.trade.controller.admin.order.vo.order.TradeDetailRespVO">
        <id property="id" column="id"/>
        <result property="orderId" column="order_id"/>
        <result property="visitorId" column="visitor_id"/>
        <result property="orderNo" column="order_no"/>
        <result property="voucherCode" column="voucher_code"/>
        <result property="voucherStatus" column="voucher_status"/>
        <result property="useDate" column="use_date"/>
        <result property="validityStartDate" column="validity_start_date"/>
        <result property="validityEndDate" column="validity_end_date"/>
        <result property="usageDays" column="usage_days"/>
        <result property="checkStatus" column="check_status"/>
        <result property="takeStatus" column="take_status"/>
        <result property="refundStatus" column="refund_status"/>
        <result property="verifyTime" column="verify_time"/>
        <result property="activateStatus" column="activate_status"/>
        <result property="activateDays" column="activate_days"/>
        <result property="activateTime" column="activate_time"/>
        <result property="productId" column="product_id"/>
        <result property="productType" column="product_type"/>
        <result property="productTag" column="product_tag"/>
        <result property="productTag2" column="product_tag2"/>
        <result property="suppSpecType" column="supp_spec_type"/>
        <result property="productName" column="product_name"/>
        <result property="productCategoryName" column="full_path_name"/>
        <result property="specType" column="spec_type"/>
        <result property="price" column="price"/>
        <result property="visitorId" column="visitorId"/>
        <result property="actualPrice" column="actual_price"/>
        <result property="quantityOfOne" column="quantity_of_one"/>
        <result property="useRealName" column="use_real_name"/>
        <result property="cateType" column="cate_type"/>
        <result property="hotelOrderId" column="hotel_order_id"/>
        <result property="routePlanId" column="route_plan_id"/>
        <result property="packProductId" column="pack_product_id"/>
        <result property="packProductName" column="pack_product_name"/>
        <result property="routePlanId" column="route_plan_id"/>
        <result property="routePlanGroupType" column="route_plan_group_type"/>
        <result property="createTime" column="create_time"/>
        <collection property="visitors" resultMap="visitorResultMap"/>
    </resultMap>
    <resultMap id="MiddleWareDtoResultMap2" type="com.yc.ship.module.trade.controller.admin.order.vo.order.TradeDetailRespVO">
        <id property="id" column="id"/>
        <result property="orderId" column="order_id"/>
        <result property="visitorId" column="visitor_id"/>
        <result property="orderNo" column="order_no"/>
        <result property="voucherCode" column="voucher_code"/>
        <result property="voucherStatus" column="voucher_status"/>
        <result property="useDate" column="use_date"/>
        <result property="validityStartDate" column="validity_start_date"/>
        <result property="validityEndDate" column="validity_end_date"/>
        <result property="usageDays" column="usage_days"/>
        <result property="checkStatus" column="check_status"/>
        <result property="takeStatus" column="take_status"/>
        <result property="refundStatus" column="refund_status"/>
        <result property="verifyTime" column="verify_time"/>
        <result property="activateStatus" column="activate_status"/>
        <result property="activateDays" column="activate_days"/>
        <result property="activateTime" column="activate_time"/>
        <result property="productId" column="product_id"/>
        <result property="productType" column="product_type"/>
        <result property="productTag" column="product_tag"/>
        <result property="productTag2" column="product_tag2"/>
        <result property="suppSpecType" column="supp_spec_type"/>
        <result property="productName" column="product_name"/>
        <result property="productCategoryName" column="full_path_name"/>
        <result property="specType" column="spec_type"/>
        <result property="price" column="price"/>
        <result property="visitorId" column="visitorId"/>
        <result property="actualPrice" column="actual_price"/>
        <result property="quantityOfOne" column="quantity_of_one"/>
        <result property="useRealName" column="use_real_name"/>
        <result property="cateType" column="cate_type"/>
        <result property="hotelOrderId" column="hotel_order_id"/>
        <result property="routePlanId" column="route_plan_id"/>
        <result property="packProductId" column="pack_product_id"/>
        <result property="packProductName" column="pack_product_name"/>
        <result property="routePlanId" column="route_plan_id"/>
        <result property="routePlanGroupType" column="route_plan_group_type"/>
        <collection property="visitors" resultMap="visitorResultMap"/>
    </resultMap>

    <resultMap id="visitorResultMap" type="com.yc.ship.module.trade.dal.dataobject.order.TradeVisitorDO">
        <id property="id" column="visitorId"/>
        <result property="detailId" column="detail_id"/>
        <result property="name" column="name"/>
        <result property="gender" column="gender"/>
        <result property="credentialNo" column="credential_no"/>
        <result property="credentialType" column="credential_type"/>
        <result property="mobile" column="mobile"/>
        <result property="otaDetailId" column="ota_detail_id"/>
        <result property="isInsure" column="is_insure"/>
        <result property="age" column="age"/>
        <result property="birthday" column="birthday"/>
        <result property="cohabitation" column="cohabitation"/>
        <result property="type" column="type"/>
        <result property="roomId" column="room_id"/>
        <result property="remark" column="remark"/>
        <result property="initRoomId" column="init_room_id"/>
        <result property="finalRoomId" column="final_room_id"/>
        <result property="inDate" column="in_date"/>
        <result property="outDate" column="out_date"/>
        <result property="nationality" column="nationality"/>
        <result property="nationalityName" column="nationalityName"/>
        <result property="roomIndexId" column="room_index_id"/>
        <result property="roomModelId" column="room_model_id"/>
        <result property="floor" column="floor"/>
        <result property="area" column="area"/>
        <result property="vid" column="vid"/>

    </resultMap>


    <resultMap id="tradeDetailBaseResMap" type="com.yc.ship.module.trade.controller.admin.order.vo.order.DetailBaseRespVO">
        <result property="id" column="id"/>
        <result property="detailId" column="detail_id"/>
        <result property="productBaseId" column="product_base_id"/>
        <result property="productBaseName" column="product_base_name"/>
        <result property="productBaseType" column="product_base_type"/>
        <result property="productResourceId" column="product_resource_id"/>
        <result property="productResourceName" column="product_resource_name"/>
        <result property="supplierProductId" column="supplier_product_id"/>
        <result property="supplierId" column="supplier_id"/>
        <result property="supplierName" column="supplier_name"/>
        <result property="isSystemDirect" column="is_system_direct"/>
        <result property="useStatus" column="use_status"/>
        <result property="checkStatus" column="check_status"/>
        <result property="verifyTime" column="verify_time"/>
        <result property="price" column="price"/>
        <result property="usageCount" column="usage_count"/>
        <result property="productResourcePrice" column="product_resource_price"/>
        <result property="projectId" column="project_id"/>
        <result property="projectCode" column="project_code"/>
        <result property="projectName" column="project_name"/>
        <result property="specificationId" column="specification_id"/>
        <result property="specificationName" column="specification_name"/>
        <result property="specType" column="spec_type"/>
        <result property="supplierVoucherCode" column="supplier_voucher_code"/>
        <result property="platSupplierOrderId" column="plat_supplier_order_id"/>
        <result property="platSupplierOrderNo" column="plat_supplier_order_no"/>
        <result property="useDate" column="use_date"/>
        <result property="planStartTime" column="plan_start_time"/>
    </resultMap>

    <select id="getOrderIdDetail" resultMap="MiddleWareDtoResultMap">
        SELECT td.*,tv.detail_id,tv.name,tv.id visitorId,tv.gender,tv.credential_no,tv.age,tv.birthday,tv.nationality,tv.cohabitation,tv.room_id,tv.in_date,tv.out_date,tv.remark,tv.init_room_id,tv.final_room_id,tv.type,
        tv.credential_type, tv.mobile,tv.ota_detail_id,tv.is_insure,tv.room_index_id,tv.room_model_id,tv.floor,tv.vid,pc.full_path_name,p.product_tag,p.product_tag2, a.name nationalityName
        FROM trade_detail td
        left join product_spu p on p.id = td.product_id
        left join product_category pc on pc.id = p.category_id
        left JOIN trade_visitor tv on td.visitor_id = tv.id and tv.deleted=0
        left join area a on tv.nationality = a.id
        where 1= 1 and td.deleted = 0
        <if test="orderId != null and orderId != ''">
            AND td.order_id = #{orderId}
        </if>
    </select>
    <select id="getOrderIdDetailList2" resultMap="MiddleWareDtoResultMap2">
    SELECT td.*,tv.detail_id,tv.name,tv.id visitorId,tv.gender,tv.credential_no,
    tv.credential_type, tv.mobile,tv.ota_detail_id,tv.is_insure,pc.full_path_name,p.product_tag,p.product_tag2,tstd.supp_spec_type
    FROM trade_detail td
    inner join product_spu p on p.id = td.product_id
    inner join product_category pc on pc.id = p.category_id
    inner JOIN trade_visitor tv on td.id = tv.detail_id
    left join trade_supp_ticket_detail tstd on td.id = tstd.trade_detail_id
    where 1= 1
        <if test="orderIds!=null">
            and  td.order_id in
            <foreach collection="orderIds" item="item" separator=","  open="(" close=")">
                #{item}
            </foreach>
        </if>
    </select>

    <select id="getOrderIdDetailList" resultMap="MiddleWareDtoResultMap">
        SELECT td.*,tv.detail_id,tv.name,tv.id visitorId,tv.gender,tv.credential_no,
        tv.credential_type, tv.mobile,tv.ota_detail_id,tv.is_insure,pc.full_path_name,p.product_tag,p.product_tag2,tstd.supp_spec_type
        FROM trade_detail td
        inner join product_spu p on p.id = td.product_id
        inner join product_category pc on pc.id = p.category_id
        inner JOIN trade_visitor tv on td.visitor_id = tv.id
        left join trade_supp_ticket_detail tstd on td.id = tstd.trade_detail_id
        where 1= 1

        and  td.order_id in
        ( SELECT td.id FROM
        product_marketing_audit pma
        INNER JOIN trade_order td on pma.order_id = td.id
        INNER JOIN trade_detail tdl on td.id = tdl.order_id
        INNER JOIN trade_order_user tou ON td.id = tou.order_id
        LEFT JOIN product_marketing_pool_spu pms on td.id = pms.order_id
        LEFT JOIN product_marketing pmk ON pmk.id = pma.marketing_id
        WHERE 1 = 1
        <if test="vo.storeId != null">
            and pma.store_id = #{vo.storeId}
        </if>
        <if test="vo.distributorId != null">
            and td.source_id = #{vo.distributorId}
        </if>
        <if test="vo.ids.size()>0">
            and pma.travel_id in
            <foreach collection="vo.ids" item="item" separator=","  open="(" close=")">
                #{item}
            </foreach>
        </if>
        <if test="vo.isExecute != null">
            and pma.is_execute = #{vo.isExecute}
        </if>
        <if test="vo.policyType != null and vo.policyType != ''">
            AND pmk.policy_type = #{vo.policyType}
        </if>
        <if test="vo.marketingName != null and vo.marketingName != ''">
            AND pmk.name like concat('%',#{vo.marketingName}, '%')
        </if>
        <if test="vo.auditState != null">
            and pma.audit_state = #{vo.auditState}
        </if>
        <if test="vo.useAuditState != null">
            and pma.use_audit_state = #{vo.useAuditState}
        </if>
        <if test="vo.orderNo != null and vo.orderNo != ''">
            AND td.order_no = #{vo.orderNo}
        </if>
        <if test="vo.travelDate != null and vo.travelDate != ''">
            AND td.travel_date = #{vo.travelDate}
        </if>
        <if test="vo.travelDateStart != null and vo.travelDateStart != ''">
            AND td.travel_date <![CDATA[ >= ]]> #{vo.travelDateStart}
        </if>
        <if test="vo.travelDateEnd != null and vo.travelDateEnd != ''">
            AND td.travel_date <![CDATA[ <= ]]> #{vo.travelDateEnd}
        </if>
        <if test="vo.productName != null and vo.productName != ''">
            AND tdl.product_name like concat('%',#{vo.productName}, '%')
        </if>
        )

    </select>

    <select id="getOrderIdDetailList1" resultMap="MiddleWareDtoResultMap2">
        SELECT td.*,tv.detail_id,tv.name,tv.id visitorId,tv.gender,tv.credential_no,
        tv.credential_type, tv.mobile,tv.ota_detail_id,tv.is_insure,pc.full_path_name,p.product_tag,p.product_tag2,tstd.supp_spec_type
        FROM trade_detail td
        inner join product_spu p on p.id = td.product_id
        inner join product_category pc on pc.id = p.category_id
        inner JOIN trade_visitor tv on td.visitor_id = tv.id
        left join trade_supp_ticket_detail tstd on td.id = tstd.trade_detail_id
        where 1= 1

            and  td.order_id in
        ( SELECT td.id FROM
        product_marketing_audit pma
        INNER JOIN trade_order td on pma.order_id = td.id
        INNER JOIN trade_detail tdl on td.id = tdl.order_id
        INNER JOIN trade_order_user tou ON td.id = tou.order_id
        LEFT JOIN product_marketing_pool_spu pms on td.id = pms.order_id
        LEFT JOIN product_marketing pmk ON pmk.id = pma.marketing_id
        WHERE 1 = 1
        <if test="vo.storeId != null">
            and pma.store_id = #{vo.storeId}
        </if>
        <if test="vo.distributorId != null">
            and td.source_id = #{vo.distributorId}
        </if>
        <if test="vo.ids.size()>0">
            and pma.travel_id in
            <foreach collection="vo.ids" item="item" separator=","  open="(" close=")">
                #{item}
            </foreach>
        </if>
        <if test="vo.isExecute != null">
            and pma.is_execute = #{vo.isExecute}
        </if>
        <if test="vo.policyType != null and vo.policyType != ''">
            AND pmk.policy_type = #{vo.policyType}
        </if>
        <if test="vo.marketingName != null and vo.marketingName != ''">
            AND pmk.name like concat('%',#{vo.marketingName}, '%')
        </if>
        <if test="vo.auditState != null">
            and pma.audit_state = #{vo.auditState}
        </if>
        <if test="vo.useAuditState != null">
            and pma.use_audit_state = #{vo.useAuditState}
        </if>
        <if test="vo.orderNo != null and vo.orderNo != ''">
            AND td.order_no = #{vo.orderNo}
        </if>
        <if test="vo.travelDate != null and vo.travelDate != ''">
            AND td.travel_date = #{vo.travelDate}
        </if>
        <if test="vo.travelDateStart != null and vo.travelDateStart != ''">
            AND td.travel_date <![CDATA[ >= ]]> #{vo.travelDateStart}
        </if>
        <if test="vo.travelDateEnd != null and vo.travelDateEnd != ''">
            AND td.travel_date <![CDATA[ <= ]]> #{vo.travelDateEnd}
        </if>
        <if test="vo.productName != null and vo.productName != ''">
            AND tdl.product_name like concat('%',#{vo.productName}, '%')
        </if>
        )

    </select>

    <select id="getOrderIdDetailV2" resultMap="MiddleWareDtoResultMap">
        SELECT td.*,tv.detail_id,tv.name,tv.id visitorId,tv.gender,tv.credential_no,
        tv.credential_type, tv.mobile,tv.ota_detail_id,tv.is_insure
        FROM trade_detail td
        left JOIN trade_visitor tv on td.id = tv.detail_id
        where 1= 1
        <if test="orderId != null and orderId != ''">
            AND td.order_id = #{orderId}
        </if>
    </select>

    <select id="getOtcOrderIdDetail" resultMap="MiddleWareDtoResultMap">
        SELECT td.*,tv.detail_id,tv.name,tv.id visitorId,tv.gender,tv.credential_no,
        tv.credential_type, tv.mobile,tv.ota_detail_id,tv.is_insure,pc.full_path_name
        FROM trade_detail td
        inner join ota_distributor_product d on d.id = td.product_id
        inner join product_spu p on p.id = d.product_id
        inner join product_category pc on pc.id = p.category_id
        left JOIN trade_visitor tv on td.id = tv.detail_id
        where 1= 1
        <if test="orderId != null and orderId != ''">
            AND td.order_id = #{orderId}
        </if>
    </select>



    <select id="selectRefundCount" resultType="java.util.Map">
        select count(*) totalCount,count(if(td.voucher_status=5,1,null)) refundCount
        from trade_detail td
        where td.order_id=#{orderId} and product_type = 0
    </select>

    <resultMap id="RefundDetailMap" type="com.yc.ship.module.trade.controller.admin.order.vo.refund.RefundDetailRespVO">
        <id property="id" column="id"/>
        <result property="refundId" column="refund_id"/>
        <result property="tradeDetailId" column="trade_detail_id"/>
        <result property="refundAmount" column="refundDetailAmount"/>
        <result property="voucherStatus" column="voucher_status"/>
        <result property="refundStatus" column="refundDetailStatus"/>
        <result property="refundTime" column="refund_time"/>
        <result property="refundBaseId" column="refundBaseId"/>
        <result property="voucherCode" column="voucher_code"/>
        <result property="productName" column="product_name"/>
        <result property="tradeDetailPrice" column="tradeDetailPrice"/>
        <result property="actualPrice" column="actual_price"/>
        <result property="fee" column="fee"/>
<!--        <collection property="refundDetailBaseRespList" resultMap="RefundBaseMap"/>-->
    </resultMap>
    <resultMap id="RefundBaseMap" type="com.yc.ship.module.trade.controller.admin.order.vo.refund.RefundDetailBaseRespVO">
        <id property="id" column="refundBaseId"/>
        <result property="refundDetailId" column="id"/>
        <result property="tradeBaseId" column="tradeBaseId"/>
        <result property="refundAmount" column="refundBaseAmount"/>
        <result property="refundStatus" column="refundBaseStatus"/>
        <result property="useStatus" column="use_status"/>
        <result property="platSupplierRefundId" column="plat_supplier_refund_id"/>
        <result property="platSupplierOrderId" column="plat_supplier_order_id"/>
        <result property="supplierVoucherCode" column="supplier_voucher_code"/>
        <result property="productBaseId" column="product_base_id"/>
        <result property="productBaseName" column="product_base_name"/>
        <result property="productResourceId" column="product_resource_id"/>
        <result property="productResourceName" column="product_resource_name"/>
        <result property="supplierProductId" column="supplier_product_id"/>
        <result property="projectName" column="project_name"/>
        <result property="productResourcePrice" column="product_resource_price"/>
        <result property="supplierId" column="supplier_id"/>
        <result property="supplierName" column="supplier_name"/>
        <result property="tradeBasePrice" column="tradeBasePrice"/>
    </resultMap>

    <!-- 1、OTA推送查询，1、根据门票ID查询 -->
    <select id="getDetailInfoByDetailId" resultType="java.util.Map">
        SELECT
            tor.id orderId,
            tor.external_order_no,
            td.id detailId,
            td.id check_id,
            tor.source_id,
            tor.sell_method,
            td.voucher_code voucherCode,
            tor.item_id,
            tor.order_no orderNo,
            ps.product_code ticketCode,
            ps.id productId,
            td.validity_start_date ticketStartDate,
            td.validity_end_date ticketEndDate,
            td.voucher_status voucherStatus
        FROM
        trade_detail td
        INNER JOIN product_spu ps ON td.product_id = ps.id
        <if test="voucherId != null and voucherId != ''">
            AND td.id = #{voucherId}
        </if>
        INNER JOIN trade_order tor ON td.order_id = tor.id
        <if test="orderId != null and orderId != ''">
            AND tor.id = #{orderId}
        </if>
    </select>

    <select id="getOneByCardNo" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        select d.* from trade_detail d inner join trade_visitor v on d.id = v.detail_id
                                       INNER JOIN trade_order o on o.id = d.order_id
            where d.order_id = #{orderId} and v.credential_no = #{cardNo} and o.sell_method in (0,1,6,7) limit 1
    </select>

    <select id="getOneByCardNoAndChannelId" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        SELECT
        DISTINCT d.*
        FROM
        trade_order o
        INNER JOIN trade_detail d ON d.order_id = o.id
        INNER JOIN trade_visitor v ON v.detail_id = d.id
        inner join trade_detail_base tdb on d.id = tdb.detail_id
        inner join product_check_channel pcc on tdb.product_base_id = pcc.product_id and pcc.deleted=0
        WHERE
        d.validity_start_date <![CDATA[ <= ]]> CURDATE() and  d.validity_end_date <![CDATA[ >= ]]> CURDATE()
        and d.voucher_status in (1,2,3,8,9)
        and tdb.use_status in (1,2,8,9)
        and o.sell_method in (0,1,6,7)
        and v.credential_no = #{cardNo}
        <if test="channelId != null">
            and pcc.channel_id = #{channelId}
        </if>
        and v.credential_type in (0,2)
        limit 1
    </select>

    <select id="getOneByVoucherCode" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        SELECT
            DISTINCT t1.*
        FROM
            trade_detail t1
        WHERE
            t1.voucher_code = #{voucherCode}
    </select>

    <update id="updateImgByVoucherCode">
        update trade_detail set faceimg=#{url}  WHERE voucher_code = #{voucherCode}
    </update>

    <select id="getOneCheckGateQuery" resultType="com.yc.ship.module.trade.controller.admin.order.vo.rule.GateCheckDetailRespVO">
        SELECT
        t2.credential_no cardNo,t3.payment_date orderCreateTime,t1.use_date travelDate,t3.order_no orderNo,t3.pay_amount orderAmount,t1.faceimg imageUrl
        FROM
        trade_detail t1
        INNER JOIN trade_visitor t2 ON t1.id = t2.detail_id
        inner join trade_order t3 on t1.order_id = t3.id
        WHERE t1.voucher_code = #{voucherCode}
    </select>
    <select id="getProductTag4" resultType="java.lang.String">
        SELECT product_tag4 FROM product_spu WHERE id = #{productId}
    </select>
    <select id="getOneByVoucherCodePlat" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        SELECT  *
        FROM
            trade_detail
        WHERE
            voucher_code = #{voucherCode}
    </select>

    <select id="getListByVoucherCodePlat" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        SELECT
        DISTINCT t3.*
        FROM
        trade_detail t1
        INNER JOIN trade_detail_base t2 ON t1.id = t2.detail_id
        inner JOIN trade_detail t3 ON t2.supplier_voucher_code = t3.voucher_code
        WHERE
        t1.voucher_code in
        <foreach collection="voucherCodes" item="item" separator=","  open="(" close=")">
            #{item}
        </foreach>
    </select>
    <select id="getListByVoucherCodeOtc" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        SELECT
        DISTINCT t3.*
        FROM
        trade_detail t1
        INNER JOIN trade_detail_base t2 ON t1.id = t2.detail_id
        inner JOIN trade_detail t3 ON t2.supplier_voucher_code = t3.voucher_code
        WHERE
        t3.voucher_code in
        <foreach collection="voucherCodes" item="item" separator=","  open="(" close=")">
            #{item}
        </foreach>
    </select>

    <!-- 产品相关信息 -->

    <select id="getProductSupInfo"
            resultType="com.yc.ship.module.product.api.dto.ProductGroupRespDTO">
        SELECT
        pg.id,
        pg.product_id productId,
        pg.product_base_id productBaseId,
        pg.product_base_type productBaseType,
        pg.sku_id skuId,
        pg.project_id projectId,
        pg.specification_id specificationId,
        pg.first_resource_id firstResourceId,
        pg.cost_price costPrice,
        pg.sale_price salePrice,
        pg.spec_type specType,
        pg.need_choose needChoose,
        pg.max_num maxNum,
        p.product_name productName,
        pb.can_repeat_buy canRepeatBuy,
        pb.`name` productBaseName,
        pp.`name` projectName,
        pp1.`name` specificationName,
        pp1.sort specSort
        FROM
        product_group pg
        INNER JOIN product_spu p ON p.id = pg.product_id
        INNER JOIN product_base pb ON pb.id = pg.product_base_id
        INNER JOIN product_project pp ON pp.id = pg.project_id
        INNER JOIN product_project pp1 ON pp1.id = pg.specification_id
        WHERE
        pg.deleted = 0
        and pg.product_base_type = 0
        <if test="productId != null and productId != ''">
            AND pg.product_id = #{productId}
        </if>
        ORDER BY pg.id,pg.update_time
    </select>

    <select id="getProductSupInfoByPlanId"
            resultType="com.yc.ship.module.product.api.dto.ProductGroupRespDTO">
        SELECT
        pg.id,
        pg.product_id productId,
        pg.product_base_id productBaseId,
        pg.product_base_type productBaseType,
        pg.sku_id skuId,
        pg.project_id projectId,
        pg.specification_id specificationId,
        pg.first_resource_id firstResourceId,
        pg.cost_price costPrice,
        pg.sale_price salePrice,
        pg.spec_type specType,
        pg.need_choose needChoose,
        pg.max_num maxNum,
        p.product_name productName,
        pb.can_repeat_buy canRepeatBuy,
        pb.`name` productBaseName,
        pp.`name` projectName,
        pp1.`name` specificationName,
        pp1.sort specSort,
        pdetail.sort
        FROM
        product_group pg
        INNER JOIN product_spu p ON p.id = pg.product_id
        INNER JOIN product_base pb ON pb.id = pg.product_base_id
        INNER JOIN product_project pp ON pp.id = pg.project_id
        INNER JOIN product_project pp1 ON pp1.id = pg.specification_id
        left join product_route_plan plan on p.id = plan.product_id
        <if test="planId != null and planId != ''">
            AND plan.id = #{planId}
        </if>
        left join product_route_plan_detail pdetail on plan.id = pdetail.plan_id and pdetail.product_base_id = pb.id
        AND ( pdetail.is_use IS NULL OR pdetail.is_use = 1) and pdetail.deleted=0
        WHERE
        pg.deleted = 0
        and pg.product_base_type = 0
        <if test="productId != null and productId != ''">
            AND pg.product_id = #{productId}
        </if>
        <if test="planId != null and planId != ''">
            AND if(pb.tenant_id = plan.tenant_id,plan.id = #{planId} and pdetail.id is not null,1=1)
        </if>
        ORDER BY pp.sort,pdetail.sort
    </select>

    <!-- 产品相关和规格信息 -->

    <select id="getProductSkuInfo"
            resultType="com.yc.ship.module.product.api.dto.ProductGroupRespDTO">
        SELECT
        odp.id,
        odp.product_id productId,
        odp.product_base_id productBaseId,
        odp.specification_id specificationId,
        odp.cost_price costPrice,
        odp.sale_price salePrice,
        odp.spec_type specType,
        pdp.product_sku_id skuId,
        pdp.sale_price allSalePrice,
        p.product_name productName,
        pp.id projectId,
        pb.`name` productBaseName,
        pb.can_repeat_buy canRepeatBuy,
        pp.`name` specificationName,
        pp.parent_id
        FROM
        ota_distributor_project odp
        INNER JOIN ota_distributor_product pdp ON pdp.id = odp.distributor_product_id
        INNER JOIN product_spu p ON p.id = odp.product_id
        INNER JOIN product_base pb ON pb.id = odp.product_base_id
        INNER JOIN product_project pp ON pp.id = odp.specification_id
        WHERE
        odp.deleted = 0 AND (odp.is_use = 1 or odp.is_use is null)
        <if test="productId != null and productId != ''">
            AND odp.product_id = #{productId}
        </if>
        <if test="distributorId != null and distributorId != ''">
            AND odp.distributor_id = #{distributorId}
        </if>
        <if test="skuId != null and skuId != ''">
            AND pdp.product_sku_id = #{skuId}
        </if>
        ORDER BY odp.id
    </select>


    <select id="selectSpuListByTenantId"
            resultType="com.yc.ship.module.product.api.dto.ProductSpuRespDTO">
        SELECT distinct
        p.id,
        p.product_name productName,
        p.product_code productCode,
        p.product_type productType,
        p.category_id categoryId,
        p.sort_num sortNum,
        p.sale_price salePrice,
        p.cost_price costPrice,
        p.is_validated isValidated,
        odp.is_use isUse,
        odp.is_use_otc isUseOtc,
        pc.full_path_name categoryName
        FROM
        product_spu p
        INNER JOIN ota_distributor_product odp ON odp.product_id = p.id
        INNER JOIN ota_distributor od ON od.id = odp.distributor_id
        INNER JOIN product_category pc ON pc.id = p.category_id
        WHERE
        od.deleted = 0
        AND od.is_use = 1
        AND odp.is_use = 1
        and if(od.self_support = 1, odp.is_use_otc=1, true)
        AND p.is_use = 1
        <if test="categoryId != null and categoryId != ''">
            AND pc.id = #{categoryId}
        </if>
        <if test="useDate != null and useDate != ''">
            and EXISTS (
                select 1 from (
                SELECT product_id as id FROM stock_day_product WHERE is_use = 1 and deleted = 0  and use_date = #{useDate}
                union ALL
                SELECT business_id as id FROM stock_day_config WHERE type = 0 and deleted = 0 and is_use = 1
                and start_date <![CDATA[ <= ]]> #{useDate} AND end_date <![CDATA[ >= ]]> #{useDate}
                ) m where m.id = p.id
            )
        </if>
        <if test='type != null and type != "" and type == "3"'>
            AND p.product_type = 7
        </if>
        AND odp.deleted = 0
        AND p.deleted = 0
        AND od.account_tenant_id = #{tenantId}
        order by if (p.sort_num is null, 9999,p.sort_num), p.create_time desc
    </select>

    <select id="platProductAll"
            resultType="com.yc.ship.module.product.api.dto.ProductSpuRespDTO">
        SELECT distinct
        p.id,
        p.product_name productName,
        p.product_code productCode,
        p.product_type productType,
        p.category_id categoryId,
        p.sort_num sortNum,
        p.sale_price salePrice,
        p.cost_price costPrice,
        p.is_validated isValidated,
        1 isUse,
        1 isUseOtc,
        pc.full_path_name categoryName
        FROM
        product_spu p INNER JOIN product_category pc ON pc.id = p.category_id
        WHERE 1=1
        <if test="productIds!=null">
            and  p.id in
            <foreach collection="productIds" item="item" separator=","  open="(" close=")">
                #{item}
            </foreach>
        </if>
        AND p.deleted = 0
        order by p.create_time desc
    </select>

    <select id="selectSpuOTAListByTenantId"
            resultType="com.yc.ship.module.product.api.dto.ProductSpuRespDTO">
        SELECT * from product_spu WHERE  is_use = 1 AND deleted = 0
        <if test="categoryId != null and categoryId != ''">
            AND category_id = #{categoryId}
        </if>
        <if test='type != null and type != "" and type == "3"'>
             AND product_type = 7
        </if>
        order by if (sort_num is null, 9999,sort_num),create_time desc
    </select>

    <select id="getProductSpuPlat"
            resultType="com.yc.ship.module.product.api.dto.ProductSpuRespDTO">
        SELECT
            ps.*,
            odp.id productBaseId,
            od.id distributorId
        FROM
            product_spu ps
                INNER JOIN ota_distributor_product odp ON ps.id = odp.product_id
                INNER JOIN ota_distributor od ON odp.distributor_id = od.id
        WHERE  ps.id = #{productId} AND od.account_tenant_id = #{tenantId}
        LIMIT 1
    </select>

    <select id="getProductSpu" resultType="com.yc.ship.module.product.api.dto.ProductSpuRespDTO">
        SELECT ps.* FROM product_spu ps WHERE ps.id = #{productId}
    </select>


    <select id="getProductBasicRule" resultType="com.yc.ship.module.product.api.dto.ProductBasicRuleRespDTO">
        SELECT * from product_basic_rule WHERE id = #{productId}
    </select>

    <select id="getProductSaleRule" resultType="com.yc.ship.module.product.api.dto.ProductSaleRuleRespDTO">
        SELECT * from product_sale_rule WHERE id = #{productId}
    </select>

    <select id="getProductRefundRule" resultType="com.yc.ship.module.product.api.dto.ProductRefundRuleRespDTO">
        SELECT * from product_refund_rule WHERE id = #{productId}
    </select>

    <select id="getProductTakeRule" resultType="com.yc.ship.module.product.api.dto.ProductTakeRuleRespDTO">
        SELECT * from product_take_rule WHERE id = #{productId}
    </select>

    <select id="getProductOtherRule" resultType="com.yc.ship.module.product.api.dto.ProductOtherRuleRespDTO">
        SELECT * from product_other_rule WHERE id = #{productId}
    </select>

    <select id="getProductSukList" resultType="com.yc.ship.module.product.api.dto.ProductSkuRespDTO">
        SELECT * from product_sku WHERE product_id = #{productId} AND deleted = 0
    </select>

    <select id="getProductSkuPriceList" resultType="com.yc.ship.module.product.api.dto.ProductSkuRespDTO">
        SELECT product_sku_id id,distributor_product_id,product_id,spec_type,cost_price,sale_price,stock
        from ota_distributor_agency_price WHERE deleted = 0 and product_id = #{productId} AND distributor_id = #{distributorId}
    </select>
    <select id="getProductCheckRule" resultType="com.yc.ship.module.product.api.dto.ProductCheckRuleRespDTO">
        SELECT * from product_check_rule WHERE  id = #{productId}
    </select>

    <select id="getProductTakeRules"
            resultType="com.yc.ship.module.product.api.dto.ProductTakeRuleRespDTO">
        SELECT ptr.*
        FROM trade_order td
        INNER JOIN trade_detail tdl on td.id = tdl.order_id
        INNER JOIN product_spu ps on tdl.product_id = ps.id
        INNER JOIN product_take_rule ptr on ps.id = ptr.id
        where 1= 1
        <if test="orderId != null and orderId != ''">
            AND td.id = #{orderId}
        </if>
        GROUP BY ps.id
    </select>

    <select id="selectInsuranceProductFromOrder"
            resultType="java.util.Map">

        select td.product_id,por.insurance_code,por.insurance_amount,count(1) num
        from trade_detail td
        inner join product_other_rule por on td.product_id = por.id
        <where>
            por.need_insurance = 1 and td.order_id=#{orderId}
        </where>
        GROUP BY
        td.product_id

    </select>

    <select id="selectContractProductFromOrder"
            resultType="java.util.Map">

        select td.product_id,por.contract_id
        from trade_detail td
        inner join product_other_rule por on td.product_id = por.id
        <where>
            por.contract_id != '' and td.order_id=#{orderId}
        </where>
        GROUP BY
        td.product_id

    </select>

    <select id="selectDetailAndVisitor"
            resultMap="MiddleWareDtoResultMap">
        SELECT td.*,tv.detail_id,tv.name,tv.id visitorId,tv.gender,tv.credential_no,tv.credential_type,tv.mobile,tv.ota_detail_id
        FROM trade_detail td
        LEFT JOIN  trade_visitor tv on td.id = tv.detail_id
        <where>
            td.order_id = #{orderId}
            <if test="detailVoucherList!=null">
                and  td.voucher_code in
                <foreach collection="detailVoucherList" item="item" separator=","  open="(" close=")">
                    #{item}
                </foreach>
            </if>
        </where>

    </select>


    <!--获取核销通知失败门票重新推送-->
    <select id="queryNotifyFailedVoucherInfo" resultType="java.util.Map">
        SELECT border.id                  orderId,
               border.external_order_no,
               border.source_id,
               border.sell_method,
               border.item_id,
               border.order_no            orderNo,

               ticket.id                  ticketId,
               ticket.validity_start_date ticketStartDate,
               ticket.validity_end_date   ticketEndDate,
               ticket.voucher_status      voucherStatus,
               ticket.product_id          productId,
               ticket.voucher_code        voucherCode,
               notify0.check_id,
               notify0.create_time
        FROM trade_notify_log notify0
                 INNER JOIN trade_detail ticket on ticket.voucher_code = notify0.voucher_code
                 INNER JOIN trade_order border on border.id = ticket.order_id
                 INNER JOIN trade_check tc ON tc.detail_id = ticket.id
                 LEFT JOIN trade_notify_log notify1 ON notify1.voucher_code = notify0.voucher_code
            AND notify1.notity_status = 1
        WHERE notify0.notity_status = 0
          AND notify0.create_time >= CONCAT(DATE_FORMAT(DATE_ADD(NOW(), INTERVAL - 1 DAY ), '%Y-%m-%d'), ' 00:00:00')
          AND notify1.notity_status IS NULL
        <if test="voucherCode != null and voucherCode != ''">
            AND ticket.voucher_code =  #{voucherCode}
        </if>

        UNION ALL
        SELECT border.id                  orderId,
               border.external_order_no,
               border.source_id,
               border.sell_method,
               border.item_id,
               border.order_no            orderNo,
               ticket.id                  ticketId,
               ticket.validity_start_date ticketStartDate,
               ticket.validity_end_date   ticketEndDate,
               ticket.voucher_status      voucherStatus,
               ticket.product_id          productId,
               ticket.voucher_code        voucherCode,
               tc.id                      check_id,
               tc.create_time             create_time
        FROM trade_detail ticket
                 INNER JOIN trade_order border ON border.id = ticket.order_id
                 INNER JOIN trade_check tc ON tc.detail_id = ticket.id
                 LEFT JOIN trade_notify_log notify ON notify.voucher_code = ticket.voucher_code
        WHERE border.sell_method = 1
          AND ticket.check_status = 1

          AND notify.voucher_code is null
          AND tc.create_time &gt;= CONCAT(DATE_FORMAT(NOW(), '%Y-%m-%d'), ' 00:00:00')
          AND tc.create_time &lt;= CONCAT(DATE_FORMAT(NOW(), '%Y-%m-%d'), ' 23:59:59')
         <if test="voucherCode != null and voucherCode != ''">
                AND ticket.voucher_code =  #{voucherCode}
         </if>

        GROUP BY ticket.id
        ORDER BY create_time DESC
    </select>

    <select id="getTradeDetailWithBaseByCodeAndIdcard" resultMap="MiddleWareDtoResultMap">
        select <include refid="selectColumnId"/>
        from trade_detail td
        inner join trade_detail_base tdb on td.id = tdb.detail_id and td.voucher_status > 0  and td.deleted = 0
        INNER JOIN trade_order tdo  on tdo.id = td.order_id  and tdo.deleted = 0
        left JOIN trade_visitor tv on tv.detail_id = td.id
        <where>
            1=1  and td.validity_start_date   <![CDATA[ <= ]]>  NOW()
            and td.validity_end_date   <![CDATA[ >= ]]>  NOW()
            and td.voucher_status in (1,2,3,8,9)
            and tdo.sell_method != 3 and tdo.sell_method != 4
            <if test="idCard!=null and idCard != ''">
                and  tv.credential_no = #{idCard}
            </if>
            <if test="voucherCode!=null and voucherCode != ''">
                and  td.voucher_code = #{voucherCode}
            </if>
            <if test="channelId != null and channelId != ''">
                and EXISTS (select product_id from product_check_channel p1 where p1.product_id=tdb.product_base_id and  channel_id=#{channelId} and deleted = 0)
            </if>
        </where>
    </select>


    <select id="getPlatByVoucherCode1" resultMap="MiddleWareDtoResultMap">
        select <include refid="selectColumnId"/>
        from trade_detail td
        inner join trade_detail_base tdb on td.id = tdb.detail_id and td.voucher_status > 0  and td.deleted = 0
        INNER JOIN trade_order tdo  on tdo.id = td.order_id  and tdo.deleted = 0
        left JOIN trade_visitor tv on tv.detail_id = td.id
        WHERE  td.validity_start_date   <![CDATA[ <= ]]>  NOW()
        and td.validity_end_date   <![CDATA[ >= ]]>  NOW()
        and td.voucher_status in (1,2,3,8,9)
        and td.voucher_code = #{voucherCode}
    </select>


    <select id="getPlatByVoucherCode2" resultMap="MiddleWareDtoResultMap">
        select <include refid="selectColumnId"/>
        from trade_detail td
        inner join trade_detail_base tdb on td.id = tdb.detail_id and td.voucher_status > 0  and td.deleted = 0
        INNER JOIN trade_order tdo  on tdo.id = td.order_id  and tdo.deleted = 0
        left JOIN trade_visitor tv on tv.detail_id = td.id
        WHERE  td.validity_start_date   <![CDATA[ <= ]]>  NOW()
        and td.validity_end_date   <![CDATA[ >= ]]>  NOW()
        and td.voucher_status in (1,2,3,8,9)
        and td.id IN (
            SELECT t3.id
            FROM trade_detail t1
            INNER JOIN trade_detail_base t2 ON t1.id = t2.detail_id
            LEFT JOIN trade_detail t3 ON t2.supplier_voucher_code = t3.voucher_code
            WHERE t1.voucher_code = #{voucherCode}
        )
    </select>


    <select id="getTradeDetailByCheckId" resultMap="MiddleWareDtoResultMap">
        select <include refid="selectColumnId"/>
        from trade_detail td
        inner join trade_detail_base tdb on td.id = tdb.detail_id
        INNER JOIN trade_order tdo  on tdo.id = td.order_id
        INNER JOIN trade_check_detail tcd on tcd.detail_base_id =tdb.id and tcd.check_id = #{checkId}
        LEFT JOIN trade_visitor tv on tv.detail_id = td.id
    </select>

    <sql id="selectColumnId">
        td.*,tdo.order_no,tdb.id detail_base_id,tdb.detail_id,tdb.product_base_id,tdb.product_base_name,tdb.product_base_type,
        tdb.product_resource_id,tdb.product_resource_name,tdb.supplier_product_id,tdb.supplier_id,
        tdb.supplier_name,tdb.is_system_direct,tdb.use_status,tdb.check_status base_check_status,tdb.verify_time base_verify_time,
        tdb.price base_price,tdb.usage_count,tdb.product_resource_price,tdb.project_id,tdb.project_name,
        tdb.specification_id,tdb.specification_name,tdb.spec_type base_spec_type,tdb.supplier_voucher_code,tdb.plat_supplier_order_id,
        tv.id visitorId,tv.credential_no,tv.credential_type,tv.gender,tv.`name`,tv.mobile,tv.gender
    </sql>

    <select id="selectOrderProduct" resultType="java.util.Map">
        select td.product_id,td.route_plan_id,td.route_plan_group_type,td.product_name,td.actual_price,td.use_date,td.quantity_of_one,count(*) buyCount
        from trade_detail td
        where td.order_id =#{orderId}
        group by td.product_id
    </select>

    <select id="selectOrderProductV2" resultType="java.util.Map">
        select td.product_id,td.route_plan_id,td.route_plan_group_type,td.product_name,td.actual_price,td.use_date,td.quantity_of_one,
        count(if(FIND_IN_SET(td.spec_type,
        <foreach collection="noContainSpecList" item="item" separator=","  open="" close="">
        #{item}
        </foreach> )<![CDATA[<= ]]> 0,1,null)) buyCount
        from trade_detail td
        where td.order_id =#{orderId}
        group by td.product_id
    </select>

    <select id="selectNoCheckCount" resultType="java.lang.Integer">
        select count(1) from trade_detail where order_id = #{orderId} and voucher_status in (1,2,8)
    </select>

    <select id="getMaxOrderNo" resultType="java.lang.Integer">
        select count(1) from trade_order where voyage_id = #{voyageId}
    </select>

    <select id="getOrderDetail"
            resultType="com.yc.ship.module.trade.controller.admin.order.vo.order.TradeDetailRespVO">
        SELECT td.*,tv.detail_id,tv.name,tv.id visitorId,tv.gender,tv.credential_no,tv.credential_type,tv.mobile,tv.ota_detail_id,tv.is_insure
        FROM trade_detail td
        INNER JOIN  trade_visitor tv on td.visitor_id = tv.id
        where 1= 1
        <if test="orderId != null and orderId != ''">
            AND td.order_id = #{orderId}
        </if>
    </select>

    <select id="getOrderDetailByOrderId"
            resultType="com.yc.ship.module.trade.controller.admin.order.vo.order.TradeDetailRespVO">
        SELECT * FROM trade_detail where order_id = #{orderId} and deleted = 0 and product_type =0
    </select>

    <select id="getProductProject" resultType="java.util.Map">
        select pp.id,pp.name
        from product_project pp
        where pp.id =#{projectId}
    </select>

    <select id="selectVisitorOrderProductCount" resultType="java.util.Map">
        select tv.credential_no,count(td.id) total
        from trade_detail td
        INNER JOIN trade_visitor tv on td.id = tv.detail_id
        where td.product_id =#{productId} and td.voucher_status in (0,1,2) and td.use_date = #{useDate}
        <if test="excludeOrderId!=null">
            and td.order_id != #{excludeOrderId}
        </if>
        and tv.credential_no in
        <foreach collection="credentialNoList" item="item" separator=","  open="(" close=")">
            #{item}
        </foreach>
        group by tv.credential_no
        HAVING total>0
    </select>

    <select id="selectPlatDetailByDetailIds" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        select td.*
        from trade_detail_base tdb
            inner join trade_detail td on td.voucher_code = tdb.supplier_voucher_code
        where td.order_id = #{orderId}
        <if test="detailIdList!=null and detailIdList.size()>0">
          and tdb.detail_id in
              <foreach collection="detailIdList" item="id" separator=","  open="(" close=")">
                #{id}
              </foreach>
        </if>
        group by td.id
    </select>

    <select id="getPlatDetailByOrderId" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        select * from trade_detail where order_id = #{orderId} and voucher_status in (1,2,3,4,6,8,9)
    </select>

    <select id="selectChangeDetailList" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        select td.*
        from trade_order_change_detail cd
        inner join trade_detail td on cd.origin_detail_id = td.id
        where cd.order_id = #{orderId} and cd.origin_order_id =#{originOrderId}
    </select>

    <select id="selectToCheckList" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        select td.*
        from trade_detail td inner join trade_order o on o.id = td.order_id and o.sell_method in (0,1,6,7)
          INNER JOIN product_refund_rule rr on rr.id = td.product_id and rr.deleted = 0
        where td.validity_start_date <![CDATA[ <= ]]> #{useDate}
          AND td.validity_end_date <![CDATA[ >= ]]> #{useDate}
          and rr.expire_operate_type = 2 AND td.voucher_status in (1,2,4,8,9)
    </select>

    <select id="selectToAllCheckList" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        SELECT td.* FROM trade_detail td
        INNER JOIN trade_order o ON o.id = td.order_id
        AND o.sell_method IN (0, 1, 6, 7 )
        INNER JOIN trade_detail_base tdb ON td.id = tdb.detail_id
        INNER JOIN product_refund_rule rr ON rr.id = td.product_id
        AND rr.deleted = 0
        WHERE td.validity_end_date <![CDATA[ < ]]> #{useDate}
        AND rr.expire_operate_type = 2
        AND td.voucher_status IN ( 1, 2, 4, 8, 9 )
        AND tdb.use_status IN ( 1, 2, 4, 8, 9 )
    </select>
    <select id="selectToTravlCheckList" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        SELECT td.* FROM trade_detail td
        INNER JOIN trade_order o ON o.id = td.order_id
        AND o.sell_method IN (3,4 )
        INNER JOIN trade_detail_base tdb ON td.id = tdb.detail_id
        INNER JOIN product_refund_rule rr ON rr.id = td.product_id
        AND rr.deleted = 0
        WHERE td.validity_end_date <![CDATA[ < ]]> #{useDate}
        AND rr.expire_operate_type = 2
        AND td.voucher_status IN ( 1, 2, 4, 8, 9 )
        AND tdb.use_status IN ( 1, 2, 4, 8, 9 )
    </select>

    <select id="selectTravelTradeDetail" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        select td.* from trade_detail td
            inner join trade_detail_base db on db.detail_id = td.id
        where db.supplier_voucher_code = #{voucherCode} limit 1
    </select>

    <select id="selectTradeDetailByVistorId" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        select td.* from trade_detail td
            inner join trade_visitor db on db.detail_id = td.id
        where db.id = #{visitorId} limit 1
    </select>

    <select id="selectPlatTradeBaseDetail" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailBaseDO">
        select tdd.* from trade_detail td inner join trade_detail_base tdd on td.id = tdd.detail_id
        where td.voucher_code =  #{voucherCode} and tdd.supplier_product_id is not null and tdd.deleted = 0
        limit 1
    </select>

    <select id="selectDispatchRecord" resultType="java.util.Map">
        select odb.id from dispatch_car_dispatch_order_detail_base odb
        where odb.car_dispatch_id = #{dispatchId} and odb.detail_id = #{detailId} and odb.deleted = 0
        union all
        select dodb.id from dispatch_operate_plan_boat_order_detail_base dodb
        where dodb.plan_id = #{dispatchId} and dodb.detail_id = #{detailId} and dodb.deleted = 0
    </select>


    <select id="getAllUpCategoryById" resultType="com.yc.ship.module.trade.dal.dataobject.order.CategoryRespVO">
        WITH recursive temp AS (
        SELECT c.* FROM product_category c WHERE c.deleted = 0 AND c.use_status = 1
        <choose>
            <when test="type != null">
                AND c.type = #{type}
            </when>
            <otherwise>
                AND c.type = 0
            </otherwise>
        </choose>
        AND c.id =  #{id}
        UNION ALL
        SELECT c.* FROM product_category c
        INNER JOIN temp t2 ON t2.parent_id = c.id WHERE c.deleted = 0 AND c.use_status = 1
        <choose>
            <when test="type != null">
                AND c.type = #{type}
            </when>
            <otherwise>
                AND c.type = 0
            </otherwise>
        </choose>
        ) SELECT
        pc.id, pc.type,
        pc.parent_id parentId,
        pc.cate_name cateName,
        pc.use_status useStatus,
        pc.sort_num sortNum,
        pc.cate_code cateCode,
        pc.full_path_name fullPathName,
        pc.parent_path parentPath,
        pc.create_time createTime
        FROM temp pc group by pc.id
        ORDER BY create_time
    </select>

    <insert id="insertSmsLog">
        INSERT INTO system_sms_send_log (
                `id`,
                `order_no`,
                `sms_config_id`,
                `sms_content`,
                `mobile`,
                `creator`,
                `create_time`,
                `updater`,
                `update_time`,
                `deleted`,
                `result`,
                `status`
        )
        VALUES
        (
        #{smsSendLogDTO.id},
        #{smsSendLogDTO.orderNo},
        #{smsSendLogDTO.smsConfigId},
        #{smsSendLogDTO.smsContent},
        #{smsSendLogDTO.mobile},
        1,
        now(),
        1,
        now(),
        0,
        #{smsSendLogDTO.result},
        #{smsSendLogDTO.status}
        );
    </insert>


    <select id="selectOverdueOrderDetailForRefund" resultType="com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO">
        select td.*
        from trade_detail td
        inner join product_refund_rule ru on td.product_id = ru.id
        where td.voucher_status in (1,2) and td.validity_end_date <![CDATA[ < ]]> #{overdueDay} and ru.expire_operate_type = 3
    </select>

    <select id="selectCheckAmount" resultType="java.math.BigDecimal">
        select sum(td.actual_price) checkAmount
        from trade_detail td
        where td.check_status =1 and td.order_id =#{orderId}
    </select>

    <select id="selectOrderPackProduct" resultType="java.util.Map">
        select td.pack_product_id,sum(td.quantity_of_one) totalQuantity,count(*) buyCount
        from trade_detail td
        where td.order_id =#{orderId}
        group by td.pack_product_id
    </select>

    <select id="selectContractByOrderId" resultType="java.util.Map">
        select order_id,res_code,res_msg,status,contract_no,signing_url,view_url,t1.payment_date paymentDate
        from trade_order t1 left join trade_contract t2 on t1.id = t2.order_id
        where t1.id =#{orderId} and t1.order_status = 6
    </select>



    <select id="queryRoutePlanDetailTimeByPlanId" resultType="java.util.Map">
        SELECT
            TIME_FORMAT(MIN(STR_TO_DATE(start_time, '%H:%i')), '%H:%i') AS startTime,
            TIME_FORMAT(MAX(STR_TO_DATE(start_time, '%H:%i')), '%H:%i') AS endTime
        FROM
            product_route_plan_detail where plan_id = #{planId};
    </select>

    <select id="selectOrderSmsInfo" resultType="com.yc.ship.module.trade.controller.admin.smsSendconfig.vo.SmsSendconfigQueryRespVO">
        select t7.*,t1.group_no groupNo,t2.product_id,t2.product_name,t66.name voyageName,t77.name shipName,t1.order_no,t1.seller_id,t2.use_date,count(distinct t2.id)
        num,t1.source_name,t3.contact_name,t3.mobile,t6.params templateParams,t6.api_template_id,t8.api_key,t8.api_secret,t8.api_url,t8.signature,t8.code channelCode from
        trade_order t1
        inner join trade_detail t2 on t1.id = t2.order_id
        inner join trade_order_user t3 on t3.order_id = t1.id
        inner join product_voyage t66 on t66.id = t1.voyage_id
        inner join resource_route t67 on t66.route_id = t67.id
        inner join resource_ship t77 on t77.id = t1.ship_id
        left join system_sms_product t5 on (t67.id=t5.product_id )
        left join system_sms_sendconfig t7 on t7.id = t5.sms_template_id
        left join system_sms_template t6 on t7.sms_template_id = t6.id
        left join system_sms_channel t8 on t8.id = t6.channel_id
        where  t2.voucher_status in (1,2)
        and t2.deleted = 0
        and t7.deleted = 0
        and t8.deleted = 0
        and t7.is_use = 1
        and t7.send_type=3
        and t6.send_type=#{type}
        and t1.id=#{orderId}
        GROUP BY t1.id

    </select>
    <select id="selectCreateOrderSmsInfo" resultType="com.yc.ship.module.trade.controller.admin.smsSendconfig.vo.SmsSendconfigQueryRespVO">
        select t7.*,t1.group_no groupNo,t2.product_id,t2.product_name,t66.name voyageName,t66.start_time,t66.leave_time,t77.name shipName,t67.name routeName,t1.order_no,t1.seller_id,t2.use_date,count(distinct t2.id) num,t1.source_name,t1.link_man contact_name,t1.link_mobile mobile,t6.params templateParams,t6.api_template_id,t8.api_key,t8.api_secret,t8.api_url,t8.signature,t8.code channelCode from
        trade_order t1
        inner join trade_detail t2 on t1.id = t2.order_id
        inner join trade_order_user t3 on t3.order_id = t1.id
        inner join product_voyage t66 on t66.id = t1.voyage_id
        inner join resource_route t67 on t66.route_id = t67.id
        inner join resource_ship t77 on t77.id = t1.ship_id
        left join system_sms_product t5 on (t67.id=t5.product_id )
        left join system_sms_sendconfig t7 on t7.id = t5.sms_template_id
        left join system_sms_template t6 on t7.sms_template_id = t6.id
        left join system_sms_channel t8 on t8.id = t6.channel_id
        where  t2.voucher_status =0
        and t2.deleted = 0
        and t7.deleted = 0
        and t8.deleted = 0
        and t7.is_use = 1
        and t7.send_type=3
        and t6.send_type=#{type}
        and t1.id=#{orderId}
        GROUP BY t1.id

    </select>
    <select id="getRoutePlanByProductId" resultType="com.yc.ship.module.product.api.dto.RoutePlanRespDTO">
        select p.*
        from product_route_plan p
        where p.product_id = #{productId} and p.deleted =0 and use_start_time <![CDATA[<= ]]> now()
        and use_end_time <![CDATA[>= ]]> now()
        <if test="useStatus != null">
            AND p.use_status = #{useStatus}
        </if>
    </select>
    <select id="getRefundBatchDetails"
            resultMap="RefundDetailMap">
        SELECT
        tf.id,tf.refund_id,tf.trade_detail_id,tf.refund_amount refundDetailAmount,tf.voucher_status,tf.refund_status refundDetailStatus,tf.refund_time,
        tf.fee, td.voucher_code,td.product_id,td.product_name,td.price  tradeDetailPrice,td.actual_price,
        tfb.id refundBaseId,tfb.trade_detail_base_id tradeBaseId,tfb.refund_amount refundBaseAmount,tfb.refund_status refundBaseStatus,tfb.use_status,
        tdb.product_base_id,tdb.product_base_name,tdb.product_resource_id,tdb.product_resource_name,tdb.supplier_product_id,tdb.project_name,tdb.product_resource_price,tdb.supplier_id,tdb.supplier_name,tdb.price tradeBasePrice
        FROM
        trade_refund_detail tf
        INNER JOIN trade_detail td ON tf.trade_detail_id = td.id
        left JOIN trade_refund_detail_base tfb ON tfb.refund_detail_id = tf.id
        left JOIN trade_detail_base tdb ON tfb.trade_detail_base_id = tdb.id
        where 1= 1
        <if test="refundId != null and refundId != ''">
            AND tf.refund_id = #{refundId}
        </if>
    </select>
    <select id="getOrderIdDetailCount"
            resultType="com.yc.ship.module.trade.controller.admin.order.vo.order.TradeOrderDetailCountRespVO">
        select product_id, product_name, price, count(1) quantity, product_type
        from trade_detail
        WHERE deleted = 0 and (product_type = 2 or product_type = 1) and order_id = #{orderId}
        GROUP BY product_type, product_id
        order by product_type asc
    </select>
    <select id="selectOrderSpuStatsByOrderIds"
            resultType="com.yc.ship.module.trade.controller.admin.order.vo.order.OrderTotalSpuVO">
        SELECT
            product_id spuId,
            product_name spuName,
            price spuPrice,
            count( 1 ) spuNum,
            sum( actual_price ) spuTotalMoney
        FROM
            trade_detail
        WHERE
            deleted = 0
          AND product_type = 1
        and order_id IN
        <foreach item="item" index="index" collection="orderIds"
                 open="(" separator="," close=")">
            #{item}
        </foreach>
        GROUP BY
            product_id
        ORDER BY
            spuTotalMoney DESC
    </select>

    <update id="updateDeleted">
        UPDATE trade_detail SET deleted = #{deleted},update_time = now() WHERE order_id = #{orderId}
    </update>
</mapper>
