<?php
/**
 * Ta.php
 * Created by: Owen
 * Created on: 2021/5/10 12:14
 *
 */
use ThinkingEngine\ThinkingDataAnalytics;
use ThinkingEngine\FileConsumer;
use ThinkingEngine\TALogger;
class ModelTa{
    //缓存keys
    public $keys=[
        "event"   =>"SS_EVENT:",//事件分类队列
        "userSysAttr" =>"USER_SYS_ATTR:",//用户系统预制属性(登录预设)
        "common" => "CE_PROPERTY:"
    ];
    //事件开关
    public $lock=[
        "all"=>1,
        "user_create"=>1,//用户注册
        "user_set"=>1, //设置属性
        "user_setOnce"=>1, //设置属性,只一次
        "new_device"=>1,//设备新增
        "user_login"=>1,//用户登录
        "level_up"=>1,//世界升级
        "sign"=>1,//完成签到
        "slot_machine"=>1,//转动老虎机
        "attack"=>1,//攻击玩家
        "steal"=>1,//偷袭玩家
        "building"=>1,//建造建筑
        "tap_fruit"=>1,//点击水果机
        "pet_unlock"=>1,//解锁宠物
        "pet_feed"=>1,//投喂宠物
        "pet_up"=>1,//宠物升级
        "order_finish"=>1,//订单完成
        "invite_success"=>1,//邀请成功
        "activity_collect_reward"=>1,//收集活动领奖
        "activity_rank_reward_layer"=>1,//锦标赛阶段领奖
        "activity_rank_reward_ranking"=>1,//锦标赛排名奖励
        "activity_coinslot"=>1,//金币老虎机
        "activity_coinslot_quest"=>1,//金币老虎机
        "activity_egg_knock"=>1,//彩蛋敲蛋
        "activity_egg_rebirth"=>1,//彩蛋复活
        "activity_egg_end"=>1,//彩蛋结束
        "activity_pass_reward"=>1,//通行证领奖
        "activity_pass_levelup"=>1,//通行证领奖
        "chest"=>1,//宝箱获得
        "chest_sp"=>1,//宝箱获得
        "card_send"=>1,//赠送卡片
        "card_accept"=>1,//接受赠送卡片
        "card_ask"=>1,//索要卡片
        "card_respond"=>1,//回应索要卡片
        "spin_send"=>1,//赠送体力
        "spin_accept"=>1,//接受其他人赠送体力
        "coin_send"=>1,//赠送金币
        "coin_accept"=>1,//接受其他人赠送金币
        "cardset_complate"=>1,//卡组完成
        "resource_obtain"=>1,//资源获取
        "resource_cost"=>1,//消耗资源时记录
        "resource_list"=>1,//资源产销
        'user_firebase_activity' => 1,
    ];
    //事件上报数据结构
    public $events =[
        //用户公共属性
        "userCommon"=>[
            "current_level"=>0,
            "current_vip_level"=>0,
            "current_spin"=>0,
            "current_coin"=>0,
            "current_star"=>0,
            "current_building_level"=>0,
            "total_obtain_spin"=>0,
            "total_cost_spin"=>0,
            "total_spin_times"=>0,
            "total_play_time"=>0,
            "current_play_time"=>0,
            "total_login_days"=>0,
            "continuity_login_days"=>0,
            "total_pay"=>0.0,
            "activity_collect_id"=>0,
            "activity_collect_type"=>0,
            "activity_collect_spin_range"=>"",
            "activity_collect_layer"=>0,
            "activity_collect_symbol_current"=>0,
            "activity_collect_symbol_need"=>0,
            "activity_collect_symbol_total"=>0,
            "activity_collect_remining_time"=>0,
            "activity_rank_id"=>0,
            "activity_rank_ranking"=>0,
            "activity_rank_layer"=>0,
            "activity_rank_symbol"=>0,
            "activity_rank_remining_time"=>0,
            "activity_list"=>[],
            "pack_list"=>[],
            "is_debug"=>IS_DEBUF,
        ],
        "user_set"=>[
            "channel"               => "",//渠道
            "nick_name"             => "",//昵称
            "register_time"         => 0,//注册时间
            "user_login_type"       => "",//登录模式
            "account_bind_time"     => 0,//账号绑定时间
            "first_pay_time"        => 0,//首次充值时间
            "current_level"         => 0,//当前等级
            "current_vip_level"     => 0,//当前等级
            "current_vip_score"     => 0,//当前vip等级
            "current_star"          => 0,//当前星星数量
            "current_coin"          => 0,//当前金币数量
            "current_spin"          => 0,//当前体力数量
            "current_shield"        => 0,//当前盾牌数量
            "user_source"           => 0,//来源
            "is_member"             => false,//是否为订阅会员
            "member_time"           => 0,//订阅会员到期时间
            "total_play_time"       => 0,//累计游戏时长
            "total_login_days"      => 0,//累计登陆天数
            "continuity_login_days" => 0,//连续登陆天数
            "last_login_time"       => 0,//最后登陆时间
            "last_pay_time"         => 0,//最后充值时间
            "total_pay"             => 0.0,//充值总额
            "friend_num"            => 0,//好友数量
            "cardset_complete_num"  => 0,//完成卡组数量
            "cardset_complete_list" => [],//完成卡组
            "pet_steal_level"       => 0,//偷宠物等级
            "pet_attack_level"      => 0,//打宠物等级
            "pet_shield_level"      => 0,//盾宠物等级
            "recalled_user"         => 0,//召回人
            "invited_user"          => 0,//邀请人
            "invite_num"            => 0,//邀请玩家数量
            "country"               => "",//国家
            "app_version"           => "",//app版本
            "os"                    => "",//操作系统
            "firebase_activity"     => 0,

            "tracker_name"          => "",//用户来源拼接
            "adjust_adid"           => "",//adjust adid
            "network_name"          => "",//渠道
            "campaign_name"         => "",//广告系列
            "adgroup_name"          => "",//广告组
            "creative_name"         => "",//素材名称
            "network_id"            => "",//渠道id
            "campaign_id"           => "",//广告系列id
            "adgroup_id"            => "",//广告组id
            "creative_id"           => "",//广告id
            "spend"                 => 0.0,//花费

        ],
        //==========================================
        //用户注册
        "user_create"=>[],
        //设备新增
        "new_device"=>[],
        //用户登录-[登录模式]
        "user_login"=>["login_type"=>0,"device_id"=>""],
        "user_firebase_activity" => ["firebase_activity"=>0], //firebase数数上报
        //世界升级-[新等级]
        "level_up"=>["new_level"=>0],
        //完成签到[签到天数(7天),累计天数(30天)]
        "sign"=>["sign_continuity_days"=>0,"sign_total_days"=>0],
        //转动老虎机
        "slot_machine"=>[
            "slot_bet"=>1,//奖励倍数
            "slot_result"=>0,//结果 1打 2偷 3体 4盾 5-10金 11空 12-14收集物 15-17小玩法 18-19偷收集 20-21打收集
            "slot_coin_basic"=>0,//金币基础
            "slot_coin_blast_ratio"=>0,//金币大爆炸倍率
            "slot_coin_final"=>0,//实际获得金币
            "slot_shield"=>0,//获得盾牌
            "slot_shield_tospin"=>0,//盾牌溢出转换体力
            "slot_spin"=>0,//获得体力
            "slot_collect_symbol"=>0,//获取收集物数量
            "slot_rank_symbol"=>0,//获取锦标赛收集物数量
        ],
        //攻击玩家
        "attack"=>[
            "attack_target_user"=>0,//对方ID
            "attack_relation"=>0,//和对方关系 1机器人 2陌生人 3好友
            "attack_result"=>0,//攻击结果 1被防御 2攻击成功
            "attack_bet"=>1,//倍率
            "attack_collect_symbol"=>0,//获得收集物数量
            "attack_rank_symbol"=>0,//获得锦标赛收集物数量
            "attack_coin_basic"=>0,//攻击基础获得金币
            "attack_coin_final"=>0,//攻击实际获取金币
            "attack_pet_remain_time"=>0,//攻击宠物剩余时间
            "attack_pet_level"=>0,//攻击宠物等级
        ],
        //偷袭玩家
        "steal"=>[
            "steal_target_user"=>0,//对方ID
            "steal_relation"=>0,//和对方关系 1机器人 2陌生人 3好友
            "steal_result"=>"",//偷取结果 10%、25%、65%、宝箱（名字）
            "steal_bet"=>1,
            "steal_collect_symbol"=>0,//获得收集物数量
            "steal_rank_symbol"=>0,//获得锦标赛收集物数量
            "steal_coin_basic"=>0,//偷取基础获得金币(cash King显示的基础值)
            "steal_coin_final"=>0,//偷取实际获得金币(偷取的实际值，包含各种加成)
            "steal_pet_remain_time"=>0,//偷宠物剩余时间
            "steal_pet_level"=>0,//偷宠物等级
        ],
        //建造建筑
        "building"=>[
            "build_id"=>0,//建筑id(1~5)
            "build_level"=>0,//建筑等级(建造后的等级)
            "build_type"=>0,//类型(1建造,2修复)
            "build_coin_basic"=>0,//花费金币的基础数(基础消耗的金币数（模板中的值）)
            "build_coin_discount"=>0,//当前建筑打折活动的折扣
            "build_coin_cost"=>0,//花费金币数(实际消耗的金币)
        ],
        //点击水果机
        "tap_fruit"=>[
            "fruit_coin"=>0,//获得金币数量
            "fruit_result"=>0,//结果档位(最终结果（1~8档）)
            "fruit_type"=>0,//类型(1广告/2免费/3会员订阅/4付费)
        ],
        //解锁宠物
        "pet_unlock"=>[
            "pet_unlock_id"=>0//宠物ID
        ],
        //投喂宠物
        "pet_feed"=>[
            "pet_feed_id"=>0,//宠物ID
            "pet_feed_type"=>0,//喂养类型(1免费2广告3粮食)
            "pet_feed_remain_time"=>0,//剩余激活时间
        ],
        //宠物升级
        "pet_up"=>[
            "pet_up_id"=>0,
            "pet_up_addexptype"=>0,//经验变化类型 (1喂经验2生效3喂粮食)
            "pet_up_addexp"=>0,//增加经验
            "pet_up_oldlevel"=>0,//升级前等级
            "pet_up_newlevel"=>0,//升级后等级
        ],
        //订单完成
        "order_finish"=>[
            "order_id"=>"",//订单id
            "order_scene_father"=>"",//付费场景
            "order_scene_son"=>"",//付费场景细分
            "shopid"=>0,//商品id
            "pay_method"=>"",//订单完成支付方式
            "pay_amount"=>0.00,//支付金额
            "pay_reward_spin"=>0,//获得体力
            "pay_reward_coin"=>0,//获得金币
            "pay_reward_petfood"=>0,//获得宠物食物
            "pay_reward_petexp"=>0,//获得宠物经验
            "pay_reward_chest_list"=>[],//获得宝箱
            "pay_reward_activity"=>0,//激活活动id
            "pay_reward_activity_time"=>0,//激活活动时间
            "pay_reward_card_list"=>[],//获得卡牌
            "pay_reward_card_joker"=>0,//订单完成获得小丑卡
            "is_first_pay"=>false//是否首购
        ],
        //邀请成功
        "invite_success"=>[
            "invite_location"=>0,//好友邀请按钮位置
            "invite_user"=>0//邀请来的新玩家的id
        ],
        //收集活动领奖
        "activity_collect_reward"=>[
            "activity_collect_reward_spin"=>0,//获得体力
            "activity_collect_reward_coin"=>0,//获得金币
            "activity_collect_reward_petfood"=>0,//获得宠物食物
            "activity_collect_reward_petexp"=>0,//获得宠物经验
            "activity_collect_reward_chest_list"=>[],//获得宝箱
            "activity_collect_reward_activity"=>0,//激活活动id
            "activity_collect_reward_activity_time"=>0,//激活活动时间
            "activity_collect_reward_card_list"=>[],//获得卡牌
            "activity_collect_reward_card_joker"=>0,//获得卡牌(可能会有小丑卡)
            "activity_collect_reward_layer"=>1,//当前层
        ],
        //锦标赛领奖
        "activity_rank_reward_layer"=>[
            "activity_rank_layer_reward_spin"=>0,//获得体力
            "activity_rank_layer_reward_coin"=>0,//获得金币
            "activity_rank_layer_reward_petfood"=>0,//获得宠物食物
            "activity_rank_layer_reward_petexp"=>0,//获得宠物经验
            "activity_rank_layer_reward_chest_list"=>[],//获得宝箱(宝箱id的列表)
            "activity_rank_layer_reward_activity"=>0,//激活活动id
            "activity_rank_layer_reward_activity_time"=>0,//激活活动时间
            "activity_rank_layer_reward_card_list"=>[],//获得卡牌
            "activity_rank_layer_reward_card_joker"=>0,//获得卡牌(可能会有小丑卡)
            "activity_rank_layer_reward_layer"=>1,//当前层
        ],
        //锦标赛排名奖励
        "activity_rank_reward_ranking"=>[
            "activity_rank_ranking_reward_spin"=>0,
            "activity_rank_ranking_reward_coin"=>0,
            "activity_rank_ranking_reward_petfood"=>0,
            "activity_rank_ranking_reward_petexp"=>0,
            "activity_rank_ranking_reward_chest_list"=>[],
            "activity_rank_ranking_reward_activity"=>0,
            "activity_rank_ranking_reward_activity_time"=>0,
            "activity_rank_ranking_reward_card_list"=>[],
            "activity_rank_ranking_reward_card_joker"=>0,
        ],
        //金币老虎机
        "activity_coinslot"=>[
            "activity_coinslot_bet"=>0,//使用倍率
            "activity_coinslot_coin_cost"=>0,//消耗金币
            "activity_coinslot_result"=>0,//转动结果(金币倍率，空奖励为0，bonus为-1)
            "activity_coinslot_bonus"=>0,//bonus倍率(若没转到bonus则为空)
            "activity_coinslot_coin_obtain"=>0,//获得金币
            "activity_coinslot_quest"=>0,//当前任务(当前任务层数)
            "activity_coinslot_quest_progress"=>0,//任务进度(任务进度（转动前）)
        ],
        //金币老虎机進度
        "activity_coinslot_quest"=>[
            "activity_coinslot_quest"=>0,
            "activity_coinslot_quest_reward_spin"=>0,
            "activity_coinslot_quest_reward_coin"=>0,
            "activity_coinslot_quest_reward_petfood"=>0,
            "activity_coinslot_quest_reward_petexp"=>0,
            "activity_coinslot_quest_reward_chest_list"=>[],
            "activity_coinslot_quest_reward_activity"=>0,
            "activity_coinslot_quest_reward_activity_time"=>0,
            "activity_coinslot_quest_reward_card_list"=>[],
            "activity_coinslot_quest_reward_card_joker"=>0,
        ],
        //彩蛋敲蛋
        "activity_egg_knock"=>[
            "activity_egg_knock_layer"=>0,//层数
            "activity_egg_knock_result"=>0,//结果(1蛇,2奖励)
            "activity_egg_knock_result_spin"=>0,//获得体力
            "activity_egg_knock_result_coin"=>0,//获得金币
            "activity_egg_knock_result_petfood"=>0,//获得宠物食物
            "activity_egg_knock_result_petexp"=>0,//获得宠物经验
            "activity_egg_knock_result_chest_list"=>[],//获得宝箱(宝箱id列表)
            "activity_egg_knock_result_activity"=>0,//获得活动id
            "activity_egg_knock_result_activity_time"=>0,//获得活动时长
            "activity_egg_knock_result_card_list"=>[],//获得卡牌(可能会有小丑卡)
            "activity_egg_knock_result_card_joker"=>0,
        ],
        //彩蛋复活
        "activity_egg_rebirth"=>[
            "activity_egg_rebirth_layer"=>0,//复活层数
            "activity_egg_rebirth_times"=>0,//复活次数(此次彩蛋第几次复活)
            "activity_egg_rebirth_coin_cost"=>0//复活消耗金币
        ],
        //彩蛋结束
        "activity_egg_end"=>[
            "activity_egg_end_layer"=>0,//结束层数
            "activity_egg_end_type"=>0,//结束方式(1通关、2领奖退出、3放弃退出)
            "activity_egg_end_reward_spin"=>0,//获得体力
            "activity_egg_end_reward_coin"=>0,//获得金币
            "activity_egg_end_reward_petfood"=>0,//获得宠物食物
            "activity_egg_end_reward_petexp"=>0,//获得宠物经验
            "activity_egg_end_reward_chest_list"=>[],//获得宝箱(宝箱id列表)
            "activity_egg_end_reward_activity"=>0,//获得活动id
            "activity_egg_end_reward_activity_time"=>0,//获得活动时长
            "activity_egg_end_reward_card_list"=>[],//获得卡牌(可能会有小丑卡)
            "activity_egg_end_reward_card_joker"=>0,
        ],
        //通行证升级
        "activity_pass_levelup"=>[
            "activity_pass_levelup_before"=>0,//通行证升级前等级
            "activity_pass_levelup_after"=>0,//通行证升级后等级
        ],
        //通行证领奖
        "activity_pass_reward"=>[
            "activity_pass_reward_type"=>0,//奖励类型(1免费2付费)
            "activity_pass_reward_spin"=>0,//获得体力
            "activity_pass_reward_coin"=>0,//获得金币
            "activity_pass_reward_petfood"=>0,//获得宠物食物
            "activity_pass_reward_petexp"=>0,//获得宠物经验
            "activity_pass_reward_chest_list"=>[],//获得宝箱(宝箱id列表)
            "activity_pass_reward_activity"=>0,//获得活动id
            "activity_pass_reward_activity_time"=>0,//获得活动时长
            "activity_pass_reward_card_list"=>[],//获得卡牌(可能会有小丑卡)
            "activity_pass_reward_card_joker"=>0,
        ],
        //宝箱获得/开启
        "chest"=>[
            "chest_id"=>0,//宝箱id
            "chest_source"=>0,//获取途径
            "chest_activity_ratio"=>0,//卡牌大爆炸倍率
            "chest_reward_card_list"=>[],//获得卡牌
        ],
        //宝箱获得/开启
        "chest_sp"=>[
            "chest_id"=>0,//宝箱id
            "chest_source"=>0,//获取途径
            "chest_activity_ratio"=>0,//活动加成
            "chest_reward_spin"=>0,//获得体力
            "chest_reward_coin"=>0,//获得金币
            "chest_reward_petfood"=>0,//获得宠物食物
            "chest_reward_petexp"=>0,//获得宠物经验
            "chest_reward_card_list"=>[],//获得活动id
            "chest_reward_card_joker"=>0,//获得卡牌(可能会有小丑卡)
        ],
        //赠送卡片
        "card_send"=>["card_list"=>[],"card_send_object_user"=>0],//[卡片id列表,赠送对象玩家id]
        //接受赠送卡片
        "card_accept"=>["card_id"=>0,"card_accept_from_user"=>0],//[卡片id,接受来源玩家id]
        //索要卡片(客户端)
        "card_ask"=>["card_id"=>0],//[卡片id]
        //回应索要卡片(客户端)
        "card_respond"=>["card_id"=>0,"card_ask_user"=>0],//[卡片id,索要玩家id]
        //赠送体力
        "spin_send"=>["spin_send_object_user"=>0,"spin_send_num"=>0],//[赠送对象玩家id,赠送体力数量]
        //接受其他人赠送体力
        "spin_accept"=>["spin_accept_from_user"=>0,"spin_accept_num"=>0],//[接受来源玩家id,接受体力数量]
        //赠送金币
        "coin_send"=>["coin_send_object_user"=>0,"coin_send_num"=>0],//[赠送对象玩家id,赠送金币数量]
        //接受其他人赠送金币
        "coin_accept"=>["coin_accept_from_user"=>0,"coin_accept_num"=>0],//[接受来源玩家id,接受金币数量]
        //卡组完成
        "cardset_complate"=>[
            "cardset_id"=>0,//卡组id
            "cardset_activity_ratio"=>0,//卡组完成疯狂卡组加成
            "cardset_reward_spin"=>0,//获得体力
            "cardset_reward_coin"=>0,//获得金币
            "cardset_reward_petfood"=>0,//获得宠物食物
            "cardset_reward_petexp"=>0,//获得宠物经验
        ],
        //资源获取(上面有的记录不需要重复记录)
        "resource_obtain"=>[
            "resource_obtain_name"=>"",//获取资源名称
            "resource_obtain_num"=>0,//获取资源数量
            "resource_obtain_newnum"=>0,//获取后数量
            "resource_obtain_type"=>0,//获取途径
            "resource_obtain_ext"=>[],//备用扩展
        ],
        //消耗资源时记录(上面有的记录不需要重复记录)
        "resource_cost"=>[
            "resource_cost_name"=>"",//消耗资源名称
            "resource_cost_num"=>0,//消耗资源数量
            "resource_cost_newnum"=>0,//消耗后数量
            "resource_cost_type"=>0,//消耗途径
            "resource_cost_ext"=>[],//备用扩展
        ],
        //资源产销(当天)
        "resource_list"=>[
            "obtain_spin"=>0,//获得体力
            "cost_spin"=>0,//消耗体力
            "obtain_coin"=>0,//获得金币
            "cost_coin"=>0,//消耗金币
            "obtain_card"=>0,//获得卡牌数量
            "cost_card"=>0,//消耗卡牌数量
            "spin_times"=>0,//旋转次数
            "date"=>"",//资源产销上报日期
            "uid"=>0,//用户id
            "level_id"=>0,//用户等级
            "obtain_card_list"=>[],//资源产销获得卡牌列表
            "cost_card_list"=>[],//资源产销消耗卡牌列表
            "stock_card_list"=>[]//昨日卡牌列表
        ]
    ];
    /**
     * Notes:格式化数据结构-获取数数事件道具奖励
     * User: wsc
     * Time: 2021/5/13 18:31
     * @param $props
     * @param $fields array 字段数量需与$data保持一致性
     * @return array
     */
    public function getPropsSSEventData($props,$fields=[]){
        $data =[
            "reward_spin" =>0,
            "reward_coin"=>0,
            "reward_petfood"=>0,
            "reward_petexp" =>0,
            "reward_chest_list"=>[],
            "reward_activity" =>0,
            "reward_activity_time" =>0,
            "reward_card_list"=>[],
            "reward_card_joker"=>0,
        ];
        $arr1= array_keys($fields);
        $arr2= array_keys($data);
        if(!empty($fields)&&count($arr1)!=count($arr2)){
            return $fields;
        }
        krsort($data);
        krsort($fields);  
        if(!empty($props)){
            foreach ($props as $row){
                if($row['propsId'] == 14){
                    $data['reward_coin'] += $row['num'];
                }else if($row['propsId'] == 15){
                    $data['reward_spin'] += $row['num'];
                }else if($row['propsId'] == 9){
                    $data['reward_petfood'] += $row['num'];
                }else if($row['propsId'] == 8){
                    $data['reward_petexp'] += $row['num'];
                }else if($row['propsId'] == 18){
                    $data['reward_card_joker']=1;
                }else if($row['propsId'] == 13){
                   !empty($row['value'][0]['id'])?array_push($data['reward_card_list'],(string)intval($row['value'][0]['id'])):true;
                }
                else if($row['propsId'] == 19){
                    $data['reward_card_list'] = !empty($row['value']['card'])?array_merge($data['reward_card_list'],array_column($row['value']['card'],'id')):$data['reward_card_list'];
                    $data['reward_card_joker'] = $row['value']['joker'] > 0||$data['reward_card_joker'] ? 1 : 0;
                    if(!empty($row['value']['props'])){
                        foreach ($row['value']['props'] as $vRow){
                            if($vRow['propsId'] == 14){
                                $data['reward_coin'] += $vRow['num'];
                            }else if($vRow['propsId'] == 15){
                                $data['reward_spin'] += $vRow['num'];
                            }else if($vRow['propsId'] == 9){
                                $data['reward_petfood'] += $vRow['num'];
                            }else if($vRow['propsId'] == 8){
                                $data['reward_petexp'] += $vRow['num'];
                            }
                        }
                    }
                    array_push($data['reward_chest_list'],(string)$row['value']['skin']);
                }else if(in_array($row['propsId'],[25, 26, 27, 28, 31, 32, 33, 35, 36, 39, 40, 41])){
                    $data['reward_activity'] = $row['propsId'];
                    $data['reward_activity_time'] = $row['num'];
                }
            }
        }

        $eventData =[];
        foreach ($arr2 as $k=>$v){
            $eventData[$arr1[$k]] = $data[$v];
        }
        return !empty($fields)?$eventData:$data;
    }


