<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Activitysta extends MY_Controller
{
	public function __construct()
    {
        parent::__construct();
        $config = array(
            'savePath' => 'Excel/uploads',             //存储文件夹
            'maxSize'  => 1024*5,                   //允许的文件最大尺寸，单位KB
            'allowFiles' => array('.xls','.xlsx')  //允许的文件格式
        );
        $this->load->library('uploader', $config);
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        $this->load->library('curl');
    }
    
    public function base($objPHPExcel,$outPutFileName){
        // 设置第一个sheet为工作的sheet
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: applicationnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$outPutFileName.'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }
    
	public function index($id){
		$tb = otable::activityConf();
		$sql = "SELECT * FROM {$tb} WHERE id = {$id}";
		$ret = oo::commonOprDb('slavedb')->getOne($sql,1);
		
		$data['config'] = $ret;
		
		$tb = otable::activityStageRewardConf();
        $sql = "SELECT * FROM {$tb} WHERE aid={$id}";
        $retStage = oo::commonOprDb('slavedb')->getOne($sql,1);
        if($retStage['type'] == 'collect'){
        	$retStage['reward'] = json_decode($retStage['extra_reward'],1);
        }else{
        	$retStage['reward'] = json_decode($retStage['reward'],1);
        }
        
        $stage = $stageNum = [];
		foreach($retStage['reward'] as $key => $row){
			if($retStage['type'] == 'collect'){
				foreach($row['list'] as $k => $val){
					$stage[$key][] = $k;
					$stageNum[$key][] = $val['stepnum'];
				}
			}else{
				$stage[1][] = $key;
				$stageNum[1][] = $row['stepnum'];
			}
		}
		$data['stage'] = $stage;
		
		foreach($stageNum as $key => $row){
			foreach($row as $k => $val){
				$stageNum[$key][$k] = $val + (empty($stageNum[$key][$k-1])?0:$stageNum[$key][$k-1]);
			}
		}

		$tb = otable::actStageLog($id);
		//每日统计
		$sql = "SELECT stage,COUNT(*) AS count,times,rid FROM {$tb} WHERE type = 1 GROUP BY times,stage,rid";
		$ret = oo::commonOprDb('log')->getAll($sql,1);
		
		$date = [];
		foreach($ret as $key => $row){
			if(!in_array($row['times'],$date)){
				$date[] = $row['times'];
			}
		}
		$data['date'] = $date;
		
		
		//结束统计
		$sql = "SELECT stage,COUNT(*) AS count,times,rid FROM {$tb} WHERE type = 2 GROUP BY times,stage,rid";
		$retEnd = oo::commonOprDb('log')->getAll($sql,1);
		
		$date = [];
		foreach($retEnd as $key => $row){
			if(!in_array($row['times'],$date)){
				$date[] = $row['times'];
			}
		}
		$data['dateEnd'] = $date;
		
		$out = $outEnd = [];

		foreach($retEnd as $key => $row){
			$outEnd[$row['times']][$row['rid']][$row['stage']] = $row['count'];
		}

		foreach($ret as $key => $row){
			$out[$row['times']][$row['rid']][$row['stage']] = $row['count'];
		}

		$data['data'] = $out;
		$data['dataEnd'] = $outEnd;
		
		//数值统计
		$Interval = [1, 5, 10, 40, 80, 110, 180, 260, 360, 500, 1000, 2000, 3000, 5000, 8000, 10000, 15000, 20000];
		$data['Interval'] = $Interval;
		$tb = otable::actStageLog($id);
		$progressData = $progressDataEnd = [];
		
		foreach($stage as $rid => $val){
			foreach($data['date'] as $day){
				//每日统计
				$sql = "SELECT stage,rate FROM {$tb} WHERE type = 1 AND times = {$day} AND rid = {$rid}";
				$ret = oo::commonOprDb('log')->getAll($sql,1);
				foreach($ret as $key => $row){
					foreach($Interval as $stageTemp){
						if($stageNum[$rid][$row['stage']] + $row['rate'] > $stageTemp){
							$progressData[$day][$rid][$stageTemp]++;
						}
					}
				}
				
			}
		}
		
		foreach($stage as $rid => $val){
			foreach($data['dateEnd'] as $day){
				//结束统计
				$sql = "SELECT stage,rate FROM {$tb} WHERE type = 2 AND times = {$day} AND rid = {$rid}";
				$ret = oo::commonOprDb('log')->getAll($sql,1);
				foreach($ret as $key => $row){
					foreach($Interval as $stageTemp){
						if($stageNum[$rid][$row['stage']] + $row['rate'] > $stageTemp){
							$progressDataEnd[$day][$rid][$stageTemp]++;
						}
					}
				}
			}
		}
		$data['progressData'] = $progressData;
		$data['progressDataEnd'] = $progressDataEnd;
		
		$this->load->view("activitysta/index", $data);
	}
	
	public function rank($id){
		if( $uid = get_cookie('uid') ){
			$tb = otable::rankActLog($id,1);
			$sql = "SELECT * FROM {$tb} WHERE aid = {$id} AND uid = {$uid}";
			$ret = oo::commonOprDb('slavedb')->getOne($sql,1);
			
			$data['rank'] = $ret;
			
			$tb = otable::rankActLog($id,2);
			$sql = "SELECT * FROM {$tb} WHERE aid = {$id} AND uid = {$uid}";
			$ret = oo::commonOprDb('slavedb')->getOne($sql,1);
			
			$data['receive'] = $ret;
		}
		$data['uid'] = $uid;
		$data['id'] = $id;
		$this->load->view("activitysta/rank", $data);
	}

    /**
     * 锦标赛 + 超级收集活动 统计
     * @return string
     * Created by: Hss
     * Created on: 2021/3/5 11:35
     */
	public function speedChart($aid = 0,$type = ''){
        $aid = empty($aid) ? get_cookie('aid') : $aid;
        $type = empty($type) ? get_cookie('actType') : $type;
        $data = oo::commonOprModel('statistics')->rankCollectSta($aid);
        $data['aid'] = $aid;
        $data['type'] = $type;
        $this->load->view("activitysta/speedChart", $data);
    }

    /**
     * 锦标赛 + 超级收集活动 统计
     * @return string
     * Created by: Hss
     * Created on: 2021/3/5 11:35
     */
    public function speedTable($aid = 0,$type = ''){
        $aid = empty($aid) ? get_cookie('aid') : $aid;
        $type = empty($type) ? get_cookie('actType') : $type;
        $data = oo::commonOprModel('statistics')->rankCollectSta($aid);
        $data['aid'] = $aid;
        $data['type'] = $type;
        $this->load->view("activitysta/speedTable", $data);
    }

    /**
     * 排行榜 统计
     * @return string
     * Created by: Hss
     * Created on: 2021/3/8 11:54
     */
    public function rankTable($aid = 0,$type = ''){
        $aid = empty($aid) ? get_cookie('aid') : $aid;
        $data = oo::commonOprModel('statistics')->rankCollectSta($aid);
        $data['aid'] = $aid;
        $data['type'] = $type;
        $this->load->view("activitysta/rankTable", $data);
    }

    /**
     * 排行榜 统计
     * @return string
     * Created by: Hss
     * Created on: 2021/3/8 11:54
     */
    public function rankChart($aid = 0,$type = ''){
        $aid = empty($aid) ? get_cookie('aid') : $aid;
        $data = oo::commonOprModel('statistics')->rankCollectSta($aid);
        $data['aid'] = $aid;
        $data['type'] = $type;
        $this->load->view("activitysta/rankChart", $data);
    }
	
	//导出UID
	public function exportUid($id,$date,$type){
		$tb = otable::actStageLog($id);
		$sql = "SELECT * FROM {$tb} WHERE type = {$type} AND times = {$date}";
		$list = oo::commonOprDb('log')->getAll($sql, MYSQLI_ASSOC);
		
		$headerTable = ['UID','进度','数值'];
		$bodyTable = $list;
        $objPHPExcel = new PHPExcel();
        //处理表头
        $char = 'A';
        foreach ($headerTable as $k => $v) {
            $objPHPExcel->getActiveSheet()->setCellValue($char.'1', $v);
            $char = chr(ord($char) + 1);
        }
        //处理数据
        $i = 2;
        foreach ($bodyTable as $kb => $vb) {
            $objPHPExcel->getActiveSheet()->setCellValue("A".$i, $vb['uid']);
            $objPHPExcel->getActiveSheet()->setCellValue("B".$i, $vb['stage']);
            $objPHPExcel->getActiveSheet()->setCellValue("C".$i, $vb['rate']);
            $i++;
        }

        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $outPutFileName = '活动'.$id."_".$date.'_记录_'.date('Y-m-d');
        $this->base($objPHPExcel,$outPutFileName);
	}

    public function fundSta($id = 0){
        $tb  = otable::activityConf();
        $aret= oo::commonOprDb('slavedb')->getAll("SELECT id,name,start_time FROM {$tb} WHERE `type`='fund'",MYSQLI_ASSOC);
        $activityId = array_column($aret,"name","id");
        $data['activityId'] = $activityId;
        $data['curId']      = $id;
        $showData  = [];
        if(!empty($id)){
            $orderInfo = [];
            for($i=0;$i<100;$i++){
                $tb = otable::payment($i);
                $ret= oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE status=2 AND gid IN (1812,1813) AND buff='{$id}'",MYSQLI_ASSOC);
                foreach ($ret as $row){
                    $orderInfo[date("Ymd",$row['pay_time'])][$row['gid']] += 1;
                }
            }
            $startTime = array_column($aret,"start_time","id")[$id];
            $endTime   = $startTime + 14*24*60*60;
            while ($startTime <= $endTime) {
                $dateList[] = date('Ymd', $startTime);
                $startTime = $startTime + 86400;
            }
            $tb = otable::report();
            foreach ($dateList as $row){
                $dau = oo::commonOprDb('slavedb')->getOne("SELECT dau FROM {$tb} WHERE `date`={$row}",MYSQLI_ASSOC);
                if($dau['dau'] != 0){
                    $pro[1812] = round($orderInfo[$row][1812]/$dau['dau'],2);
                    $pro[1813] = round($orderInfo[$row][1813]/$dau['dau'],2);
                }else{
                    $pro[1812] = 0;
                    $pro[1813] = 0;
                }
                $showData[$row] = [
                    "orderInfo1812"=>$orderInfo[$row][1812]??0,
                    "orderInfo1813"=>$orderInfo[$row][1813]??0,
                    "pro1812"      => $pro[1812],
                    "pro1813"      => $pro[1813],
                ];
            }
        }
        $data['showData'] = $showData;
        $this->load->view('statistics/activity/fundSta',$data);
    }
}