<?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.bonus.canteen.core.report.statistics.order.analysis.mapper.ReportAnalysisDishesSaleMapper">

    <sql id="dataPermission">
        <if test="'3'.toString() == authPO.roleType.toString()">
            AND (
            EXISTS(
            SELECT NULL
            FROM mgr_role_canteen it1
            LEFT JOIN mgr_role it2 ON it2.role_id = it1.role_id
            LEFT JOIN mgr_user_role it3 ON it1.role_id = it3.role_id
            WHERE it2.del_flag = 2
            AND it2.role_code = #{authPO.roleCode}
            AND it1.half_select = 1
            AND it3.user_id = #{authPO.userId}
            AND (a.stall_id = it1.data_id)
            )
            OR EXISTS (
            SELECT NULL
            FROM mgr_role_canteen it1
            LEFT JOIN mgr_role it2 ON it2.role_id = it1.role_id
            LEFT JOIN mgr_user_role it3 ON it1.role_id = it3.role_id
            WHERE it2.del_flag = 2
            AND it2.role_code = #{authPO.roleCode}
            AND it1.half_select = 1
            AND it3.user_id = #{authPO.userId}
            AND (a.canteen_id = it1.data_id)
            )
            )
        </if>
        <if test="param.areaIdList != null and param.areaIdList.size() > 0">
            AND ac.area_id in
            <foreach collection="param.areaIdList" item="item" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        <if test="'2'.toString() == authPO.roleType.toString() or '1'.toString() == authPO.roleType.toString()">
            and EXISTS (
            SELECT null
            FROM mgr_role_area it1
            LEFT JOIN mgr_role it2 ON it2.role_id = it1.role_id
            LEFT JOIN mgr_user_role it3 ON it1.role_id = it3.role_id
            WHERE it2.del_flag = 2
            AND it2.role_code = #{authPO.roleCode}
            AND it1.half_select = 1
            AND it3.user_id = #{authPO.userId}
            AND ac.area_id = it1.data_id
            )
        </if>
    </sql>

    <select id="listSummary" resultType="com.bonus.canteen.core.report.statistics.order.analysis.vo.ReportAnalysisDishesSaleVO">
            SELECT
                   t.*,
                    (CASE
                    WHEN #{param.treeType} = 1 THEN
                    IFNULL( c.canteen_name, si.supermarket_name )
                    WHEN #{param.treeType} = 2 THEN
                    s.stall_name ELSE IFNULL( c.canteen_name, si.supermarket_name )
                    END
                    ) AS canteen_stall_name,
                    ar.area_name,

                   round(t.real_amount/t.quantity) avg_amount,
                   d.type_name,

                    ROUND((t.cust_num / total_customers.total_cust_num) * 100, 2) AS purchase_rate,
                    ROUND((t.repurchase_num / t.cust_num) * 100, 2) AS repurchase_rate,
                    ROUND(IFNULL(med.average_star_level,0),2) dishes_star_level
                FROM (
                    SELECT b.*,
                            b.total_quantity AS quantity,
                            CASE b.sales_mode
                                WHEN 2 THEN CONCAT(m.unit_price, 'g')
                                ELSE '份'
                            END AS unit_name,
                            SUM(CASE WHEN b.cust_num > 1 THEN 1 ELSE 0 END) AS repurchase_num
                    FROM (
                            SELECT (CASE
                                    WHEN #{param.treeType} = 1 THEN a.canteen_id
                                    WHEN #{param.treeType} = 2 THEN a.stall_id
                                    ELSE a.canteen_id
                                    END) AS canteen_stall_id,
                                    a.goods_dishes_id,
                                    a.goods_dishes_name,
                                    a.goods_dishes_num,
                                    a.detail_type,
                                    a.sales_mode,
                                    a.type_id,
                                    sum(a.quantity) total_quantity,
                                    sum(a.real_amount) real_amount,
                                    sum(a.cust_num) cust_num
                             FROM report_analysis_dishes_sale a
                            LEFT JOIN alloc_canteen ac ON ac.canteen_id = a.canteen_id
                             <where>
                                 a.detail_type NOT in (3,4,5,6)
                                <if test="param.startDate != null">
                                    <![CDATA[AND a.statistic_date >= #{param.startDate}]]>
                                </if>
                                <if test="param.endDate != null">
                                    <![CDATA[AND a.statistic_date <= #{param.endDate}]]>
                                </if>
                                <if test="param.ageTypes != null and param.ageTypes.size() > 0">
                                    AND a.age_type IN
                                    <foreach collection="param.ageTypes" item="ageType" separator="," open="(" close=")">
                                        #{ageType}
                                    </foreach>
                                </if>
                                <if test="param.canteenId != null">
                                    AND a.canteen_id = #{param.canteenId}
                                </if>
                                <if test="param.stallId != null">
                                    AND a.stall_id = #{param.stallId}
                                </if>
                                <if test="param.canteenStallIds != null and param.canteenStallIds.size() > 0">
                                 <if test="param.treeType == 1">
                                     AND a.canteen_id IN
                                     <foreach collection="param.canteenStallIds" item="canteenStallId" separator="," open="(" close=")">
                                         #{canteenStallId}
                                     </foreach>
                                 </if>
                                 <if test="param.treeType == 2">
                                     AND a.stall_id IN
                                     <foreach collection="param.canteenStallIds" item="canteenStallId" separator="," open="(" close=")">
                                         #{canteenStallId}
                                     </foreach>
                                 </if>
                                </if>
                                <if test="param.orgId != null">
                                    AND a.org_id = #{param.orgId}
                                </if>
                                <if test="param.detailType != null">
                                    AND a.detail_type = #{param.detailType}
                                </if>
                                 <if test="param.detailTypes != null and param.detailTypes.size() > 0">
                                     AND a.detail_type IN
                                     <foreach collection="param.detailTypes" item="detailType" separator="," open="(" close=")">
                                         #{detailType}
                                     </foreach>
                                 </if>
                                <if test="param.keyword != null and param.keyword != ''">
                                    AND (a.goods_dishes_name like concat('%', #{param.keyword},'%')
                                        OR a.goods_dishes_num like concat('%', #{param.keyword},'%'))
                                </if>

                                 <include refid="dataPermission"></include>
                            </where>
                             GROUP BY canteen_stall_id,
                                      a.goods_dishes_id,
                                      a.goods_dishes_name,
                                      a.goods_dishes_num,
                                      a.detail_type,
                                      a.sales_mode,
                                      a.type_id
                    ) b
                    LEFT JOIN menu_dishes m ON m.dishes_id = b.goods_dishes_id
                    GROUP BY b.canteen_stall_id,
                        b.goods_dishes_id,
                        b.goods_dishes_name,
                        b.goods_dishes_num,
                        b.detail_type,
                        b.sales_mode,
                        b.type_id,
                        quantity,
                        b.real_amount,
                        b.cust_num,
                        unit_name

                    UNION ALL

                    SELECT c.*,
                            c.total_quantity AS quantity,
                            d.unit_name,
                            SUM(CASE WHEN c.cust_num > 1 THEN 1 ELSE 0 END) AS repurchase_num
                    FROM (
                            SELECT (CASE
                                    WHEN #{param.treeType} = 1 THEN a.canteen_id
                                    WHEN #{param.treeType} = 2 THEN a.stall_id
                                    ELSE a.canteen_id
                                    END) AS canteen_stall_id,
                                    a.goods_dishes_id,
                                    a.goods_dishes_name,
                                    a.goods_dishes_num,
                                    a.detail_type,
                                    a.sales_mode,
                                    a.type_id,
                                    sum(a.quantity) total_quantity,
                                    sum(a.real_amount) real_amount,
                                    sum(a.cust_num) cust_num
                             FROM report_analysis_dishes_sale a
                            LEFT JOIN alloc_canteen ac ON ac.canteen_id = a.canteen_id
                             <where>
                                 a.detail_type = 3
                                <if test="param.startDate != null">
                                    <![CDATA[AND a.statistic_date >= #{param.startDate}]]>
                                </if>
                                <if test="param.endDate != null">
                                    <![CDATA[AND a.statistic_date <= #{param.endDate}]]>
                                </if>
                                <if test="param.ageTypes != null and param.ageTypes.size() > 0">
                                    AND a.age_type IN
                                    <foreach collection="param.ageTypes" item="ageType" separator="," open="(" close=")">
                                        #{ageType}
                                    </foreach>
                                </if>
                                <if test="param.canteenId != null">
                                    AND a.canteen_id = #{param.canteenId}
                                </if>
                                <if test="param.stallId != null">
                                    AND a.stall_id = #{param.stallId}
                                </if>
                                <if test="param.canteenStallIds != null and param.canteenStallIds.size() > 0">
                                 <if test="param.treeType == 1">
                                     AND a.canteen_id IN
                                     <foreach collection="param.canteenStallIds" item="canteenStallId" separator="," open="(" close=")">
                                         #{canteenStallId}
                                     </foreach>
                                 </if>
                                 <if test="param.treeType == 2">
                                     AND a.stall_id IN
                                     <foreach collection="param.canteenStallIds" item="canteenStallId" separator="," open="(" close=")">
                                         #{canteenStallId}
                                     </foreach>
                                 </if>
                                </if>
                                <if test="param.orgId != null">
                                    AND a.org_id = #{param.orgId}
                                </if>
                                <if test="param.detailType != null">
                                    AND a.detail_type = #{param.detailType}
                                </if>
                                 <if test="param.detailTypes != null and param.detailTypes.size() > 0">
                                     AND a.detail_type IN
                                     <foreach collection="param.detailTypes" item="detailType" separator="," open="(" close=")">
                                         #{detailType}
                                     </foreach>
                                 </if>
                                <if test="param.keyword != null and param.keyword != ''">
                                    AND (a.goods_dishes_name like concat('%', #{param.keyword},'%')
                                        OR a.goods_dishes_num like concat('%', #{param.keyword},'%'))
                                </if>

                                 <include refid="dataPermission"></include>
                            </where>
                             GROUP BY canteen_stall_id,
                                      a.goods_dishes_id,
                                      a.goods_dishes_name,
                                      a.goods_dishes_num,
                                      a.detail_type,
                                      a.sales_mode,
                                      a.type_id
                    ) c
                    LEFT JOIN menu_material g ON g.material_id = c.goods_dishes_id
                    LEFT JOIN drp_unit d ON d.unit_id = g.unit_id
                    GROUP BY c.canteen_stall_id,
                        c.goods_dishes_id,
                        c.goods_dishes_name,
                        c.goods_dishes_num,
                        c.detail_type,
                        c.sales_mode,
                        c.type_id,
                        quantity,
                        c.real_amount,
                        c.cust_num,
                        unit_name

                ) t
                LEFT JOIN menu_dishes_type d on d.type_id = t.type_id
                LEFT JOIN alloc_canteen c ON c.canteen_id = t.canteen_stall_id
                LEFT JOIN alloc_stall s ON s.stall_id = t.canteen_stall_id
                LEFT JOIN alloc_area ar ON c.area_id = ar.area_id
                LEFT JOIN supermarket_info si ON si.supermarket_id = t.canteen_stall_id
                CROSS JOIN (SELECT SUM(cust_num) AS total_cust_num FROM report_analysis_dishes_sale WHERE detail_type NOT IN (4, 5, 6)) AS total_customers
                LEFT JOIN(
                SELECT meal_id, AVG(star_level) AS average_star_level
                FROM menu_evalua_detail
                GROUP BY meal_id) med ON t.goods_dishes_id = med.meal_id

        ORDER BY t.quantity DESC
    </select>

    <select id="getSummaryTotal" resultType="com.bonus.canteen.core.report.statistics.order.analysis.vo.ReportAnalysisDishesSaleVO">
                 SELECT
                        sum(a.real_amount) AS real_amount
                 FROM report_analysis_dishes_sale a
                LEFT JOIN menu_dishes m on m.dishes_id = a.goods_dishes_id
                LEFT JOIN menu_material g ON g.material_id = a.goods_dishes_id
                LEFT JOIN drp_unit d ON d.unit_id = g.unit_id

                LEFT JOIN alloc_canteen ac ON ac.canteen_id = a.canteen_id
                 <where>
                     a.detail_type NOT in (4,5,6)
                    <if test="param.startDate != null">
                        <![CDATA[AND a.statistic_date >= #{param.startDate}]]>
                    </if>
                    <if test="param.endDate != null">
                        <![CDATA[AND a.statistic_date <= #{param.endDate}]]>
                    </if>
                    <if test="param.ageTypes != null and param.ageTypes.size() > 0">
                         AND a.age_type IN
                         <foreach collection="param.ageTypes" item="ageType" separator="," open="(" close=")">
                             #{ageType}
                         </foreach>
                    </if>
                    <if test="param.canteenId != null">
                        AND a.canteen_id = #{param.canteenId}
                    </if>
                    <if test="param.stallId != null">
                        AND a.stall_id = #{param.stallId}
                    </if>
                    <if test="param.canteenStallIds != null and param.canteenStallIds.size() > 0">
                     <if test="param.treeType == 1">
                         AND a.canteen_id IN
                         <foreach collection="param.canteenStallIds" item="canteenStallId" separator="," open="(" close=")">
                             #{canteenStallId}
                         </foreach>
                     </if>
                     <if test="param.treeType == 2">
                         AND a.stall_id IN
                         <foreach collection="param.canteenStallIds" item="canteenStallId" separator="," open="(" close=")">
                             #{canteenStallId}
                         </foreach>
                     </if>
                    </if>
                    <if test="param.orgId != null">
                        AND a.org_id = #{param.orgId}
                    </if>
                    <if test="param.detailType != null">
                        AND a.detail_type = #{param.detailType}
                    </if>
                     <if test="param.detailTypes != null and param.detailTypes.size() > 0">
                         AND a.detail_type IN
                         <foreach collection="param.detailTypes" item="detailType" separator="," open="(" close=")">
                             #{detailType}
                         </foreach>
                     </if>
                    <if test="param.keyword != null and param.keyword != ''">
                        AND (a.goods_dishes_name like concat('%', #{param.keyword},'%')
                            OR a.goods_dishes_num like concat('%', #{param.keyword},'%'))
                    </if>

                     <include refid="dataPermission"></include>
                </where>
    </select>

    <sql id="baseInit">
        SELECT t.*,IFNULL(a.cust_num,0) cust_num from
        (

        SELECT
            o.order_date AS statistic_date,
            ifnull(o.canteen_id, -1) as canteen_id,
            ifnull(o.stall_id, -1) as stall_id,

            ifnull(o.org_id, -1) as org_id,
            ifnull(d.goods_dishes_id, -1) AS goods_dishes_id,
            d.goods_dishes_name,
            CASE d.detail_type
            WHEN 3 THEN IFNULL(g.material_code,'')
            ELSE IFNULL(m.dishes_num,'')
            END AS goods_dishes_num,
            ifnull(d.detail_type, 1) AS detail_type,
            ifnull(d.sales_mode, 1) AS sales_mode,
            ifnull(m.type_id, 1) AS type_id,
            o.age_type,
            ifnull(sum( d.quantity ), 0) - ifnull(sum( d.goods_refund_num ), 0) AS quantity,
            ifnull(sum( d.real_amount ), 0) - ifnull(sum( d.refund_amount ), 0) AS real_amount,
            ifnull(o.mealtime_type, -1) AS mealtime_type
        FROM
            report_order_detail d
        LEFT JOIN report_order_info o ON o.order_id = d.order_id
        LEFT JOIN menu_dishes m ON m.dishes_id = d.goods_dishes_id
        LEFT JOIN menu_material g ON g.material_id = d.goods_dishes_id

        WHERE
            <![CDATA[ d.detail_state <> 2 ]]>
            <if test="startTime != null">
                <![CDATA[AND o.order_date >= DATE_FORMAT(#{startTime},'%Y-%m-%d')]]>
            </if>
            <if test="endTime != null">
                <![CDATA[AND o.order_date <= DATE_FORMAT(#{endTime},'%Y-%m-%d')]]>
            </if>
            <if test="param != null and param.canteenId != null">
                AND o.canteen_id = #{param.canteenId}
            </if>
            <if test="param != null and param.stallId != null">
                AND o.stall_id = #{param.stallId}
            </if>
            <if test="param != null and param.orgId != null">
                AND o.org_id = #{param.orgId}
            </if>
            <if test="param != null and param.dishesIds != null and param.dishesIds.size() > 0">
                AND d.goods_dishes_id in
                <foreach collection="param.dishesIds" item="dishesId" separator="," open="(" close=")">
                    #{dishesId}
                </foreach>
            </if>
            <if test="param != null and param.ageTypes != null and param.ageTypes.size() > 0">
                AND o.age_type IN
                <foreach collection="param.ageTypes" item="ageType" separator="," open="(" close=")">
                    #{ageType}
                </foreach>
            </if>
            <if test="param != null and param.mealtimeType != null">
                AND o.mealtime_type = #{param.mealtimeType}
            </if>
        GROUP BY
            statistic_date,
            o.canteen_id,
            o.stall_id,
            o.org_id,
            d.goods_dishes_id,
            d.goods_dishes_name,
            goods_dishes_num,
            d.detail_type,
            d.sales_mode,
            m.type_id,
            o.age_type,
            o.mealtime_type


        ) t

        LEFT JOIN (
            SELECT
                o.order_date AS statistic_date,
                ifnull(o.canteen_id, -1) as canteen_id,
                ifnull(o.stall_id, -1) as stall_id,

                ifnull(o.org_id, -1) as org_id,
                ifnull(d.goods_dishes_id, -1) AS goods_dishes_id,
                d.goods_dishes_name,
                CASE d.detail_type
                WHEN 3 THEN IFNULL(g.material_code,'')
                ELSE IFNULL(m.dishes_num,'')
                END AS goods_dishes_num,
                ifnull(d.detail_type, 1) AS detail_type,
                ifnull(d.sales_mode, 1) AS sales_mode,
                ifnull(m.type_id, 1) AS type_id,
                o.age_type,
                ifnull(o.mealtime_type, -1) AS mealtime_type,

                count(DISTINCT o.cust_id) cust_num
            FROM
                report_order_info o
                left join report_order_detail d on o.order_id = d.order_id
                LEFT JOIN menu_dishes m ON m.dishes_id = d.goods_dishes_id
                LEFT JOIN menu_material g ON g.material_id = d.goods_dishes_id

            WHERE
                <![CDATA[ d.detail_state <> 2 ]]>
                <if test="startTime != null">
                    <![CDATA[AND o.order_date >= DATE_FORMAT(#{startTime},'%Y-%m-%d')]]>
                </if>
                <if test="endTime != null">
                    <![CDATA[AND o.order_date <= DATE_FORMAT(#{endTime},'%Y-%m-%d')]]>
                </if>
                <if test="param != null and param.canteenId != null">
                    AND o.canteen_id = #{param.canteenId}
                </if>
                <if test="param != null and param.stallId != null">
                    AND o.stall_id = #{param.stallId}
                </if>
                <if test="param != null and param.orgId != null">
                    AND o.org_id = #{param.orgId}
                </if>
                <if test="param != null and param.dishesIds != null and param.dishesIds.size() > 0">
                    AND d.goods_dishes_id in
                    <foreach collection="param.dishesIds" item="dishesId" separator="," open="(" close=")">
                        #{dishesId}
                    </foreach>
                </if>
                <if test="param != null and param.ageTypes != null and param.ageTypes.size() > 0">
                    AND o.age_type IN
                    <foreach collection="param.ageTypes" item="ageType" separator="," open="(" close=")">
                        #{ageType}
                    </foreach>
                </if>
                <if test="param != null and param.mealtimeType != null">
                    AND o.mealtime_type = #{param.mealtimeType}
                </if>

                GROUP BY
                        statistic_date,
                        o.canteen_id,
                        o.stall_id,
                        o.org_id,
                        d.goods_dishes_id,
                        d.goods_dishes_name,
                        goods_dishes_num,
                        d.detail_type,
                        d.sales_mode,
                        m.type_id,
                        o.age_type,
                        o.mealtime_type
		) a ON a.statistic_date = t.statistic_date AND a.canteen_id = t.canteen_id AND a.stall_id = t.stall_id AND a.org_id = t.org_id AND a.goods_dishes_id = t.goods_dishes_id
            AND a.goods_dishes_name = t.goods_dishes_name
            AND a.goods_dishes_num = t.goods_dishes_num AND a.detail_type = t.detail_type
            AND a.sales_mode = t.sales_mode AND a.type_id = t.type_id AND a.age_type = t.age_type AND a.mealtime_type = t.mealtime_type
    </sql>

    <select id="init" resultType="com.bonus.canteen.core.report.statistics.order.analysis.model.ReportAnalysisDishesSale">
        <include refid="baseInit"></include>
    </select>

    <select id="getDishesMonthSum" resultType="com.bonus.canteen.core.report.api.vo.ReportOrderDishesSumVO">
        SELECT
            a.goods_dishes_id AS dishes_id,
            SUM( quantity ) AS quantity
        FROM
            report_analysis_dishes_sale a
        WHERE
            a.statistic_date BETWEEN #{startDate} AND #{endDate}
        <if test="dishesIdList != null and dishesIdList.size() > 0">
            AND a.goods_dishes_id in
            <foreach collection="dishesIdList" item="dishesId" separator="," open="(" close=")">
                #{dishesId}
            </foreach>
        </if>
        GROUP BY
            a.goods_dishes_id
    </select>

    <insert id="initFix">
        INSERT INTO report_analysis_dishes_sale(
            statistic_date,
            canteen_id,
            stall_id,
            org_id,
            goods_dishes_id,
            goods_dishes_name,
            goods_dishes_num,
            detail_type,
            sales_mode,
            type_id,
            age_type,
            quantity,
            real_amount,
            mealtime_type,
            cust_num
        )
        <include refid="baseInit"></include>
    </insert>



    <select id="getOrderMealtimeDetail" resultType="com.bonus.canteen.core.report.api.vo.ReportOrderDetaiVO">
        SELECT
        a.statistic_date ord_goods_date,
        a.mealtime_type,
        a.goods_dishes_id,
        a.goods_dishes_name,
        a.sales_mode,
        SUM(a.quantity) quantity,
        SUM(a.real_amount) real_amount
        FROM
        report_analysis_dishes_sale a
        <where>
            <if test="param.ordGoodsDate != null">
                AND a.statistic_date = #{param.ordGoodsDate}
            </if>
            <if test="param != null and param.mealtimeType != null">
                AND a.mealtime_type = #{param.mealtimeType}
            </if>
            <if test="param.goodsName != null and param.goodsName != ''">
                AND a.goods_dishes_name LIKE concat('%', #{param.goodsName},'%')
            </if>
        </where>
        GROUP BY
        a.statistic_date,
        a.mealtime_type,
        a.goods_dishes_id,
        a.goods_dishes_name,
        a.sales_mode
    </select>
</mapper>