    public function initCommonEventProperty($uid){
        $levelInfo  = oo::commonOprModel('member')->getUserLevel($uid);
        $userStatisticsInfo = oo::commonOprModel('statistics')->getUserStatistics($uid);
        return [
            "current_level"          => $levelInfo['levelId'],
            "current_vip_level"      => oo::commonOprModel('newvip')->getUserVipLv($uid, false,false,155),
            "current_building_level" => array_sum(array_column($levelInfo['element'],"level")),//1,
            "total_play_time"        => $userStatisticsInfo['playTime'],
            "current_play_time"      => 0,
            "total_login_days"       => $userStatisticsInfo['loginDays'],//初始化
            "continuity_login_days"  => $userStatisticsInfo['continuityLoginDays'],//初始化
            "total_pay"              => oo::commonOprModel('payment')->getUserTotalPayNum($uid),
            "activity_list"          => "",
            "pack_list"              => "",
            "is_debug"               =>IS_DEBUF,
        ];
    }
    public function makeCollectInfo($uid){
        if(!$this->lock['all']){
            return false;
        }
        $actInfo = oo::commonOprModel('activitynew')->activityLock($uid,"super_collect",true);
        $cacheKey= $this->keys['common'].$uid."collect";
        oo::commonOprRedis('statistics')->hMset($cacheKey,[
            "activity_collect_id"               => intval($actInfo['activityData']['aid']),
            "activity_collect_type"             => intval($actInfo['activityData']['groupId']),
            "activity_collect_spin_range"       => !empty($actInfo['userData']['spinRange'])?implode('-',$actInfo['userData']['spinRange']):"0-0",
            "activity_collect_layer"            => intval($actInfo['userData']['stage']),
            "activity_collect_symbol_current"   => intval($actInfo['userData']['num']),
            "activity_collect_symbol_need"      => intval($actInfo['userData']['maxNum']),
            "activity_collect_symbol_total"     => intval($actInfo['userData']['total']),
            "activity_collect_remining_time"    => intval($actInfo['activityData']['end']),
        ]);
        oo::commonOprRedis('statistics')->expire($cacheKey,max(0,intval($actInfo['activityData']['end']) - time()));
    }

