<?php
/**
 * 小游戏活动参与率统计相关数据
 */
class ParticipationModel extends CI_Model
{
    const PLAYCOINDOZERTYPE = 1; //推金币
    const PLAYMININGTYPE    = 2; //黄金矿工
    const PLAYTURNTABLETYPE = 3; //大转盘
    const PLAYLUCKYDRAWTYPE = 4; //夺宝活动
    const PLAYTREASURE      = 5; //宝藏活动

    private static $indexs = [
        'coindozer' => self::PLAYCOINDOZERTYPE,
        'mining'    => self::PLAYMININGTYPE,
        'turntable' => self::PLAYTURNTABLETYPE,
        'luckydraw' => self::PLAYLUCKYDRAWTYPE,
        'treasure'  => self::PLAYTREASURE,
    ];
    private static $types = [
        'steal'     => '宠物参与偷',
        'attack'    => '宠物参与打',
        'coindozer' => '推金币',
        'mining'    => '黄金矿工',
        'turntable' => '大转盘',
        'luckydraw' => '夺宝活动',
        'treasure'  => '宝藏活动',
    ];

    private static $keys = [
        'total'         => '总数',
        'canNum'        => '可玩数',
        'openNum'       => '参与数',
        'totalDuration' => '总时长',
        'avgDuration'   => '平均时长',
        'totalTimes'    => '总次数',
        'avgTimes'      => '平均次数',
        'totalTimes'    => '总次数',
        'canRate'       => '可玩参与率(%)',
        'allRate'       => '总参与率(%)',
    ];

    public static function getNameByType($type, $flag = 0) {
        $str = isset(self::$types[$type]) ? self::$types[$type] : '-';
        if(in_array($type, ['steal', 'attack', 'turntable'])){
            $str = $flag ? '付费'.$str : '免费'.$str;
        }
        return $str;
    }

    public static function getNameByKey($key = '') {
        $str = isset(self::$keys[$key]) ? self::$keys[$key] : '-';
        return $str;
    }

    /**
     * 获取类型索引值
     */
    public function getIndexByType($key) {
        $index = isset(self::$indexs[$key]) ? self::$indexs[$key] : '-';
        return $index;
    }

    /**
     * 获取参与率数据模型
     * @param string $start
     * @param string $end
     * @param string $type
     * @return array
     */
    public function getParticipation($start = '', $end = '', $type = '') {
        if(empty($start)){
            $start = date('Ymd', strtotime('-7 days 0:0:1'));
        }
        if(empty($end)){
            $end = date('Ymd', strtotime('-1 days 23:59:59'));
        }
        $tb = otable::participation();
        $sql = "SELECT * FROM {$tb} WHERE date >= {$start} AND date <= {$end}";
        if(!empty($type)){
            $sql .= " AND type = '{$type}'";
        }
        $sql .= " ORDER BY date DESC";
        $arr = oo::commonOprDb('statistics')->getAll($sql,1);

        $data = ['day' => []];
        //$keys = ['allRate', 'openNum', 'canRate', 'total', 'canNum'];
        $keys = ['openNum', 'total', 'canNum', 'totalDuration', 'totalTimes'];
        foreach($arr as $k => $v){
            $arr[$k]['canRate'] = empty($v['canNum']) ? '-' : (!empty($v['openNum']) ? sprintf('%.2f%%', $v['openNum'] * 100 / $v['canNum']) : '-');
            $arr[$k]['allRate'] = !empty($v['openNum']) ? sprintf('%.2f%%', $v['openNum'] * 100 / $v['total']) : '-';
            $arr[$k]['avgDuration'] = !empty($v['totalDuration']) ? sprintf('%.2f', $v['totalDuration'] / $v['total']) : '-';
            $arr[$k]['avgTimes'] = !empty($v['totalTimes']) ? sprintf('%.2f', $v['totalTimes'] / $v['total']) : '-';
            $name = self::getNameByType($v['type'], $v['flag']);
            $arr[$k]['name'] = $name;
            $arr[$k]['duration'] = oo::commonOprModel('common')->timeuse($arr[$k]['totalDuration']);

            if(!in_array($v['date'], $data['day'])){
                $data['day'][] = $v['date'];
            }

            foreach($keys as $key){
                if(empty($arr[$k][$key]) || $arr[$k][$key] == '-'){
                    $val = 0;
                }else{
                    $val = $arr[$k][$key];
                }
                if(in_array($key, ['allRate', 'canRate'])){
                    $val = rtrim($val, '%');
                }
                $name2 = $name.'_'.self::getNameByKey($key);

                if(empty($data[$name2])){
                    $data[$name2] = [
                        'name' => $name2,
                        'data' => [$val],
                    ];
                }else{
                    $data[$name2]['data'][] = $val;
                }
            }
        }
        return [$arr, $data];
    }

    /**
     * 总时长统计
     * @param string $day 
     * @param int $type
     * @return int
     */
    public function playTotalDuration($day, $type) {
        $key = okeys::PlayParticipateDuration($day, $type);
        $totals = oo::commonOprRedis('statistics')->hgetAll($key);
        return array_sum($totals);
    }

    /**
     * 总次数统计
     * @param string $day 
     * @param int $type
     * @return int
     */
    public function playTotalTimes($day, $type) {
        $key = okeys::PlayParticipateTimes($day, $type);
        $totals = oo::commonOprRedis('statistics')->hgetAll($key);
        return array_sum($totals);
    }
}
