<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/28 0028
 * Time: 18:09
 */
class Lose extends MY_Controller {
    public $postdata = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('cookie');
        $this->load->library('curl');

        //请求地址
        $this->env = get_cookie($this->_wenenv);
        $this->_url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
    }

    /**
     * 获取等级
     * @return array
     */
    public function getLevel()
    {
        $data = [];
        for($i=1; $i <= 30; $i ++) {
            $data[$i] = '等级'.$i;
        }
        return $data;
    }

    /**
     * 流失统计
     */
    public function index($type=1)
    {
        $bougth = ['pay'=>'付费', 'notpay'=>'非付费'];
        $deviceAccount = ['AF'=>'安卓FB','AV'=>'安卓游客','IF'=>'苹果FB', 'IV'=>'苹果游客'];
//        $money = [0 => '0-1000',1001 => '1001-5000',5001=>'5001-10000',10001=>'10001-50000', 50001=>'50001-100K',100000=>'100K以上'];
        $money = [0 => '0-1000',1001 => '1001-40K',40001=>'40K-150K',150001=>'150K-600K',600001=>'600K-2M',2000001=>'2M-10M',10000001=>'10M-100M',100000001=>'100M以上'];

        $bougthKey = array_keys($bougth);
        $deviceAccountKey = array_keys($deviceAccount);
        $moneyKey = array_keys($money);
        $data = array('stime' => '', 'etime' => '');

        //时间查询
        $dateArr = array();

        if( $stime = get_cookie('loseindex_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $dateArr['stime'] = strtotime('- 7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if( $etime = get_cookie('loseindex_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.'23:59:59');
        }else{
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postdata);
        $postData['mod'] = 'Lose';
        if($type == 2) {//7日流失
            $postData['act'] = 'sevenDaysLose';
            $data['keyName'] = '7日';
        }else {//昨日流失
            $postData['act'] = 'index';
            $data['keyName'] = '次日';
        }
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);

        if(empty($retData)) {
            $this->load->view('lose/index', $data);
        }

        //获取等级
        $levelKeyList = $this->getLevel();
        $keyLevel = array_keys($levelKeyList);

        $dayList = $retData['dayList'];
        $loseLevelValue = $loseTotal = $loseBoughtValue = $loseDeviceAccountValue = $loseMoneyValue = [];
        $loseLevelPercent = $loseBoughtPercent = $loseDevAccPercent = $loseMoneyPercent = [];
        //获取报表的数据
        foreach ($dayList as $day) {
            $day = date('Ymd', strtotime($day));
            $loseList = $retData['loseList'][$day];
            $loseList = empty($loseList) ? [] : unserialize($loseList);
            if(empty($loseList)) {
                array_push($loseTotal, 0);
                $this->getLoseValue($keyLevel, [], $loseLevelValue, $loseLevelPercent, 0);
                $this->getLoseValue($bougthKey, [], $loseBoughtValue, $loseBoughtPercent, 0);//是否付费
                $this->getLoseValue($deviceAccountKey, [], $loseDeviceAccountValue, $loseDevAccPercent, 0);//账号是游客还是FB
                $this->getLoseValue($moneyKey, [], $loseMoneyValue, $loseMoneyPercent, 0);//筹码
            }else {
                $total = $loseList['total'] ?? 0;
                $payNum = $loseList['payNum'] ?? 0;
                $notpayNum = $loseList['dau'] - $payNum;
                $af = $loseList['login_af'] ?? 0;
                $av = $loseList['login_av'] ?? 0;
                $if = $loseList['login_if'] ?? 0;
                $iv = $loseList['login_iv'] ?? 0;

                array_push($loseTotal, $total);//流失总数
                $this->getLoseValue($keyLevel, $loseList['level'] ?? [], $loseLevelValue, $loseLevelPercent, $total);//玩家等级
                $this->getLoseValue($bougthKey, $loseList['bought'] ?? [], $loseBoughtValue, $loseBoughtPercent, $total, ['pay'=>$payNum, 'notpay' => $notpayNum]);//是否付费
                $this->getLoseValue($deviceAccountKey, $loseList['deviceAccount'] ?? [], $loseDeviceAccountValue, $loseDevAccPercent, $total, ['AF'=>$af, 'AV' => $av, 'IF' => $if, 'IV' => $iv]);//账号是游客还是FB
                $this->getLoseValue($moneyKey, $loseList['money'] ?? [], $loseMoneyValue, $loseMoneyPercent, $total);//筹码
            }
        }
        $totalStr = '';
        $levelStr = '';
        $bougthStr = '';
        $deviceAccountStr = '';
        $moneyStr = '';
        $levelPercentStr = '';
        $bougthPercentStr = '';
        $devAccPercentStr = '';
        $moneyPercentStr = '';
        $totalStr =  "{name: '总人数',data: [".implode(",", $loseTotal)."]}";
        //等级
        foreach ($levelKeyList as $k => $v) {
            $k > 6 ?  $levelStr .= "{name:'".$v."' ,visible:false ,data: [".implode(',',$loseLevelValue[$k]).']},' :  $levelStr .= "{name:'".$v."',data: [".implode(',',$loseLevelValue[$k]).']},';
            $levelPercentStr .=  "{ name: '".$v."流失率',visible:false , yAxis: 1,data: [".implode(',', $loseLevelPercent[$k])."],tooltip: {valueSuffix: '%'}},";
        }

        //是否付费
        foreach ($bougth as $kb => $_vb) {
            $bougthStr .=  ",{name:'".$_vb."',data: [".implode(',',$loseBoughtValue[$kb]).']}';
            $bougthPercentStr .=  ",{ name: '".$_vb."流失率', visible:false , yAxis: 1,data: [".implode(',', $loseBoughtPercent[$kb])."],tooltip: {valueSuffix: '%'}}";
        }
        //账号
        foreach ($deviceAccount as $ka => $_va) {
            $deviceAccountStr .=  ",{name:'".$_va."',data: [".implode(',',$loseDeviceAccountValue[$ka]).']}';
            $devAccPercentStr .=  ",{ name: '".$_va."流失率', visible:false, yAxis: 1,data: [".implode(',', $loseDevAccPercent[$ka])."],tooltip: {valueSuffix: '%'}}";
        }

        //筹码
        foreach ($money as $km => $_vm) {
            $moneyStr .=  "{name:'筹码【".$_vm."】',data: [".implode(',',$loseMoneyValue[$km]).']},';
            $moneyPercentStr .=  "{ name: '筹码【".$_vm."】流失率', visible:false, yAxis: 1,data: [".implode(',', $loseMoneyPercent[$km])."],tooltip: {valueSuffix: '%'}},";
        }
        $levelStr = $levelStr.$levelPercentStr;
        $levelStr = rtrim($levelStr, ',');
        $moneyStr = $moneyStr.$moneyPercentStr;
        $moneyStr = rtrim($moneyStr, ',');


        $data['total'] = $loseTotal;
        $data['levelStr'] = $levelStr;
        $data['displayStr'] = $totalStr.$bougthStr.$deviceAccountStr.$bougthPercentStr.$devAccPercentStr;
        $data['moneyStr'] = $moneyStr;
        $data['dayList'] = $dayList;
        $data['type'] = $type;

        $this->load->view('lose/index', $data);
    }

    /**
     * 获取等级数据
     * @param $levelKey
     * @param $loseLevel
     * @param $loseLevelValue
     * @return mixed
     */
    private function getLoseValue($levelKey, $loseLevel, &$loseLevelValue, &$loseLevelPercent = [], $total = 0, $data = array())
    {
        foreach ($levelKey as $kl) {
            $loseLevelValue[$kl] = isset($loseLevelValue[$kl]) ? $loseLevelValue[$kl] : [];
            $valueTmp = $loseLevel[$kl] ?? 0;
            array_push($loseLevelValue[$kl], $valueTmp);
            $loseLevelPercent[$kl] = isset($loseLevelPercent[$kl]) ? $loseLevelPercent[$kl] : [];
            if(!empty($data)) {
                empty($data[$kl]) ? array_push($loseLevelPercent[$kl], 0) : array_push($loseLevelPercent[$kl],  round($valueTmp * 100 / $data[$kl], 2));//流失率
            }else {
                empty($total) ? array_push($loseLevelPercent[$kl], 0) : array_push($loseLevelPercent[$kl],  round($valueTmp * 100 / $total, 2));//流失率
            }
        }
        return $loseLevelValue;
    }


    /**
     *	计算天数差
     */
    private function getDays($day1, $day2)
    {
        $second1 = $day1;
        $second2 = $day2;

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        $days = ($second1 - $second2) / 86400;
        $dayList = array();
        for ($i=0; $i <= $days ; $i++) {
            $dayList[] = date('Y-m-d', $second2 + 86400*$i);
        }
        return $dayList;
    }

}