    public function makeRankInfo($uid){
        if(!$this->lock['all']){
            return false;
        }
        $actInfo = oo::commonOprModel('activitynew')->activityLock($uid,"rank",true);
        $cacheKey= $this->keys['common'].$uid."rank";
        oo::commonOprRedis('statistics')->hMset($cacheKey,[
            "activity_rank_id"                  => intval($actInfo['activityData']['aid']),
            "activity_rank_ranking"             => intval($actInfo['userData']['curRankId']),
            "activity_rank_layer"               => intval($actInfo['userData']['curRankProgressId']),
            "activity_rank_symbol"              => intval($actInfo['userData']['curRankNum']),
            "activity_rank_remining_time"       => intval($actInfo['activityData']['end']),
        ]);
        oo::commonOprRedis('statistics')->expire($cacheKey,max(0,intval($actInfo['activityData']['end']) - time()));
    }
    public function getCollectInfo($uid){
        $actInfo = oo::commonOprRedis('statistics')->hGetAll($this->keys['common'].$uid."collect");
        return [
            "activity_collect_id"               => empty($actInfo)? 0  :intval($actInfo['activity_collect_id']),
            "activity_collect_type"             => empty($actInfo)? 0  :intval($actInfo['activity_collect_type']),
            "activity_collect_spin_range"       => empty($actInfo)? "0-0" :$actInfo['activity_collect_spin_range'],
            "activity_collect_layer"            => empty($actInfo)? 0  :intval($actInfo['activity_collect_layer']),
            "activity_collect_symbol_current"   => empty($actInfo)? 0  :intval($actInfo['activity_collect_symbol_current']),
            "activity_collect_symbol_need"      => empty($actInfo)? 0  :intval($actInfo['activity_collect_symbol_need']),
            "activity_collect_symbol_total"     => empty($actInfo)? 0  :intval($actInfo['activity_collect_symbol_total']),
            "activity_collect_remining_time"    => empty($actInfo)? 0  :intval($actInfo['activity_collect_remining_time']),
        ];
    }

