<?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="cn.com.ctop.toutiao.modules.report.mapper.BytedanceAccountReportMapper">

    <select id="queryTodaySumReportBy" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
          ROUND(sum(cost),2) cost,
          sum(show_num) showNum,
          sum(click) click,
          sum(convert_num) as convertNum,
          max(stat_hour) maxHour
        FROM
          ctop_bytedance_report_advertiser_hourly
        WHERE
          stat_datetime = #{statDate}
        AND advertiser_id in
        <foreach item="item" index="index" collection="accountIds"
                 open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

    <select id="queryTodaySumByHourGroupAccount" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
          t2.account_id as accountId,
          t2.auth_name as authName,
          ${filed}
        FROM ctop_bytedance_report_advertiser_hourly t1
        left join ctop_user_allocation t2 on t1.advertiser_id=t2.account_id
        WHERE t1.stat_datetime = #{statDate}
          and t1.stat_hour &lt;= #{hour}
        AND t1.advertiser_id in
        <foreach item="item" index="index" collection="accountIds"
                 open="(" separator="," close=")">
            #{item}
        </foreach>
        group by t1.advertiser_id
        order by ${target} ${order}
    </select>

    <select id="queryTodaySumByHour" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
          ROUND(sum(cost),2) cost,
          sum(show_num) showNum,
          sum(click) click,
          sum(convert_num) as convertNum
        FROM
          ctop_bytedance_report_advertiser_hourly
        WHERE
          stat_datetime = #{statDate}
        and stat_hour &lt;= #{hour}
        AND advertiser_id in
        <foreach item="item" index="index" collection="accountIds"
                 open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

    <select id="querySumByHour" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
          ${filed}
        FROM
          ctop_bytedance_report_advertiser_hourly t1
        WHERE
          t1.stat_datetime = #{statDate}
        and t1.stat_hour &lt;= #{hour}
        AND t1.advertiser_id in
        <foreach item="item" index="index" collection="accountIds"
                 open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

    <select id="queryTodayDetailReportBy" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
          ROUND(sum(cost),2) cost,
          sum(show_num) showNum,
          sum(click) click,
          sum(convert_num) as convertNum,
          stat_hour as statHour
        FROM
            ctop_bytedance_report_advertiser_hourly
        WHERE
            stat_datetime = #{statDate}
        AND advertiser_id in
        <foreach item="item" index="index" collection="accountIds"
                 open="(" separator="," close=")">
            #{item}
        </foreach>
        GROUP BY
            stat_hour
        ORDER BY
            stat_hour ASC
    </select>

    <select id="queryAllSumByStartEndDate" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
          ${filed}
        FROM ctop_bytedance_report_advertiser_daily t1
        WHERE t1.stat_datetime &lt;= #{endDate} '00:00:00'
        AND t1.stat_datetime &gt;= #{startDate}
        AND t1.advertiser_id in
        <foreach item="item" index="index" collection="accountIds"
                 open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

    <select id="querySumByStartEndDate" resultType="com.alibaba.fastjson.JSONObject">
        SELECT ROUND(sum(cost), 2) cost,
        sum(show_num)       showNum,
        sum(click)          click,
        sum(convert_num) as convertNum
        FROM ctop_bytedance_report_advertiser_daily t1
        WHERE t1.stat_datetime &lt;= #{endDate} '00:00:00'
        AND t1.stat_datetime &gt;= #{startDate}
        AND advertiser_id in
        <foreach item="item" index="index" collection="accountIds"
                 open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

    <select id="querySumByDateGroupAccount" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
          DATE_FORMAT(t1.stat_datetime,'%Y-%m-%d') as statDate,
          t2.account_id as accountId,
          t2.auth_name as authName,
          ${filed}
        FROM
        ctop_bytedance_report_advertiser_daily t1
        left join ctop_user_allocation t2 on t1.advertiser_id=t2.account_id
        WHERE
            t1.stat_datetime &lt;= #{endDate} '00:00:00'
        AND t1.stat_datetime &gt;= #{startDate}
        AND t1.advertiser_id in
        <foreach item="item" index="index" collection="accountIds"
                 open="(" separator="," close=")">
            #{item}
        </foreach>
        group by t1.advertiser_id
        order by ${target} ${order}
    </select>

    <select id="querySumByDateGroupAccountAndDate" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
        DATE_FORMAT(t1.stat_datetime,'%Y-%m-%d') as statDate,
        t2.account_id as accountId,
        t2.auth_name as authName,
        ${filed}
        FROM
        ctop_bytedance_report_advertiser_daily t1
        left join ctop_user_allocation t2 on t1.advertiser_id=t2.account_id
        WHERE
        t1.stat_datetime &lt;= #{endDate} '00:00:00'
        AND t1.stat_datetime &gt;= #{startDate}
        AND t1.advertiser_id in
        <foreach item="item" index="index" collection="accountIds"
                 open="(" separator="," close=")">
            #{item}
        </foreach>
        group by t1.stat_datetime
        order by ${target} ${order}
    </select>

    <select id="queryDetailByStartEndDate" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
          ROUND(sum(cost),2) cost,
          sum(show_num) showNum,
          sum(click) click,
          sum(convert_num) convertNum,
          DATE_FORMAT(stat_datetime, '%Y-%m-%d') statDate
        FROM
           ctop_bytedance_report_advertiser_daily
        WHERE stat_datetime &lt;= #{endDate} '00:00:00'
          AND stat_datetime &gt;= #{startDate}
          AND advertiser_id in
          <foreach item="item" index="index" collection="accountIds"
                 open="(" separator="," close=")">
            #{item}
          </foreach>
        group by stat_datetime
        order by stat_datetime asc
    </select>

    <select id="queryDetailGroupMonthByDate" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
          ROUND(sum(cost),2) cost,
          sum(show_num) showNum,
          sum(click) click,
          sum(convert_num) convertNum,
          DATE_FORMAT(t1.stat_datetime, '%Y-%m') statDate
        FROM ctop_bytedance_report_advertiser_daily t1
        WHERE t1.stat_datetime &lt;= #{endDate} '00:00:00'
          AND t1.stat_datetime &gt;= #{startDate}
          AND t1.advertiser_id in
        <foreach item="item" index="index" collection="accountIds"
                 open="(" separator="," close=")">
            #{item}
        </foreach>
        group by DATE_FORMAT(t1.stat_datetime, '%Y-%m')
        order by t1.stat_datetime asc
    </select>

    <select id="queryDetailGroupDayByMonth" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
               DATE_FORMAT(stat_datetime, '%Y-%m-%d')                      statDate,
               SUBSTR(DATE_FORMAT(stat_datetime, '%Y-%m-%d') FROM 9 FOR 2) day
        FROM ctop_bytedance_report_advertiser_daily
        WHERE stat_datetime like '${month}%'
        group by DATE_FORMAT(stat_datetime, '%Y-%m-%d')
        order by stat_datetime asc
    </select>

    <sql id="selectSql">
        ifnull(sum(a.show_num),0)                          as showMaterial,                   -- 展现数据-展示数
        ifnull(sum(a.click),0)                             as clickMaterial,                  -- 点击数
        ifnull(sum(a.convert_num),0)                       as convertMaterial,                -- 转化数据-转化数
        ifnull(sum(a.cost),0)                              as cost,                           -- 消耗
        ifnull(sum(a.active),0)                            as active,                         -- 应用下载-激活
        ifnull(sum(a.download_finish),0)                   as downloadFinish,                 -- 应用下载-安卓下载完成
        ifnull(sum(a.download_start),0)                    as downloadStart,                  -- 应用下载-安卓下载开始
		ifnull(sum(a.click_install),0)                     as clickInstall,                   -- 应用下载-点击安装数
		ifnull(sum(a.install_finish),0)                    as installFinish,                  -- 应用下载-安卓安装完成
		ifnull(sum(a.register),0)                          as register,                       -- 应用下载-注册
        ifnull(sum(a.pay_count),0)                         as payCount,                       -- 应用下载-付费数
		ifnull(sum(a.form),0)                              as form,                           --  表单提交数
		ifnull(sum(a.total_play),0)                        as totalPlay,                      -- 视频-总播放
        ifnull(sum(a.valid_play),0)                        as validPlay,                      -- 视频-有效播放
        ifnull(sum(a.wifi_play),0)                         as wifiPlay,                       -- 视频-wifi播放
        ifnull(sum(a.play25_feed_break),0)                 as play25FeedBreak,                -- 视频-播放25%进度总数
        ifnull(sum(a.play50_feed_break),0)                 as play50FeedBreak,                -- 视频-播放50%进度总数
        ifnull(sum(a.play75_feed_break),0)                 as play75FeedBreak,                -- 视频-播放75%进度总数
        ifnull(sum(a.play100_feed_break),0)                as play100FeedBreak,               -- 视频-播放100%进度总数
		ifnull(sum(a.share),0)                             as shareMaterial,                  -- 互动数据-分享数
		ifnull(sum(a.like_num),0)                          as likeMaterial,                   -- 互动数据-点赞数
		case
        when sum(a.total_play) != 0 and sum(a.total_play) is not null and sum(a.play25_feed_break) is not null
        then round(sum(a.play25_feed_break) / sum(a.total_play),2)
        else 0 end                               as play25FeedBreakRate,            -- 25%进度播放率
		case
        when sum(a.click) != 0 and sum(a.click) is not null and sum(a.convert_num) is not null
        then round(sum(a.convert_num) / sum(a.click),2)
        else 0 end                               as convertRate,                    -- 转化率  转化数/点击数*100% !
        case
        when sum(a.convert_num) != 0 and sum(a.convert_num) is not null and sum(a.cost) is not null
        then round(sum(a.cost)/sum(a.convert_num),2)
        else 0 end as convertCost, --  转化数据-转化成本=总花费/转化数
		ifnull(sum(a.follow),0)                            as follow,                         -- 互动数据-新增关注数
        ifnull(sum(a.next_day_open),0)                     as nextDayOpen,                    -- 次留数
        case
        when sum(a.active) != 0 and sum(a.next_day_open) is not null and sum(a.active) is not null
        then round(sum(a.next_day_open) / sum(a.active),2)
        else 0 end                               as nextDayOpenRate,                -- 次留率 = 次留数/激活数
        case
        when sum(a.next_day_open) != 0 and sum(a.next_day_open) is not null and sum(a.cost) is not null
        then round(sum(a.cost) / sum(a.next_day_open),2)
        else 0 end                               as nextDayOpenCost,                -- 次留成本 = 消耗/次留数
		case
        when sum(a.click) != 0 and sum(a.click) is not null and sum(a.cost) is not null
        then round(sum(a.cost) / sum(a.click),2)
        else 0 end                               as cpc,                            -- 平均点击单价
        case
        when sum(a.show_num) != 0 and sum(a.show_num) is not null and sum(a.click) is not null
        then round(sum(a.click) / sum(a.show_num),2)
        else 0 end                               as ctr,                            -- 展现数据-点击率   广告被点击的次数占展示次数的百分比。计算方法：点击数/展示数*100%
        case
        when sum(a.show_num) != 0 and sum(a.cost) is not null and sum(a.show_num) is not null
        then round(sum(a.cost) / sum(a.show_num) * 1000,2)
        else 0 end                               as cpm,                            -- 平均千次展现费用  广告平均每一千次展现所付出的费用，计算公式是：总花费/展示数*1000。
		case
        when sum(a.active) != 0 and sum(a.cost) is not null and sum(a.active) is not null
        then round(sum(a.cost) / sum(a.active),2)
        else 0 end                               as activeCost,                     -- 应用下载广告数据-激活成本  计算方式：总花费/激活数。
		case
        when sum(a.click) != 0 and sum(a.active) is not null and sum(a.click) is not null
        then round(sum(a.active) / sum(a.click),2)
        else 0 end                               as activeRate,                     -- 应用下载广告数据-激活率   计算方式：激活数/点击数*100%
        case
        when sum(a.active) != 0 and sum(a.register) is not null and sum(a.active) is not null
        then round(sum(a.register) / sum(a.active),2)
        else 0 end                               as activeRegisterRate,             -- 应用下载广告数据-注册率   注册用户占激活用户的比例
        case
        when sum(a.register) != 0 and sum(a.cost) is not null and sum(a.register) is not null
        then round(sum(a.cost) / sum(a.register),2)
        else 0 end                               as activeRegisterCost               -- 应用下载广告数据-注册成本  总花费/注册数，当天数据可能会有波动，次日早8点后稳定。
    </sql>

    <select id="getBytedanceAccountInfoByProjectId" resultType="cn.com.ctop.toutiao.modules.report.DTO.ByteDanceReportAccountDailyDTO">
        select * from (
        select
        concat(#{startDate},'~',#{endDate}) as statDate,
        a.advertiser_id as 'accountId',
        c.advertiser_id as 'advertiserId',
        c.advertiser_name as 'advertiserName',
        c.responsible_name as 'responsibleName',
        c.design_responsible_name as 'designResponsibleName',
        b.auth_name as 'authName',
        b.project_id as 'projectId',
        b.project_name as 'projectName',
        c.media_id as 'mediaId',
        <include refid="selectSql"></include>
        from
        ctop_bytedance_report_advertiser_daily a
        left join (select * from ctop_user_allocation group by account_id) b on a.advertiser_id = b.account_id
        left join ctop_project c on b.project_id = c.id
        where
        date_format(a.stat_datetime,'%Y-%m-%d') &gt;= #{startDate}
        and
        date_format(a.stat_datetime,'%Y-%m-%d') &lt;= #{endDate}
        <if test="projectId!=null and projectId!=''">
            and
            b.project_id = #{projectId}
        </if>
        <if test="accountIds !=null">
            and a.advertiser_id in
            <foreach collection="accountIds" item="item" separator=","
                     open="(" close=")">
                #{item}
            </foreach>
        </if>
        group by a.advertiser_id
        order by sum(a.cost) desc
        )m
        <if test="yn =1">
            where
            m.cost != 0
        </if>
    </select>

    <select id="getBytedanceProjectInfo" resultType="cn.com.ctop.toutiao.modules.report.DTO.ByteDanceReportAccountDailyDTO">
        select * from (
        select
        concat(#{startDate},'~',#{endDate}) as statDate,
        a.advertiser_id as 'accountId',
        c.advertiser_id as 'advertiserId',
        c.advertiser_name as 'advertiserName',
        c.responsible_name as 'responsibleName',
        c.design_responsible_name as 'designResponsibleName',
        b.auth_name as 'authName',
        b.project_id as 'projectId',
        b.project_name as 'projectName',
        c.media_id as 'mediaId',
        <include refid="selectSql"></include>
        from
        ctop_bytedance_report_advertiser_daily a
        left join (select * from ctop_user_allocation group by account_id) b on a.advertiser_id = b.account_id
        left join ctop_project c on b.project_id = c.id
        where
        date_format(a.stat_datetime, '%Y-%m-%d') &gt;= #{startDate}
        and
        date_format(a.stat_datetime, '%Y-%m-%d') &lt;= #{endDate}
        and
        b.project_id in
        <foreach collection="projectList" item="item" separator=","
                 open="(" close=")">
            #{item}
        </foreach>
        group by b.project_id
        )m
        <if test="yn = 1">
            where
            m.cost != 0
        </if>
    </select>

    <select id="getRoleCodeByUserId" resultType="string">
        select
        role_code
        from
        sys_user_role a
        left join sys_role b on a.role_id = b.id
        where a.user_id = #{userId}
    </select>

    <select id="queryProjectInfoByAdmin" resultType="long">
        select
        id as projectId
        -- project_name as projectName,
        -- advertiser_id as advertiserId,
        -- advertiser_name as advertiserName,
        -- responsible_name as responsibleName,
        -- media_id as mediaId
        from
        ctop_project
        where
        media_id in
        <foreach collection="mediaIds" item="item" separator=","
                 open="(" close=")">
            #{item}
        </foreach>
    </select>

    <select id="getSaleProjects" resultType="long">
        select
        distinct a.id as projectId
        -- a.project_name as projectName,
        -- a.advertiser_id as advertiserId,
        -- a.advertiser_name as advertiserName,
        -- a.media_id as mediaId,
        -- a.sale_id as saleId,
        -- b.realname as saleName
        from
        ctop_project a
        left join sys_user b on a.sale_id = b.id
        where a.sale_id = #{userId}
        and a.media_id in
        <foreach collection="mediaIds" item="item" separator=","
                 open="(" close=")">
            #{item}
        </foreach>
    </select>

    <select id="queryProjectMemberByIds" resultType="cn.com.ctop.toutiao.modules.report.DTO.ByteDanceReportAccountDailyDTO">
        select
        distinct id as projectId,
        project_name as projectName,
        advertiser_id as advertiserId,
        advertiser_name as advertiserName,
        media_id as mediaId,
        responsible_name as responsibleName,
        design_responsible_name as designResponsibleName
        from
        left join ctop_project
        where
        id in
        <foreach collection="projectIds" item="item" separator=","
                 open="(" close=")">
            #{item}
        </foreach>
        order by create_time desc
    </select>

    <select id="getUserProjectAccountIds" resultType="long">
        select
        a.account_id
        from
        (select project_id,account_id,media_id,create_time from ctop_user_allocation  group by account_id) a
        left join ctop_project_member b on a.project_id=b.project_id
        where
        a.user_id = #{userId}
        and a.media_id in (1,3)
        order by a.create_time desc
        limit 50
    </select>


    <select id="getSaleProjectAccountIds" resultType="long">
        select
        a.account_id
        from
        (select project_id,account_id,media_id,create_time from ctop_user_allocation  group by account_id) a
        left join ctop_project b on a.project_id=b.id
        where
        b.sale_id = #{userId}
        and b.media_id in (1,3)
        order by a.create_time desc

    </select>

    <select id="getUserProjectAccountIdsByAdmin" resultType="long">
        select
        a.account_id
        from
        ctop_user_allocation a
        left join ctop_project b on a.project_id = b.id
        where
        b.media_id in (1,3)

    </select>

</mapper>
