<?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.yami.shop.dao.ProductMapper">

    <resultMap id="BaseResultMap" type="com.yami.shop.bean.model.Product">
        <id property="prodId" column="prod_id"/>
        <result property="prodName" column="prod_name"/>
        <result property="shopId" column="shop_id"/>
        <result property="oriPrice" column="ori_price"/>
        <result property="price" column="price"/>
        <result property="brief" column="brief"/>
        <result property="content" column="content"/>
        <result property="imgs" column="imgs"/>
        <result property="status" column="status"/>
        <result property="scorePrice" column="score_price"/>
        <result property="prodType" column="prod_type"/>
        <result property="activityId" column="activity_id"/>
        <result property="categoryId" column="category_id"/>
        <result property="soldNum" column="sold_num"/>
        <result property="totalStocks" column="total_stocks"/>
        <result property="pic" column="pic"/>
        <result property="deliveryMode" column="delivery_mode"/>
        <result property="deliveryTemplateId" column="delivery_template_id"/>
        <result property="createTime" column="create_time"/>
        <result property="updateTime" column="update_time"/>
        <result property="putawayTime" column="putaway_time"/>
        <result property="version" column="version"/>
    </resultMap>

    <resultMap id="tagProductMap" type="com.yami.shop.bean.app.dto.TagProductDto">
        <result property="id" column="id"/>
        <result property="title" column="title"/>
        <result property="seq" column="seq"/>
        <result property="style" column="style"/>
        <collection property="productDtoList" javaType="list" ofType="com.yami.shop.bean.app.dto.ProductDto">
            <result property="prodId" column="prod_id"/>
            <result property="prodName" column="prod_name"/>
            <result property="shopId" column="shop_id"/>
            <result property="price" column="price"/>
            <result property="brief" column="brief"/>
            <result property="imgs" column="imgs"/>
            <result property="oriPrice" column="ori_price"/>
            <result property="categoryId" column="category_id"/>
            <result property="totalStocks" column="total_stocks"/>
            <result property="pic" column="pic"/>
        </collection>

    </resultMap>

    <resultMap id="productAndSkuListMap" type="com.yami.shop.bean.param.ProductExportParam">
        <id property="prodId" column="prod_id"/>
        <result property="prodName" column="prod_name"/>
        <result property="shopId" column="shop_id"/>
        <result property="oriPrice" column="ori_price"/>
        <result property="transName" column="trans_name"/>
        <result property="brandName" column="brand_name"/>
        <result property="price" column="price"/>
        <result property="brief" column="brief"/>
        <result property="content" column="content"/>
        <result property="imgs" column="imgs"/>
        <result property="status" column="status"/>
        <result property="categoryName" column="category_name"/>
        <result property="shopCategoryName" column="shop_category_name"/>
        <result property="soldNum" column="sold_num"/>
        <result property="totalStocks" column="total_stocks"/>
        <result property="pic" column="pic"/>
        <result property="deliveryMode" column="delivery_mode"/>
        <result property="putawayTime" column="putaway_time"/>
        <collection property="skuList" javaType="list" ofType="com.yami.shop.bean.model.Sku">
            <id column="sku_id" jdbcType="BIGINT" property="skuId" />
            <result column="prod_id" jdbcType="BIGINT" property="prodId" />
            <result column="properties" jdbcType="VARCHAR" property="properties" />
            <result column="sku_prod_name" jdbcType="VARCHAR" property="prodName" />
            <result column="sku_ori_price" jdbcType="DECIMAL" property="oriPrice" />
            <result column="sku_price" jdbcType="DECIMAL" property="price" />
            <result column="weight" jdbcType="DECIMAL" property="weight" />
            <result column="volume" jdbcType="DECIMAL" property="volume" />
            <result column="stocks" jdbcType="INTEGER" property="stocks" />
            <result column="sku_score" jdbcType="INTEGER" property="skuScore" />
            <result column="actual_stocks" jdbcType="INTEGER" property="actualStocks" />
            <result column="status" jdbcType="TINYINT" property="status" />
            <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
            <result column="rec_time" jdbcType="TIMESTAMP" property="recTime" />
            <result column="party_code" jdbcType="VARCHAR" property="partyCode" />
            <result column="model_id" jdbcType="VARCHAR" property="modelId" />
            <result column="sku_pic" jdbcType="VARCHAR" property="pic" />
            <result column="sku_name" jdbcType="VARCHAR" property="skuName" />
            <result column="is_delete" jdbcType="INTEGER" property="isDelete"/>
        </collection>

    </resultMap>

    <resultMap id="ProdResultMap" type="com.yami.shop.bean.app.dto.ProductDto">
        <id column="prod_id" jdbcType="BIGINT" property="prodId"/>
        <result column="prod_name" jdbcType="VARCHAR" property="prodName"/>
        <result column="pic" jdbcType="VARCHAR" property="pic"/>
    </resultMap>

    <sql id="productDtoWithNoContent_SQL">
        p.`prod_id`,
        p.`shop_id`,
        p.`prod_name`,
        p.`pic`,
        p.`price`,
        p.`ori_price`,
        p.`brief`,
        p.`imgs`,
        p.`category_id`,
        p.`total_stocks`,
        p.status
    </sql>

    <sql id="prodWithNoContent_SQL">
        p.prod_id,
        p.pic,
        p.prod_name,
        p.price,
        p.brief,
        p.shop_id,
        p.status
    </sql>

    <update id="updateStocks" parameterType="com.yami.shop.bean.model.Product">
        update tz_prod set total_stocks = total_stocks - #{prod.totalStocks} ,version = version + 1 where prod_id = #{prod.prodId} and #{prod.totalStocks} &lt;= total_stocks
    </update>

    <select id="getProductByProdNameAndShopId" resultType="com.yami.shop.bean.model.Product">
        select * from tz_prod where prod_name = #{prodName} and shop_id = #{shopId} and p.`is_delete`=0
    </select>

    <select id="doGetById" resultType="com.yami.shop.bean.model.Product">
        SELECT
            tp.prod_id,
            tp.prod_name,
            tp.shop_id,
            tp.brand_id,
            tp.brand_name,
            tp.ori_price,
            tp.price,
            tp.score_price,
            tp.brief,
            tp.video,
            tp.pic,
            tp.content,
            tp.imgs,
            tp.status,
            tp.is_delete,
            tp.shop_category_id,
            tp.category_id,
            tp.hb_front_category_id,
            tp.sold_num,
            tp.delivery_mode,
            tp.delivery_template_id,
            tp.create_time,
            tp.update_time,
            tp.putaway_time,
            tp.version,
            tp.prod_type,
            tp.activity_id,
            tp.sup_id,
            tp.hb_spu_id,
            tp.hb_status,
            tp.channel_code,
            tp.half_title,
            SUM(tss.shop_sku_stocks) AS total_stocks
        FROM tz_prod tp
                 INNER JOIN tz_shop_sku tss ON tp.prod_id = tss.spu_id
                 INNER JOIN tz_channel_shop tcs ON tss.shop_id = tcs.shop_id AND tcs.channel_id = #{channelId}
        WHERE tp.prod_id = #{prodId}
          AND tp.is_delete = 0
          AND tss.shop_id = #{shopId}
          AND tss.is_delete = 0
        GROUP BY tp.prod_id, tss.shop_id
            LIMIT 1

    </select>

    <select id="doGetByShopId" resultType="com.yami.shop.bean.model.Product">
        SELECT
            tp.prod_id,
            tp.prod_name,
            tp.shop_id,
            tp.brand_id,
            tp.brand_name,
            tp.ori_price,
            tp.price,
            tp.score_price,
            tp.brief,
            tp.video,
            tp.pic,
            tp.content,
            tp.imgs,
            tp.status,
            tp.is_delete,
            tp.shop_category_id,
            tp.category_id,
            tp.hb_front_category_id,
            tp.sold_num,
            tp.delivery_mode,
            tp.delivery_template_id,
            tp.create_time,
            tp.update_time,
            tp.putaway_time,
            tp.version,
            tp.prod_type,
            tp.activity_id,
            tp.sup_id,
            tp.hb_spu_id,
            tp.hb_status,
            tp.channel_code,
            tp.half_title,
            SUM(tss.shop_sku_stocks) AS total_stocks
        FROM tz_prod tp
                 INNER JOIN tz_shop_sku tss ON tp.prod_id = tss.spu_id
        WHERE tp.prod_id = #{prodId}
          AND tp.is_delete = 0
          AND tss.shop_id = #{shopId}
          AND tss.is_delete = 0
        GROUP BY tp.prod_id, tss.shop_id
            LIMIT 1
    </select>


    <update id="returnStock">
        <foreach collection="prodCollect" item="changeStocks" index="prodId" separator=";">
            update tz_prod set total_stocks = total_stocks + #{changeStocks} where prod_id = #{prodId}
        </foreach>
    </update>


    <select id="pageByTagId" resultType="com.yami.shop.bean.app.dto.ProductDto">
        SELECT
        <include refid="prodWithNoContent_SQL"/>
        FROM tz_prod p
        LEFT JOIN tz_prod_tag_reference ptr
        ON ptr.`prod_id` = p.`prod_id`
        LEFT JOIN tz_prod_tag pt
        ON pt.`id` = ptr.`tag_id`
        WHERE pt.`id` = #{tagId}
        AND p.status = 1 and p.`is_delete`=0
        ORDER BY p.`update_time` DESC
    </select>

    <select id="pageByPutawayTime" resultType="com.yami.shop.bean.app.dto.ProductDto">
        SELECT
        <include refid="prodWithNoContent_SQL"/>
        FROM tz_prod p
        WHERE p.`status` = 1 AND p.prod_type =0 and p.`is_delete`=0
        ORDER BY p.putaway_time DESC
    </select>

    <select id="pageByScore" resultType="com.yami.shop.bean.app.dto.ProductDto">
        SELECT p.*
        FROM tz_prod p
        WHERE p.`status` = 1
            and p.prod_type = 3 and p.`is_delete`=0
        ORDER BY p.putaway_time DESC
    </select>

    <select id="moreBuyProdList" resultType="com.yami.shop.bean.app.dto.ProductDto">
        SELECT
        <include refid="prodWithNoContent_SQL"/>
        FROM tz_prod p
        WHERE p.`status` = 1 AND p.prod_type =0
        ORDER BY p.`sold_num` DESC, p.`update_time` DESC
    </select>

    <select id="getSearchProdDtoPageByProdName" resultType="com.yami.shop.bean.dto.SearchProdDto">
        SELECT
        p.prod_id,
        p.prod_name,
        p.pic,
        ss.shop_id AS shop_id,
        SUM(ss.shop_sku_stocks) AS stocks,
        MIN(cp.channel_prod_price) AS price,
        COALESCE(SUM(oi.prod_count), 0) -
        COALESCE(SUM(refund.product_count), 0) AS net_sales_volume
        FROM tz_prod p
        LEFT JOIN tz_sku sku ON p.prod_id = sku.prod_id AND sku.is_delete = 0
        INNER JOIN tz_shop_sku ss ON ss.sku_id = sku.sku_id AND ss.shop_id = #{searchParam.shopId} AND ss.is_delete = 0
        INNER JOIN tz_channel_prod cp ON sku.sku_id = cp.sku_id AND cp.shop_id = #{searchParam.shopId}  AND cp.channel_id = #{searchParam.channelId}  AND cp.is_delete = 0
        LEFT JOIN tz_order_item oi ON p.prod_id = oi.prod_id
        LEFT JOIN tz_order o ON oi.order_number = o.order_number and  o.shop_id = #{searchParam.shopId}  and o.channel_id = #{searchParam.channelId}
        AND o.hb_order_status in (70,80)
        AND o.delete_status = 0
        LEFT JOIN tz_order_refund_sku refund ON oi.order_item_id = refund.order_item_id
        AND refund.order_refund_id IN (
        SELECT refund_id FROM tz_order_refund
        WHERE return_money_sts= 70
        )
        WHERE p.status = 1
        <if test="searchParam.prodName != null">
            and p.prod_name LIKE CONCAT('%',#{searchParam.prodName},'%')
        </if>
        AND p.is_delete = 0
        GROUP BY p.prod_id
        ORDER BY net_sales_volume DESC
    </select>

    <select id="tagProdList" resultMap="tagProductMap">
        SELECT pt.*,
        <include refid="prodWithNoContent_SQL"/>
        FROM tz_prod_tag pt -- 获取分组信息
        LEFT JOIN
        (-- 分组获取各组前6个
        SELECT ptr.* FROM tz_prod_tag_reference ptr
        INNER JOIN tz_prod p3 ON p3.`prod_id` = ptr.`prod_id` AND p3.`status` =1
        WHERE
        (SELECT COUNT(0) FROM tz_prod_tag_reference prt2
        INNER JOIN tz_prod p2 ON p2.`prod_id` = prt2.`prod_id` AND p2.`status` =1
        WHERE prt2.`tag_id` = ptr.`tag_id` AND prt2.`create_time` > ptr.`create_time`)&lt;6
        ORDER BY ptr.`tag_id`,ptr.`create_time` DESC
        )AS temp
        ON temp.`tag_id` = pt.`id`
        LEFT JOIN tz_prod p -- 获取商品详细信息
        ON p.`prod_id` = temp.`prod_id`
        ORDER BY pt.`seq` DESC
    </select>

    <select id="pageByDiscountId" resultType="com.yami.shop.bean.app.dto.ProductDto">
        SELECT p.*
        FROM tz_discount_prod dp
        LEFT JOIN tz_prod p ON dp.prod_id = p.prod_id  AND  p.prod_type =0
        WHERE p.status= 1 AND dp.discount_id = #{discountId}
    </select>

    <select id="listByShopId" resultType="com.yami.shop.bean.app.dto.ProductDto">
        SELECT
        <include refid="prodWithNoContent_SQL"/>
        FROM tz_prod p
        WHERE p.`status` = 1 and p.`is_delete`=0
        <if test="shopId != 0">
            AND p.shop_id = #{shopId}
        </if>
        ORDER BY p.`sold_num` DESC, p.`update_time` DESC
    </select>
    <select id="listBySuitableProdTypeAndCouponIdAndShopId" resultType="com.yami.shop.bean.app.dto.ProductDto">
        SELECT
        <include refid="prodWithNoContent_SQL"/>
        FROM
        tz_prod p
        WHERE p.`status` = 1 and p.`is_delete`=0
        <if test="shopId != 0">
        AND p.shop_id = #{shopId}
        </if>
        AND p.`prod_id`
        <if test="suitableProdType == 1">
            IN
        </if>
        <if test="suitableProdType == 2">
            NOT IN
        </if>
        (SELECT
        cp.`prod_id`
        FROM
        tz_coupon_prod cp
        WHERE cp.`coupon_id` = #{couponId})
        ORDER BY p.`sold_num` DESC,p.`update_time` DESC
    </select>

    <select id="collectionProds" resultType="com.yami.shop.bean.app.dto.ProductDto">
        SELECT
        <include refid="prodWithNoContent_SQL"/>
        FROM tz_prod p
        WHERE  p.`is_delete`=0 p.`prod_id` IN
        (SELECT uc.`prod_id` FROM tz_user_collection uc
        WHERE uc.user_id = #{userId})
    </select>

    <resultMap id="prodAndSkuListMap" type="com.yami.shop.bean.dto.ProdAndSkuListsDto">
        <result property="prodId" column="prod_id"/>
        <result property="prodName" column="prod_name"/>
        <collection property="skuDtoList" javaType="list" ofType="com.yami.shop.bean.app.dto.SkuDto">
            <result property="stocks" column="stocks"/>
            <result property="skuId" column="sku_id"/>
            <result property="price" column="price"/>
            <result property="skuName" column="sku_name"/>
        </collection>
    </resultMap>
    <select id="getProdAndSkuLists" resultMap="prodAndSkuListMap">
        SELECT
        p.`prod_id`,
        p.`prod_name`,
        s.`price`,
        s.`stocks`,
        s.`sku_id`,
        s.`sku_name`
        FROM
        tz_prod p
        LEFT JOIN tz_sku s ON s.`prod_id` = p.`prod_id`
        WHERE  p.`is_delete`=0 p.`prod_id` IN
        <foreach collection="prodIds" item="prodId" open="(" close=")" separator=",">
            #{prodId}
        </foreach>
    </select>

    <update id="updateProductToGroup">
        UPDATE tz_prod p SET p.`activity_id` = #{groupActivityId},p.`prod_type`=1 WHERE p.`prod_id` IN
        <!--UPDATE tz_prod p SET p.`activity_id` = #{groupActivityId},p.`prod_type`=1 WHERE p.`prod_id` IN-->
        <foreach collection="prodIds" item="prodId" open="(" close=")" separator=",">
            #{prodId}
        </foreach>
    </update>

    <update id="updateProductToUnGroup">
        UPDATE tz_prod p SET p.`activity_id` = NULL,p.`prod_type`=0 WHERE p.`prod_id` =#{prodId}
        <!--UPDATE tz_prod p SET p.`group_activity_id` = 0 WHERE p.`prod_id` =#{prodId}-->
    </update>

    <update id="updateToUnGroupByGroupActivityId">
      UPDATE tz_prod p SET p.`activity_id` = NULL,p.`prod_type`=0  WHERE p.`activity_id` =#{groupActivityId}
        <!--UPDATE tz_prod p SET p.`group_activity_id` = 0 WHERE p.`activity_id` =#{groupActivityId}-->
    </update>

    <select id="listByActivityId" resultType="com.yami.shop.bean.model.Product">
        SELECT * FROM tz_prod p WHERE p.`activity_id` = 4 AND p.`prod_type` = 1 AND p.`status` = 1
        <!--SELECT * FROM tz_prod p WHERE p.`group_activity_id` = #{groupActivityId} AND p.`status` = 1-->
    </select>

    <update id="updateToApply">
        update tz_prod p set p.status = 3,p.update_time=now() where p.prod_id = #{prodId}
    </update>

    <update id="updateToShopOffline">
        update tz_prod p set p.status = 0,p.update_time=now() where p.prod_id = #{prodId}
    </update>

    <update id="updateToOffline">
        update tz_prod p set p.status = 2,p.update_time=now() where p.prod_id = #{prodId}
    </update>

    <update id="updateSoldNum">
        <foreach collection="orderItems" item="orderItem" separator=";">
            update tz_prod p set p.sold_num = p.sold_num + #{orderItem.prodCount},p.update_time=now() where p.prod_id = #{orderItem.prodId}
        </foreach>
    </update>

    <update id="offlineProdByShopId">
        UPDATE tz_prod p SET p.`status` = 0 WHERE p.`shop_id` = #{shopId} AND p.`status` = 1
    </update>
    <select id="getcouponProdList" resultMap="ProdResultMap">
        SELECT prod_id,prod_name,pic FROM tz_prod
        WHERE shop_id = #{shopId}
        <if test="ids != null">
            AND prod_id NOT IN
            <foreach collection="ids" item="id" open="(" close=")" separator=",">
                #{id}
            </foreach>
        </if>
        LIMIT 0,3
    </select>
    <select id="getPageAndShopName" resultType="com.yami.shop.bean.model.Product">
        SELECT p.*,s.shop_name FROM tz_prod p
        LEFT JOIN tz_shop_detail s
        ON p.shop_id = s.shop_id
        <where>
            p.status != -1 AND prod_type = 0 and p.`is_delete`=0
            <if test="product.status != null">
                AND p.status = #{product.status}
            </if>
            <if test="product.prodName != null">
                AND p.prod_name LIKE concat('%',#{product.prodName},'%')
            </if>
            <if test="product.shopName != null">
                AND s.shop_name LIKE concat('%',#{product.shopName},'%')
            </if>
            <if test="product.categoryId != null">
                AND p.category_id = #{product.categoryId}
            </if>
        </where>
        ORDER BY putaway_time DESC
    </select>
    <select id="getProdsByOrderNumber" resultType="com.yami.shop.bean.param.ProdOrderParam">
        SELECT oi.*,p.category_id FROM tz_order_item oi
        LEFT JOIN tz_prod p ON p.`prod_id` = oi.`prod_id`
        WHERE oi.order_number = #{orderNumber}
    </select>

    <select id="listProdsByProdParam" resultMap="productAndSkuListMap">
        SELECT p.*,s.*,s.prod_name AS sku_prod_name,s.pic AS sku_pic,s.ori_price AS sku_ori_price,s.price AS sku_price,
               b.brand_name,t.trans_name,stc.category_name as shop_category_name,tc.category_name
        FROM
            tz_prod p
        LEFT JOIN
            tz_brand b ON b.`brand_id` = p.`brand_id`
        LEFT JOIN
            tz_transport t ON t.`transport_id` = p.`delivery_template_id`
        LEFT JOIN
            tz_sku s ON s.`prod_id` = p.`prod_id`
        LEFT JOIN
            tz_category tc ON tc.`category_id` = p.`category_id`
        LEFT JOIN
            tz_category stc ON stc.`category_id` = p.`shop_category_id`
        WHERE s.`is_delete` = 0 and p.`is_delete`=0 AND p.`status` = #{productParam.status} AND p.shop_id = #{productParam.shopId}
    </select>

    <select id="pageProducts" resultType="com.yami.shop.bean.model.Product">
        SELECT
            prod_name,prod_id,score_price,shop_category_id,pic,video,content,activity_id,delivery_mode,price,
            shop_id,brief,imgs,putaway_time,sold_num,total_stocks,update_time,prod_type,
            VERSION,ori_price,create_time,brand_id,delivery_template_id,category_id,STATUS
        FROM
            tz_prod p
        <where>
            shop_id = #{product.shopId} and  STATUS = 1 AND prod_type = 0 and p.`is_delete`=0
            <if test="product.prodName != null">
                AND p.prod_name LIKE concat('%',#{product.prodName},'%')
            </if>
            <if test="product.isDistribution != null and product.isDistribution == 1">
                AND p.`prod_id` NOT IN (SELECT prod_id FROM `tz_distribution_prod`)
            </if>
            <if test="product.shopCategoryId != null">
                AND p.shop_category_id = #{product.shopCategoryId}
            </if>
        </where>
        ORDER BY putaway_time DESC
    </select>

    <select id="getSearchProdDtoPageByCategory" resultType="com.yami.shop.bean.dto.SearchProdDto">
        select
        any_value(p.prod_id) as prod_id,
        any_value(p.pic) as pic,
        any_value(p.prod_name) as prod_name,
        any_value(p.price) as price,
        any_value(p.brief) as brief,
        count(pc.prod_comm_id) as prod_comm_number,
        count( CASE WHEN evaluate = 0 THEN prod_comm_id ELSE null END ) AS praise_number
        from
        tz_prod p
        left join tz_prod_comm pc on p.prod_id=pc.prod_id and pc.`status`=1
        where 1 = 1 and p.`status` = 1 and prod_type = 0 and p.`is_delete`=0

        <if test="searchParam.prodName != null and searchParam.prodName != ''">
            and prod_name like concat('%',#{searchParam.prodName} ,'%')
        </if>
        <if test="searchParam.shopId != null">
            and p.shop_id = #{searchParam.shopId}
        </if>

        <if test="searchParam.categoryId != null">
            and p.category_id = #{searchParam.categoryId}
        </if>
        <if test="searchParam.shopCategoryId != null">
            and p.shop_category_id = #{searchParam.shopCategoryId}
        </if>
        <if test="searchParam.prodType != null">
            and p.prod_type = #{searchParam.prodType}
        </if>
        GROUP BY p.prod_id
        <if test="searchParam.sort == 0">
            ORDER BY any_value(p.update_time)
        </if>
        <if test="searchParam.sort == 1">
            ORDER BY any_value(p.sold_num)
        </if>
        <if test="searchParam.sort == 2">
            ORDER BY any_value(p.price)
        </if>
        <if test="searchParam.orderBy == 0">
            asc
        </if>
        <if test="searchParam.orderBy == 1">
            desc
        </if>
        <if test="searchParam.sort == 1">
            , any_value(p.prod_id) DESC
        </if>

    </select>
    <update id="updateProduct">
        UPDATE tz_prod
        SET shop_category_id=#{product.shopCategoryId}, pic=#{product.pic}, video=#{product.video}, content=#{product.content},
            delivery_mode=#{product.deliveryMode},price=#{product.price}, prod_name=#{product.prodName}, brief=#{product.brief},
            imgs=#{product.imgs}, total_stocks=#{product.totalStocks}, update_time=#{product.updateTime},ori_price=#{product.oriPrice},
            delivery_template_id=#{product.deliveryTemplateId}, category_id=#{product.categoryId}, status=#{product.status},brand_id=#{product.brandId}
         WHERE prod_id=#{product.prodId}
    </update>
    <update id="offlineProdByCategoryId">
        UPDATE
          tz_prod
        SET
          `status` = 0
        WHERE `category_id` = #{categoryId}
    </update>

    <select id="queryShop" resultType="com.yami.shop.bean.model.ShopDetail">
        select
            sd.shop_id shopId,
            shop_name shopName,
            ( 6371 * acos( cos( radians(#{lat}) ) * cos( radians( shop_lat ) ) * cos( radians( shop_lng ) - radians(#{lon}) ) + sin( radians(#{lat}) ) * sin( radians( shop_lat ) ) ) ) AS distance
        from
            tz_shop_detail sd
        right join tz_transport2 tp on tp.shop_id = sd.shop_id
        having distance <![CDATA[ <= ]]> #{distance}
        order by distance
    </select>

    <select id="pageByPutawayTimeNew" resultType="com.yami.shop.bean.app.dto.ProductDto">
        SELECT
            p.prod_id,
            p.imgs pic,
            p.prod_name,
            p.price,
            p.brief,
            p.shop_id,
            p.status
        FROM tz_prod p
        left join tz_shop_detail sd on p.shop_id = sd.shop_id
        WHERE p.`status` = 1 AND p.prod_type =0 and p.`is_delete`=0
        <if test="list != null">
            and p.shop_id in
            <foreach collection="list" item="item" separator="," open="(" close=")">
                #{item}
            </foreach>
        </if>
        ORDER BY p.putaway_time DESC
    </select>

    <select id="getSearchProdDtoPageByProdNameNew" resultType="com.yami.shop.bean.dto.SearchProdDto">
        select
        sum(tss.shop_sku_stocks) as stocks,
        any_value(p.prod_id) as prod_id,
        any_value(p.imgs) as pic,
        any_value(p.prod_name) as prod_name,
        MIN(tcp.channel_prod_price) as price,
        any_value(p.brief) as brief,
        any_value ( tss.shop_id ) AS shopId,

        ls.name as selfLabel,
        lr.name as returnLabel,
        lh.name as hotLabel,

        count(pc.prod_comm_id) as prod_comm_number,
        count( CASE WHEN evaluate = 0 THEN prod_comm_id ELSE null END ) AS praise_number,
        (6371 * acos(cos(radians(#{searchParam.lat})) * cos(radians(shop_lat)) * cos(radians(shop_lng) -
        radians(#{searchParam.lon}) ) + sin(radians(#{searchParam.lat})) * sin(radians(shop_lat)))) distance
        from
        tz_shop_sku tss
        LEFT JOIN tz_prod p ON p.prod_id = tss.spu_id
        LEFT JOIN tz_shop_detail sd ON sd.shop_id = tss.shop_id
        LEFT JOIN tz_prod_comm pc ON p.prod_id = pc.prod_id
        LEFT JOIN tz_channel_prod tcp ON tss.sku_id = tcp.sku_id

        LEFT JOIN tz_category_prod cp on p.prod_id = cp.prod_id
        LEFT JOIN tz_shop_category sc on cp.code = sc.code

        left join tz_label ls on ls.id = tss.self_label_id
        left join tz_label lr on lr.id = tss.return_label_id
        left join tz_label lh on lh.id = tss.hot_label_id

        where 1 = 1 and p.`status` = 1 and p.`is_delete`=0 and tcp.is_delete=0 and tss.shop_id in
        <foreach collection="list" item="item" separator="," open="(" close=")">
            #{item}
        </foreach>
        <if test="searchParam.prodName != null and searchParam.prodName != ''">
            and prod_name like concat('%',#{searchParam.prodName} ,'%')
        </if>
        <if test="searchParam.shopId != null">
            and tss.shop_id = #{searchParam.shopId}
        </if>

        <if test="searchParam.categoryId != null">
            and sc.id = #{searchParam.categoryId}
        </if>
        <if test="searchParam.shopCategoryId != null">
            and p.shop_category_id = #{searchParam.shopCategoryId}
        </if>
        <if test="searchParam.channelId == null or searchParam.channelId == 0">
            and tcp.channel_id = 1
        </if>
        <if test="searchParam.channelId != null and searchParam.channelId != 0">
            and tcp.channel_id = #{searchParam.channelId}
        </if>
        <if test="searchParam.prodType != null and searchParam.isAllProdType == null">
            and p.prod_type = #{searchParam.prodType}
        </if>
        <if test="searchParam.isAllProdType == true">
            and p.prod_type in (0,1,2)
        </if>
        GROUP BY p.prod_id
        HAVING distance <![CDATA[<=]]> #{searchParam.distance}
        <if test="searchParam.sort == 0">
            ORDER BY any_value(p.update_time)
        </if>
        <if test="searchParam.sort == 1">
            ORDER BY any_value(p.sold_num)
        </if>
        <if test="searchParam.sort == 2">
            ORDER BY any_value(p.price)
        </if>
        <if test="searchParam.sort == 3">
            ORDER BY distance
        </if>
        <if test="searchParam.orderBy == 0">
            asc
        </if>
        <if test="searchParam.orderBy == 1">
            desc
        </if>
        <if test="searchParam.sort == 1">
            , any_value(p.prod_id) DESC
        </if>
    </select>
    <select id="getSalesVolume" resultType="java.lang.Integer">
        select ifnull(sum(oi.prod_count),0) from tz_order o
                                                     join tz_order_item oi on oi.order_number=o.order_number
        where oi.prod_id=#{prodId} and o.hb_order_status=80
    </select>
    <select id="getSearchProdDtoPageByProdName2" resultType="com.yami.shop.bean.dto.SearchProdDto">
        SELECT
        t.*,
        t1.salesVolume
        FROM (
        SELECT
        sum(tss.shop_sku_stocks)  AS stocks,
        ANY_VALUE(p.prod_id) AS prod_id,
        ANY_VALUE(p.pic) AS pic,
        ANY_VALUE(p.prod_name) AS prod_name,
        ANY_VALUE(p.price) AS price,
        ANY_VALUE(p.brief) AS brief,
        ANY_VALUE(p.shop_id) AS shopId,
        ANY_VALUE(p.update_time) AS update_time
        FROM
        tz_prod p
        LEFT JOIN tz_sku sku ON p.prod_id = sku.prod_id
        left join tz_shop_sku tss on sku.sku_id = tss.sku_id
        LEFT JOIN tz_category_prod cp on p.prod_id = cp.prod_id
        LEFT JOIN tz_shop_category sc on cp.code = sc.code
        WHERE 1 = 1
        AND p.`status` = 1 and p.`is_delete`=0
        <if test="searchParam.prodName != null and searchParam.prodName != ''">
            AND prod_name LIKE CONCAT('%', #{searchParam.prodName}, '%')
        </if>
        <if test="searchParam.shopId != null">
            AND p.shop_id = #{searchParam.shopId}
        </if>
        <if test="searchParam.categoryId != null">
            AND sc.id = #{searchParam.categoryId}
        </if>
        <if test="searchParam.shopCategoryId != null">
            AND p.shop_category_id = #{searchParam.shopCategoryId}
        </if>
        <if test="searchParam.prodType != null and searchParam.isAllProdType == null">
            AND p.prod_type = #{searchParam.prodType}
        </if>
        <if test="searchParam.isAllProdType == true">
            AND p.prod_type IN (0,1,2)
        </if>
        GROUP BY
        p.prod_id
        ) t
        LEFT JOIN (
        SELECT
        oi.prod_id,
        IFNULL(SUM(oi.prod_count), 0) AS salesVolume
        FROM
        tz_order o
        JOIN
        tz_order_item oi ON oi.order_number = o.order_number
        WHERE
        o.hb_order_status = 80
        GROUP BY
        oi.prod_id
        ) t1 ON t.prod_id = t1.prod_id
        <!-- 修改点：合并排序条件 -->
        <choose>
            <when test="searchParam.sort != null">
                <choose>
                    <when test="searchParam.sort == 0">
                        ORDER BY t.update_time
                        <if test="searchParam.orderBy != null">
                            <choose>
                                <when test="searchParam.orderBy == 0">ASC</when>
                                <when test="searchParam.orderBy == 1">DESC</when>
                            </choose>
                        </if>
                    </when>
                    <when test="searchParam.sort == 1">
                        ORDER BY t1.salesVolume
                        <if test="searchParam.orderBy != null">
                            <choose>
                                <when test="searchParam.orderBy == 0">ASC</when>
                                <when test="searchParam.orderBy == 1">DESC</when>
                            </choose>
                        </if>
                        , t.prod_id DESC
                    </when>
                    <when test="searchParam.sort == 2">
                        ORDER BY t.price
                        <if test="searchParam.orderBy != null">
                            <choose>
                                <when test="searchParam.orderBy == 0">ASC</when>
                                <when test="searchParam.orderBy == 1">DESC</when>
                            </choose>
                        </if>
                    </when>
                </choose>
            </when>
            <otherwise>
                <!-- 默认排序（当sort未指定时） -->
                ORDER BY t.update_time DESC
            </otherwise>
        </choose>
    </select>

    <select id="listProdByCategoryIdAndShopId" parameterType="com.yami.shop.bean.dto.ProdByCategoryIdAndShopIdDTO" resultType="com.yami.shop.bean.model.Product">
        SELECT
            p.*
        FROM
            tz_prod p
                INNER JOIN tz_category c ON p.shop_category_id = c.category_id
        WHERE
            c.parent_id = #{prodByCategoryIdAndShopIdDTO.categoryId}
          AND p.STATUS = 1 and p.`is_delete`=0
          AND c.STATUS = 1
          AND  p.shop_id = #{prodByCategoryIdAndShopIdDTO.shopId}
        ORDER BY
            p.create_time DESC
    </select>

    <select id="listProdByCIdAndSId" parameterType="com.yami.shop.bean.dto.ProdByCategoryIdAndShopIdDTO" resultType="com.yami.shop.bean.param.CategoryProductParam" >

        SELECT
        tp.prod_id,
        tp.prod_name,
        tcp.shop_id,
        MIN(cp.channel_prod_price) AS price,
        tp.pic,
        sum(tss.shop_sku_stocks) AS total_stocks,

        COALESCE ((
        SELECT
        SUM( oi2.prod_count )
        FROM
        tz_order_item oi2
        INNER JOIN tz_order o2 ON o2.order_number = oi2.order_number
        WHERE
        oi2.shop_id = #{prodByCategoryIdAndShopIdDTO.shopId}
        AND oi2.prod_id = tp.prod_id
        AND o2.hb_order_status IN ( 20, 30, 40, 70, 80 )
        AND o2.delete_status = 0
        ),
        0
        ) AS sales_volume

        FROM tz_prod tp
        INNER JOIN tz_category_prod tcp ON tp.prod_id = tcp.prod_id
        AND tcp.is_delete = 0 AND tcp.shop_id = #{prodByCategoryIdAndShopIdDTO.shopId}
        and tcp.category_id = #{prodByCategoryIdAndShopIdDTO.categoryId}
        LEFT JOIN tz_shop_sku tss ON tss.spu_id = tp.prod_id and tss.shop_id =  #{prodByCategoryIdAndShopIdDTO.shopId}
        INNER JOIN tz_channel_prod cp ON cp.shop_id = tcp.shop_id
        AND cp.sku_id = tss.sku_id
        AND cp.is_delete = 0
        <if test="prodByCategoryIdAndShopIdDTO.channelId == null or prodByCategoryIdAndShopIdDTO.channelId == 0">
            and cp.channel_id = 1
        </if>
        <if test="prodByCategoryIdAndShopIdDTO.channelId != null and prodByCategoryIdAndShopIdDTO.channelId != 0">
            and cp.channel_id = #{prodByCategoryIdAndShopIdDTO.channelId}
        </if>
        AND cp.channel_prod_price IS NOT NULL
        WHERE tp.STATUS = 1
        AND tp.`is_delete` = 0
        GROUP BY tp.prod_id
        ORDER BY
        sales_volume DESC,  price ASC
    </select>

<!--    <resultMap id="listProdByCIdAndSIdMap" type="com.yami.shop.bean.param.CategoryProductParam">-->
<!--        <id property="prodId" column="prod_id"/>-->
<!--        <result property="prodName" column="prod_name"/>-->
<!--        <result property="shopId" column="shop_id"/>-->
<!--        <result property="price" column="price"/>-->
<!--        <result property="pic" column="pic"/>-->
<!--        <result property="salesVolume" column="sales_volume"/>-->
<!--        <result property="totalStocks" column="total_stocks"/>-->
<!--        <collection property="skuList" javaType="list" ofType="com.yami.shop.bean.model.Sku">-->
<!--            <id column="sku_id" jdbcType="BIGINT" property="skuId" />-->
<!--            <result column="prod_id" jdbcType="BIGINT" property="prodId" />-->
<!--            <result column="properties" jdbcType="VARCHAR" property="properties" />-->
<!--            <result column="sku_prod_name" jdbcType="VARCHAR" property="prodName" />-->
<!--            <result column="sku_ori_price" jdbcType="DECIMAL" property="oriPrice" />-->
<!--            <result column="sku_price" jdbcType="DECIMAL" property="price" />-->
<!--            <result column="weight" jdbcType="DECIMAL" property="weight" />-->
<!--            <result column="volume" jdbcType="DECIMAL" property="volume" />-->
<!--            <result column="stocks" jdbcType="INTEGER" property="stocks" />-->
<!--            <result column="sku_score" jdbcType="INTEGER" property="skuScore" />-->
<!--            <result column="actual_stocks" jdbcType="INTEGER" property="actualStocks" />-->
<!--            <result column="status" jdbcType="TINYINT" property="status" />-->
<!--            <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />-->
<!--            <result column="rec_time" jdbcType="TIMESTAMP" property="recTime" />-->
<!--            <result column="party_code" jdbcType="VARCHAR" property="partyCode" />-->
<!--            <result column="model_id" jdbcType="VARCHAR" property="modelId" />-->
<!--            <result column="sku_pic" jdbcType="VARCHAR" property="pic" />-->
<!--            <result column="sku_name" jdbcType="VARCHAR" property="skuName" />-->
<!--            <result column="is_delete" jdbcType="INTEGER" property="isDelete"/>-->
<!--        </collection>-->

<!--    </resultMap>-->


    <select id="listProdByCategoryIdAndShopId2" parameterType="com.yami.shop.bean.dto.ProdByCategoryIdAndShopIdDTO" resultType="com.yami.shop.bean.model.Product">
        select t.*,t1.salesVolume from (
        SELECT
            p.*
        FROM
            tz_prod p
                INNER JOIN tz_category c ON p.shop_category_id = c.category_id
        WHERE
            c.category_id = #{prodByCategoryIdAndShopIdDTO.categoryId}
          AND p.STATUS = 1
          AND c.STATUS = 1
          AND  p.shop_id = #{prodByCategoryIdAndShopIdDTO.shopId}
        ) t left join  (select oi.prod_id,ifnull(sum(oi.prod_count),0) as salesVolume from tz_order o
            join tz_order_item oi on oi.order_number=o.order_number
            where  o.hb_order_status=80  GROUP BY oi.prod_id) t1 on t.prod_id = t1.prod_id
        <if test="prodByCategoryIdAndShopIdDTO.sort == 0">
            ORDER BY p.update_time
        </if>
        <if test="prodByCategoryIdAndShopIdDTO.sort == 1">
            ORDER BY t1.salesVolume
        </if>
        <if test="prodByCategoryIdAndShopIdDTO.sort == 2">
            ORDER BY p.price
        </if>
        <if test="prodByCategoryIdAndShopIdDTO.orderBy == 0">
            asc
        </if>
        <if test="prodByCategoryIdAndShopIdDTO.orderBy == 1">
            desc
        </if>
    </select>


    <select id="selectByHbSpuId" resultType="com.yami.shop.bean.model.Product">
        select * from tz_prod where hb_spu_id = #{hbSpuId} AND is_delete = 0;
    </select>
    <select id="findByProdIdAndShopId" resultType="com.yami.shop.bean.model.ChannelProd">
        select a.* from tz_channel_prod a
        INNER join  tz_sku b  on  b.prod_id = #{prodId} and b.sku_id = a.sku_id and b.is_delete = 0
        where a.shop_id=#{shopId} and a.channel_id = #{channelId} and a.is_delete = 0 ORDER BY a.channel_prod_price  LIMIT 1
    </select>

    <select id="findByProdIdAndShopIdAndPrice" resultType="com.yami.shop.bean.app.dto.ProductDto">
        SELECT
        d.prod_id,
        d.shop_id,
        IFNULL(i.count,0)
        FROM tz_category_prod a  -- 商品类目关联表
        INNER JOIN tz_shop_category b ON a.`code` = b.`code`   -- 商品类目表
        INNER JOIN tz_category_prod c ON b.`code` = c.`code` AND c.shop_id = a.shop_id and c.is_delete =0 -- 商品类目关联表
        INNER JOIN tz_prod d ON c.shop_id = d.shop_id AND c.prod_id = d.prod_id  AND d.`status` = 1 and d.is_delete=0  -- 商品表
        INNER JOIN tz_sku e on  d.prod_id  =  e.prod_id and e.is_delete=0 -- 商品规格表
        INNER JOIN tz_channel_prod f on  d.shop_id =f.shop_id and e.sku_id =f.sku_id and f.is_delete = 0  -- 渠道商品价格表
        and f.channel_prod_price &gt;=#{decreased} and  f.channel_prod_price &lt;=#{increased}
        LEFT JOIN (SELECT count(h.order_item_id) as count,h.prod_id  from  tz_order g LEFT JOIN tz_order_item h on g.order_number = h.order_number where g.refund_status is null and g.delete_status and g.hb_order_status = 80 GROUP BY h.prod_id) i on d.prod_id = i.prod_id -- 统计销量
        WHERE a.prod_id = #{prodId}
        AND d.shop_id = #{shopId}
        AND f.channel_id = #{channelId}
        AND b.`level` = 2
        and a.is_delete =0
        ORDER BY i.count DESC limit 6
    </select>
    <select id="findByProdAndShop" resultType="com.yami.shop.bean.dto.SearchProdDto">
        SELECT
        SUM(tss.shop_sku_stocks) as stocks,
        p.prod_id,
        p.imgs as pic,
        p.prod_name,
        MIN(tcp.channel_prod_price) as price,
        p.brief,
        tss.shop_id AS shopId,
        tss.self_label_id AS selfLabelId,
        tss.return_label_id AS returnLabelId,
        tss.hot_label_id AS hotLabelId,
        COUNT(pc.prod_comm_id) as prod_comm_number,
        COUNT(CASE WHEN pc.evaluate = 0 THEN pc.prod_comm_id ELSE null END) AS praise_number,
        IFNULL(i.count,0)
        FROM tz_prod p
        INNER JOIN tz_shop_sku tss ON p.prod_id = tss.spu_id
        INNER JOIN tz_shop_detail sd ON sd.shop_id = tss.shop_id
        INNER JOIN tz_channel_prod tcp ON tss.sku_id = tcp.sku_id AND tcp.is_delete = 0
        LEFT JOIN tz_prod_comm pc ON p.prod_id = pc.prod_id
        LEFT JOIN tz_category_prod cp ON p.prod_id = cp.prod_id
        LEFT JOIN tz_shop_category sc ON cp.code = sc.code
        LEFT JOIN (SELECT count(h.order_item_id) as count,h.prod_id  from  tz_order g LEFT JOIN tz_order_item h on g.order_number = h.order_number where g.refund_status is null and g.delete_status and g.hb_order_status = 80) i on p.prod_id = i.prod_id -- 统计销量
        WHERE p.status = 1
        AND p.is_delete = 0
        AND (p.shop_id, p.prod_id) IN
        <foreach collection="list" item="item" open="(" close=")" separator=",">
            (#{item.shopId}, #{item.prodId})
        </foreach>
        GROUP BY p.prod_id
        order by  i.count DESC
    </select>


    <select id="similarProdList" resultType="com.yami.shop.bean.vo.SimilarProdListVo">
        SELECT ss.shop_id AS shopId,
        p.prod_id AS prodId,
        p.prod_name AS prodName,
        p.pic,
        min(cha.channel_prod_price) AS channelProdPrice,
        sum(ss.shop_sku_stocks) shopSkuStocks,
        min(ss.sku_id) skuId,
        max(b.basket_count ) as prodCount
        FROM tz_category_prod cp
        INNER JOIN tz_prod p on p.prod_id = cp.prod_id
        LEFT JOIN tz_shop_sku ss on ss.spu_id = cp.prod_id and ss.is_delete = 0 and ss.shop_id = #{shopId}
        INNER JOIN tz_channel_prod cha on cha.sku_id = ss.sku_id and cha.is_delete = 0
        LEFT JOIN tz_basket b ON b.prod_id = p.prod_id AND b.user_id = COALESCE(NULLIF(#{userId}, ''), '0')
        where p.is_delete = 0 and
        cha.channel_id = #{channelId} and cha.shop_id = #{shopId}

        and(cp.code in (select sc.code
        FROM tz_category_prod cp
        LEFT JOIN tz_shop_category sc on cp.code = sc.code
        WHERE sc.level = 2
        and cp.shop_id = #{shopId}
        and sc.is_delete = 0
        and cp.is_delete = 0
        and cp.prod_id = #{prodId}
        GROUP BY sc.code)

        or (
        p.brand_id = (SELECT brand_id FROM tz_prod WHERE prod_id = #{prodId})
        AND EXISTS (SELECT 1
        FROM tz_channel_prod base_cha
        INNER JOIN tz_shop_sku base_ss ON base_cha.sku_id = base_ss.sku_id
        WHERE base_ss.spu_id = #{prodId}
        AND base_cha.channel_id =  #{channelId}
        AND base_cha.is_delete = 0
        AND base_ss.is_delete = 0
        AND cha.channel_prod_price BETWEEN
        base_cha.channel_prod_price * 0.9
        AND base_cha.channel_prod_price * 1.1)
        ))
        AND p.prod_id != #{prodId}
        GROUP BY p.prod_id
    </select>

</mapper>