    public function getRankInfo($uid){
        $actInfo = oo::commonOprRedis('statistics')->hGetAll($this->keys['common'].$uid."rank");
        return [
            "activity_rank_id"                  => empty($actInfo)? 0 :intval($actInfo['activity_rank_id']),
            "activity_rank_ranking"             => empty($actInfo)? 0 :intval($actInfo['activity_rank_ranking']),
            "activity_rank_layer"               => empty($actInfo)? 0 :intval($actInfo['activity_rank_layer']),
            "activity_rank_symbol"              => empty($actInfo)? 0 :intval($actInfo['activity_rank_symbol']),
            "activity_rank_remining_time"       => empty($actInfo)? 0 :intval($actInfo['activity_rank_remining_time']),
        ];
    }

    public function getCommonEventProperty($uid){
        $cacheKey = $this->keys['common'].$uid."common";
        $info = oo::commonOprRedis('statistics')->hGetAll($cacheKey);
        if(empty($info)){
            $info = $this->initCommonEventProperty($uid);
            oo::commonOprRedis('statistics')->hMset($cacheKey,$info);
            oo::commonOprRedis('statistics')->expire($cacheKey,oo::todayDeadline());
        }
        $info = array_merge($info,$this->getRankInfo($uid),$this->getCollectInfo($uid));
        $curTime = time();
        $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $info["current_spin"] = $assetsInfo['spins'];
        $info["current_coin"] = $assetsInfo['money'];
        $info["current_star"] = $assetsInfo['star'];
        $cacheKey = okeys::UserStatistics($uid);
        $info["total_obtain_spin"] = oo::commonOprRedis('Statistics')->hGet($cacheKey,"obtainSpin");
        $info["total_cost_spin"]   = oo::commonOprRedis('Statistics')->hGet($cacheKey,"costSpin");
        $info["total_spin_times"]  = oo::commonOprRedis('Statistics')->hGet($cacheKey,"spinTimes");
        $info["activity_list"]     = array_filter(explode(",",$info["activity_list"]));
        foreach ($info["activity_list"] as $i=>$x){
            $info["activity_list"][$i] = "".$x;
        }
        $info["pack_list"]         = array_filter(explode(",",$info["pack_list"]));
        foreach ($info["pack_list"] as $i=>$x){
            $info["pack_list"][$i] = "".$x;
        }
        $info["current_play_time"] = $curTime - $info["current_play_time"];
        $info["total_play_time"]   = intval($info["total_play_time"]) + intval($info["current_play_time"]);
        $info["activity_collect_remining_time"] = max($info["activity_collect_remining_time"] - $curTime,0);
        $info["activity_rank_remining_time"]    = max($info["activity_rank_remining_time"] - $curTime,0);
        return $info;
    }

    public function setCommonEventProperty($uid,$type,$info){
        if(!$this->lock['all']){
            return false;
        }
        $cacheKey = $this->keys['common'].$uid.$type;
        if(!oo::commonOprRedis('statistics')->exists($cacheKey)&&$type=='common'){
            $this->getCommonEventProperty($uid); // 初始化数据
        }
        foreach ($info as $key=>$row){
            oo::commonOprRedis('statistics')->hSet($cacheKey,$key,$row);
        }
        return true;
    }

    public function addCommonEventProperty($uid,$type,$info){
        if(!$this->lock['all']){
            return false;
        }
        $cacheKey = $this->keys['common'].$uid.$type;
        if(!oo::commonOprRedis('statistics')->exists($cacheKey)){
            $this->getCommonEventProperty($uid); // 初始化数据
        }
        foreach ($info as $key=>$row){
            oo::commonOprRedis('statistics')->hIncrBy($cacheKey,$key,$row);
        }
        return true;
    }

    /**
     * Notes:登录预设用户系统属性
     * User: wsc
     * Time: 2021/5/11 17:03
     * @param $uid
     * @param $info ["device_id","os","os_version","app_version"] //[设备id,操作系统,操作系统版本,app版本号]
     * @return bool
     */
    public function setSysEventProperty($uid,$info){
        if(!$this->lock['all']){
            return false;
        }
        $key = $this->keys['userSysAttr'].$uid;
        oo::commonOprRedis('statistics')->hMset($key,$info);
        return true;
    }
    /**
     * Notes:获取系统属性
     * User: wsc
     * Time: 2021/5/11 16:42
     * @param $uid
     * @return array
     */
    public function getSysEventProperty($uid){
        $key = $this->keys['userSysAttr'].$uid;
        $data =oo::commonOprRedis('statistics')->hGetAll($key);
        $data = !empty($data)?$data:[];
        return $data;
    }

    /**
     * Notes:定时设置用户昨日资源产销事件
     * User: wsc
     * Time: 2021/5/18 16:01
     * @return bool
     */
    public function cronToSendUserDayData(){
        $time = strtotime('-1 day');
        $yesterday = date( 'Ymd',  $time);
        $uidList=oo::commonOprModel('statistics')->getAllPlayer($yesterday,2,[1,2]);
        foreach ($uidList as $uid){
            $userInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
            $eventData = oo::commonOprRedis("statistics")->hGetAll(okeys::UserDayData($uid,$yesterday));
            $eventData = array_merge($this->events['resource_list'],$eventData);
            $eventData['date'] = date("Y-m-d H:i:s",strtotime($yesterday));
            $eventData['uid'] = intval($uid);
            $eventData["level_id"] = $userInfo["levelId"];
            $eventData["stock_spin"] = $userInfo["spins"];
            $eventData["stock_coin"] = $userInfo["money"];
            //用户卡片数据上报
            $ObtainCardList  =oo::commonOprRedis("statistics")->hGetAll(okeys::UserDayObtainCardList($uid,$yesterday));//昨日获得卡片列表
            $CostCardList  =oo::commonOprRedis("statistics")->hGetAll(okeys::UserDayCostCardList($uid,$yesterday));//昨日消耗卡片列表
            $cardInfo =oo::commonOprModel('card')->getUserCardInfo($uid);
            $sumLostCardNum = $sumGetCardNum =0;
            $userAllCardList = $cardInfo['ciid'];//用户卡片存量
            if(!empty($ObtainCardList)&&is_array($ObtainCardList)){
                foreach ($ObtainCardList as $k=>$v){
                    $sumGetCardNum+=$v;
                    $eventData["obtain_card_list"][] = (string)$k;
                }
                sort($eventData["obtain_card_list"]);
                oo::commonOprRedis('statistics')->delete(okeys::UserDayObtainCardList($uid,$yesterday));
            }
            if(!empty($CostCardList)&&is_array($CostCardList)){
                foreach ($CostCardList as $k=>$v){
                    $sumLostCardNum+=$v;
                    $eventData["cost_card_list"][] = (string)$k;
                }
                sort($eventData["cost_card_list"]);
                oo::commonOprRedis('statistics')->delete(okeys::UserDayCostCardList($uid,$yesterday));
            }
            $eventData["obtain_card"] =  $sumGetCardNum;
            $eventData["cost_card"]   =  $sumLostCardNum;
            if(!empty($userAllCardList)&&is_array($userAllCardList)){
                foreach ($userAllCardList as $k=>$v){
                    $eventData["stock_card_list"][] = (string)$k;
                }
                sort($eventData["stock_card_list"]);
            }
            $this->setEventData($uid,"resource_list",$eventData);
        }
        return true;
    }

    /**
     * Notes:设置事件结构化数据
     * User: wsc
     * Time: 2021/5/11 15:55
     * @param $uid
     * @param $event
     * @param $data
     * @return bool|array
     */
    public function setEventData($uid,$event,$data=[]){
        if(intval($uid)<=0){
            return false;
        }
        //开发环境也不上报数数平台
        if(!$this->lock['all']||!$this->lock[$event]){
            return false;
        }
        if(!in_array($event,["user_setOnce","user_set","resource_list"])){
            if(!$uid||!in_array($event,array_keys($this->events))){
                return false;
            }
            if(!in_array($event,["user_create"])&&empty($data)){//不在空属性事件内,且属性数据为空
                return false;
            }
            $sysData = $this->getSysEventProperty($uid);
            $commData = $this->getCommonEventProperty($uid);

            //事件属性断言
            $data = $this->getSuccessTypeData($this->events[$event],$data);
            $commData = $this->getSuccessTypeData($this->events["userCommon"],$commData);

            $datas = array_merge($this->events[$event],$data,$commData,$sysData);
        }else{
            $thisEvent = $event=='user_setOnce'?"user_set":$event;
            $datas = $this->getSuccessTypeData($this->events[$thisEvent],$data);
            $datas['is_debug'] = IS_DEBUF;
        }
        $key = $this->keys['event'].$event;
        $time = IS_DEBUF?time():time()+8*3600;
        $datas["#time"] = date("Y-m-d H:i:s",$time);
        $arr = [
            "accountId"=>intval($uid),
            "distinctId"=>(string)$datas['distinctId'],
            "eventName"=>(string)$event,
            "properties"=>$datas
        ];
        oo::commonOprRedis('statistics')->rPush($key,json_encode($arr));
        return true;
    }

    /**
     * Notes:数据类型断言转换
     * User: wsc
     * Time: 2021/5/24 15:40
     * @param $model array 数据类型模板
     * @param $data array 数组数据
     * @return mixed
     */
    public function  getSuccessTypeData($model,$data){
        foreach ($model as $k=>$v){
            if(isset($data[$k])){
                if(is_int($v)){
                    $data[$k] = intval($data[$k]);
                }
                if(is_float($v)){
                    $data[$k] = floatval($data[$k]);
                }
                if(is_string($v)){
                    $data[$k] = (string)$data[$k];
                }
                if(is_bool($v)){
                    $data[$k] = $data[$k]?true:false;
                }
            }
        }
        return $data;
    }

    public function cronToSendUserDayDataNew(){
        $consumer = new FileConsumer("./deBUG/shushulog", 200, true, "ta");
        TALogger::$enable = false;
        $teSDK = new ThinkingDataAnalytics($consumer, true);
        $time = strtotime('-1 day');
        $yesterday = date( 'Ymd',  $time);
        $uidList=oo::commonOprModel('statistics')->getAllPlayer($yesterday,2,[1,2]);
        $mm=0;
        foreach ($uidList as $uid){
            $userInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
            $eventData = oo::commonOprRedis("statistics")->hGetAll(okeys::UserDayData($uid,$yesterday));
            $eventData = array_merge($this->events['resource_list'],$eventData);
            $eventData['date'] = date("Y-m-d H:i:s",strtotime($yesterday));
            $eventData['uid'] = intval($uid);
            $eventData["level_id"] = $userInfo["levelId"];
            $eventData["stock_spin"] = $userInfo["spins"];
            $eventData["stock_coin"] = $userInfo["money"];
            //用户卡片数据上报
            $ObtainCardList  =oo::commonOprRedis("statistics")->hGetAll(okeys::UserDayObtainCardList($uid,$yesterday));//昨日获得卡片列表
            $CostCardList  =oo::commonOprRedis("statistics")->hGetAll(okeys::UserDayCostCardList($uid,$yesterday));//昨日消耗卡片列表
            $cardInfo =oo::commonOprModel('card')->getUserCardInfo($uid);
            $sumLostCardNum = $sumGetCardNum =0;
            $userAllCardList = $cardInfo['ciid'];//用户卡片存量
            if(!empty($ObtainCardList)&&is_array($ObtainCardList)){
                foreach ($ObtainCardList as $k=>$v){
                    $sumGetCardNum+=$v;
                    $eventData["obtain_card_list"][] = (string)$k;
                }
                sort($eventData["obtain_card_list"]);
                oo::commonOprRedis('statistics')->delete(okeys::UserDayObtainCardList($uid,$yesterday));
            }
            if(!empty($CostCardList)&&is_array($CostCardList)){
                foreach ($CostCardList as $k=>$v){
                    $sumLostCardNum+=$v;
                    $eventData["cost_card_list"][] = (string)$k;
                }
                sort($eventData["cost_card_list"]);
                oo::commonOprRedis('statistics')->delete(okeys::UserDayCostCardList($uid,$yesterday));
            }
            $eventData["obtain_card"] =  $sumGetCardNum;
            $eventData["cost_card"]   =  $sumLostCardNum;
            $allCards = array_keys($userAllCardList);
            if(!empty($allCards)&&is_array($allCards)){
                sort($allCards);
                $arr = [];
                $i=$j=0;
                foreach ($allCards as $cid){
                    $arr[$j][] = intval($cid);
                    $i++;
                    if($i%270==0){
                        $j++;
                    }
                }
                $eventData["stock_card_list_new"] = $arr;
            }
            $eventData["#time"] = date("Y-m-d H:i:s",IS_DEBUF?time():time()+8*3600);
            try {
                $teSDK->track("", $uid, "resource_list", $eventData);
                $mm++;
            } catch (Exception $e) {
                oo::logs()->commlog("shushu_log err:{$e}",'crontab/shushuUpLog');
                echo $e;
            }
        }
        $teSDK->flush();
        oo::logs()->commlog("shushu_log over {$mm}",'crontab/shushuUpLog');
    }

//================用户广告源数据上报==================
    function getAdDataByDay($date = "2022-04-10"){
        $adjustDataTb = otable::AdJustData();
        $startTs = strtotime($date);
        $endTs = strtotime($date)+86400;
        $sql = 'SELECT *  FROM '.$adjustDataTb.'  WHERE created_at>='.$startTs.' and created_at<='.$endTs." ";
        $arr = oo::commonOprDb('common')->getAll($sql,1);
        $uTb = otable::userinfo();
//        $sql2= "SELECT min(uid) as minUid,max(uid) as maxUid FROM {$uTb} where createtime>={$startTs} and createtime<={$endTs}";
//        $uArr =oo::commonOprDb('common')->getOne($sql2,1);
        echo "日期:{$date}";
        echo "累计回调数:".count($arr)."\r\n";
//        echo "注册用户数:".($uArr['maxUid']-$uArr['minUid'])."\r\n";
        if(!empty($arr)){
            $gpsAdidslist = array_column($arr,null,'gps_adid');
            unset($gpsAdidslist[""]);
            $adidsList =array_column($arr,null,'adid');
            unset($adidsList[""]);
            $idfasList =array_column($arr,null,'idfa');
            unset($idfasList[""]);
            $iosAdidsList =array_merge($adidsList,$idfasList);

            $list1 = $this->getAdEventData($gpsAdidslist,'android',$date);
            $list2 = $this->getAdEventData($iosAdidsList,'ios',$date);

            $allList = array_merge($list1,$list2);
            echo "最终上报用户数:".count($allList)."\r\n";
//            $allList2 = array_unique($allList);
//            echo "去重最终上报用户数:".count($allList2)."\r\n";
        }
    }
    function getAdEventData($Adidslist,$os,$date="",$uArr=[]){
        $keys = array_keys($Adidslist);
        unset($keys[""]);
        $listStr = '"'.implode('","',$keys).'"';
        $uidList=$androidUinfoList= [];
//    $w2 = "uid>={$uArr['minUid']} and uid<={$uArr['maxUid']} and  ";
        $w2 = "";
        for ($i=100;$i>0;$i--){
            $tb2 = otable::AdJustSta($i);
            $sql2 = 'SELECT uid,'.$os.' as aid FROM '.$tb2.' WHERE '.$w2.$os.' in ('.$listStr.')';
            $arr2 = oo::commonOprDb('common')->getAll($sql2,1);
            foreach ($arr2 as $item){
                if(!empty($item['aid'])){
                    array_push($uidList,$item['uid']);
                    $androidUinfoList[$item['uid']] = $item['aid'];
                }
            }
        }
        // var_dump($androidUinfoList);
        $p = '/\((\d+)\)$/';
        // var_dump($uidList);
        foreach ($uidList as $uid){
            if(!$uid){
                continue;
            }
            $network_name = $Adidslist[$androidUinfoList[$uid]]['network_name'];
//        if(in_array($network_name,["Facebook Installs","Off-Facebook Installs","Facebook Messenger Installs"])){
//            $network_name = "facebook";
//        }
//        else if(in_array($network_name,["Google Ads UAC","Google Ads ACI","Google Ads Video"])){
//            $network_name = "google";
//        }
            $campaign_name =$Adidslist[$androidUinfoList[$uid]]['campaign_name'];
            preg_match($p,$campaign_name,$campaign_name_arr);
            $adgroup_name =$Adidslist[$androidUinfoList[$uid]]['adgroup_name'];
            preg_match($p,$adgroup_name,$adgroup_name_arr);
            $creative_name =$Adidslist[$androidUinfoList[$uid]]['creative_name'];
            preg_match($p,$creative_name,$creative_name_arr);
            $campaign_id = isset($campaign_name_arr[1])?$campaign_name_arr[1]:0;
            $adgroup_id = isset($adgroup_name_arr[1])?$adgroup_name_arr[1]:0;
            $creative_id = isset($creative_name_arr[1])?$creative_name_arr[1]:0;
            $event_aid = sprintf("%s_%s_%s_%s",$date,intval($campaign_id),intval($adgroup_id),intval($creative_id));
            $one =[
                "uid"=>$uid,
                "tracker_name"=>$Adidslist[$androidUinfoList[$uid]]['tracker_name'],
                "adjust_adid"=>$Adidslist[$androidUinfoList[$uid]]['adid'],
                "campaign_name"=>$campaign_name,
                "adgroup_name"=>$adgroup_name,
                "creative_name"=>$creative_name,
                "campaign_id"=>$campaign_id,
                "adgroup_id"=>$adgroup_id,
                "creative_id"=>$creative_id,
                "network_name"=>$network_name,
                "event_aid"=>$event_aid
            ];
            $EventData[] =$one;
            unset($one['uid']);
            $this->setEventData($uid,"user_set",$one);
        }
        return $EventData;
    }
//===============用户广告源数据及花费上报============
    function getSpendData($date = "2022-04-10"){
        $tbs = [
            "apple"       =>["table"=>"t_apple_campain","field"=>"campain_id","spend"=>"spend"],  //apple       广告系列id  campain_id
            "applovin"    =>["table"=>"t_applovin_campain","field"=>"id","spend"=>"spend"],       //applovin    广告系列id  id
            "chartboost"  =>["table"=>"t_chartboost_campain","field"=>"id","spend"=>"spend"],     //chartboost  广告系列id  id
            "facebook"    =>["table"=>"t_facebook_ads","field"=>"ad_id","spend"=>"spend"],        //facebook    广告id      ad_id   date_start
            "google"      =>["table"=>"t_google_views","field"=>"ad_group_id","spend"=>"spend"],  //google      广告id      ad_id
            "ironsource"  =>["table"=>"t_ironsource_campain","field"=>"id","spend"=>"spend"],     //ironsource  广告系列id  id
            "mintegral"   =>["table"=>"t_mintegral_campain","field"=>"id","spend"=>"spend"],      //mintegral   广告系列id  id
            "tiktok"      =>["table"=>"t_tiktok_campain","field"=>"ad_id","spend"=>"spend"],       //tiktok     广告id      ad_id
            "unity"       =>["table"=>"t_unity_campain","field"=>"id","spend"=>"spend"],            //unity      广告系列id  id
            "vungle"      =>["table"=>"t_vungle_campain","field"=>"ad_id","spend"=>"spend"],         //tiktok     广告系列id  ad_id
        ];
        $dates = [];
        for($i=7;$i--;){
            $oneDate = date("Y-m-d",strtotime("{$date} -{$i} day"));
            array_push($dates,$oneDate);
        }
        $datesStr = '"'.implode('","',$dates).'"';
        foreach ($tbs as $k=>$tbOne){
            $dateField = "data_start";
            if($k=="facebook"){
                $dateField = "date_start";
            }
            $sql = "SELECT {$tbOne['field']} as id,sum(spend) as spends FROM {$tbOne['table']} WHERE $dateField in ($datesStr)  GROUP BY {$tbOne['field']} having spends>0";
            $one = oo::commonOprDb('report')->getAll($sql,1);
            if($one){
                $adList[$k] = $one ;
            }
        }
        $startTs = strtotime($date)-6*86400;
        $endTs = strtotime($date)+86400;
        $adjustDataTb = otable::AdJustData();
        $i=0;
        foreach ($adList as $k=>$oneAdInfo){
            foreach ($oneAdInfo as $key => $item) {
                $i++;
                $spends = $item['spends'];
                $from = "campaign_name";
                if(in_array($k,["facebook","tiktok"])){
                    $from = "creative_name";
//                    echo "{$k}-广告:{$item['id']},花费:{$spends}\r\n";
                }else if(in_array($k,["google"])){
                    $from = "adgroup_name";
//                    echo "{$k}-广告组:{$item['id']},花费:{$spends}\r\n";
                }else{
//                    echo "{$k}-广告系列:{$item['id']},花费:{$spends}<br>\r\n";
                }

                $sql = 'SELECT *  FROM '.$adjustDataTb.'  WHERE created_at>='.$startTs.' and created_at<='.$endTs.' and '.$from.' LIKE "%'.$item['id'].'%"';
                $arr = oo::commonOprDb('common')->getAll($sql,1);
                $callbackTotal = count($arr);
//                echo "回调用户数:{$callbackTotal}<br>\r\n";
                if(!empty($arr)){
                    $Adidslist = array_column($arr,null,'gps_adid');
                    $os = 'android';
                    unset($Adidslist[""]);
                    if(empty($Adidslist)){
                        $adidsList =array_column($arr,null,'adid');
                        $idfasList =array_column($arr,null,'idfa');

                        $iosAdids =array_merge($adidsList,$idfasList);
                        unset($iosAdids[""]);
                        if(!empty($iosAdids)){
                            $Adidslist = $iosAdids;
                            $os = 'ios';
                        }
                    }
                    if(empty($Adidslist)){
                        echo "七日未带来安装:0\r\n";
                        continue;
                    }
                    $allList = $this->getUserAdsEventDatas($Adidslist,$os);
//                    $instellNum = count($allList);
//                    echo "广告:{$arr[0]['tracker_name']},七天总花费:{$spends},七日总安装:{$instellNum}<br>\r\n";
                    $oneSpend = round($spends/count($allList),4);
                    foreach ($allList as $item3){
                        $one = $item3;
                        $uid = $item3['uid'];
                        $one['spend'] = $oneSpend;
                        unset($one['uid']);
                        oo::commonOprModel('ta')->setEventData($uid,"user_set",$one);
                    }
//                    if($i%10==0){
//                        echo "\r\n====over:{$i}======\r\n";
//                    }
                }

            }

        }
    }
    function getUserAdsEventDatas($Adidslist,$os="android"){
        $listStr = '"'.implode('","',array_keys($Adidslist)).'"';
        $uidList=$UinfoList= [];
        for ($i=100;$i>0;$i--){
            $tb2 = otable::AdJustSta($i);
            $sql2 = 'SELECT uid,'.$os.' as aid FROM '.$tb2.' WHERE ' .$os. ' in ('.$listStr.')';
            $arr2 = oo::commonOprDb('common')->getAll($sql2,1);
            foreach ($arr2 as $item2){
                array_push($uidList,$item2['uid']);
                $UinfoList[$item2['uid']] = $item2['aid'];
            }
        }
        $p = '/\((\d+)\)$/';
        foreach ($uidList as $uid){
            $campaign_name =$Adidslist[$UinfoList[$uid]]['campaign_name'];
            preg_match($p,$campaign_name,$campaign_name_arr);
            $adgroup_name =$Adidslist[$UinfoList[$uid]]['adgroup_name'];
            preg_match($p,$adgroup_name,$adgroup_name_arr);
            $creative_name =$Adidslist[$UinfoList[$uid]]['creative_name'];
            preg_match($p,$creative_name,$creative_name_arr);
            $campaign_id = isset($campaign_name_arr[1])?$campaign_name_arr[1]:0;
            $adgroup_id = isset($adgroup_name_arr[1])?$adgroup_name_arr[1]:0;
            $creative_id = isset($creative_name_arr[1])?$creative_name_arr[1]:0;
            $AndroidEventData[] =[
                "uid"=>$uid,
                "tracker_name"=>$Adidslist[$UinfoList[$uid]]['tracker_name'],
                "adjust_adid"=>$Adidslist[$UinfoList[$uid]]['adid'],
                "network_name"=>$Adidslist[$UinfoList[$uid]]['network_name'],
                "campaign_name"=>$Adidslist[$UinfoList[$uid]]['campaign_name'],
                "adgroup_name"=>$Adidslist[$UinfoList[$uid]]['adgroup_name'],
                "creative_name"=>$Adidslist[$UinfoList[$uid]]['creative_name'],
                "campaign_id"=>$campaign_id,
                "adgroup_id"=>$adgroup_id,
                "creative_id"=>$creative_id,
            ];
        }
        return $AndroidEventData;
    }
//=================上报7日广告用户人均成本===========
    function subAdUidSpendList($date = "2022-04-10"){
        $tbs = [
            "apple"       =>["table"=>"t_apple_campain","field"=>"campain_id","spend"=>"spend"],  //apple       广告系列id  campain_id
            "applovin"    =>["table"=>"t_applovin_campain","field"=>"id","spend"=>"spend"],       //applovin    广告系列id  id
            "chartboost"  =>["table"=>"t_chartboost_campain","field"=>"id","spend"=>"spend"],     //chartboost  广告系列id  id
            "facebook"    =>["table"=>"t_facebook_ads","field"=>"ad_id","spend"=>"spend"],        //facebook    广告id      ad_id   date_start
            "google"      =>["table"=>"t_google_views","field"=>"ad_group_id","spend"=>"spend"],  //google      广告id      ad_id
            "ironsource"  =>["table"=>"t_ironsource_campain","field"=>"id","spend"=>"spend"],     //ironsource  广告系列id  id
            "mintegral"   =>["table"=>"t_mintegral_campain","field"=>"id","spend"=>"spend"],      //mintegral   广告系列id  id
            "tiktok"      =>["table"=>"t_tiktok_campain","field"=>"ad_id","spend"=>"spend"],       //tiktok     广告id      ad_id
            "unity"       =>["table"=>"t_unity_campain","field"=>"id","spend"=>"spend"],            //unity      广告系列id  id
            "vungle"      =>["table"=>"t_vungle_campain","field"=>"ad_id","spend"=>"spend"],         //tiktok     广告系列id  ad_id
        ];
        $dates = [];
        for($i=7;$i--;){
            $oneDate = date("Y-m-d",strtotime("{$date} -{$i} day"));
            array_push($dates,$oneDate);
        }
        $datesStr = '"'.implode('","',$dates).'"';
        foreach ($tbs as $k=>$tbOne){
            $dateField = "data_start";
            if($k=="facebook"){
                $dateField = "date_start";
            }
//        $sql = "SELECT $dateField as data_start,{$tbOne['field']} as id,sum(spend) as spends FROM {$tbOne['table']} WHERE $dateField = '$date'  GROUP BY {$tbOne['field']} having spends>0";
            $sql = "SELECT {$tbOne['field']} as id,sum(spend) as spends FROM {$tbOne['table']} WHERE $dateField in ($datesStr)  GROUP BY {$tbOne['field']} having spends>0";
//        echo " $sql";exit;
            $one = oo::commonOprDb('report')->getAll($sql,1);
            if($one){
                $adList[$k] = $one ;
            }
        }
        $adjustDataTb = otable::AdJustData();
        $startTs = strtotime($date)-6*86400;
        $endTs = strtotime($date)+86400;
        $lostSpend =$lostNum= $realyLost =  $sumSpends=0;
        $sumInstall = $sumCallBack = 0;
        $lostSpendList=[];
        $uidList = [];
        foreach ($adList as $k=>$oneAdInfo) {
            foreach ($oneAdInfo as $key => $item) {
                $i++;
                $spends = $item['spends'];
                $sumSpends += $spends;
                $from = "campaign_name";
                if (in_array($k, ["facebook", "tiktok"])) {
                    $from = "creative_name";
                    echo "{$k}-广告:{$item['id']},花费:{$spends}\r\n";
                } else if (in_array($k, ["google"])) {
                    $from = "adgroup_name";
                    echo "{$k}-广告组:{$item['id']},花费:{$spends}\r\n";
                } else {
                    echo "{$k}-广告系列:{$item['id']},花费:{$spends}\r\n";
                }

                $sql = 'SELECT *  FROM ' . $adjustDataTb . '  WHERE created_at>=' . $startTs . ' and created_at<=' . $endTs . ' and ' . $from . ' LIKE "%' . $item['id'] . '%"';
                $arr = oo::commonOprDb('common')->getAll($sql, 1);
                if(empty($arr)){
                    $lostSpend+=$spends;
                    echo "安装数:0\r\n";
                }else{
                    echo "回调安装数:".count($arr)."\r\n";
                    $sumCallBack+=count($arr);

                    $Adidslist = array_column($arr,null,'adid');
                    unset($Adidslist[""]);
                    if(empty($Adidslist)){
                        $lostNum +=count($arr);
                        continue;
                    }
                    $listStr = '"'.implode('","',array_keys($Adidslist)).'"';
                    $tb2 = otable::adjustCliectData();
                    $sql = "SELECT * FROM {$tb2} WHERE adid in ({$listStr})";
                    $allList = oo::commonOprDb('common')->getAll($sql,1);
                    if(empty($allList)){
                        $realyLost +=count($arr);
                        $lostSpendList[$from][] =$item['id'];
                    }else{
                        echo "实际安装数:".count($allList)."\r\n";
                        $sumInstall+=count($allList);
                        $oneSpend = round($spends/count($allList),4);
                        foreach ($allList as $item2){
                            $one["spend"] = $oneSpend;
                            $this->setEventData($item2['uid'],"user_set",$one);
                        }
                        $uidList = array_merge($uidList,array_column($allList,'uid'));
                    }
                }
            }
        }
        echo "7日累计广告花费:{$sumSpends}\r\n";
        echo "累计花费未回调总金额:{$lostSpend}\r\n";
        echo "累计有回调未知来源:{$lostNum}\r\n";
        echo "累计有回调无UID注册:{$realyLost}\r\n";
        echo "累计回调数:{$sumCallBack}\r\n";
        echo "累计有UID注册:{$sumInstall}\r\n";
        echo "无uid注册的广告列表:".json_encode($lostSpendList)."\r\n";
        return true;
//    return $userSpendList;
    }

//==================================================
    /**
     * Notes:定时上报用户来源(每天上报前一天的数据)
     * User: wsc
     * Time: 2022/4/11 15:20
     */
    public function cronToSendUserFrom(){
        $lastDay = date('Y-m-d', strtotime("-1 day"));
//        $this->getSpendData($lastDay);
    }

}
