<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 比赛场配置相关
*/
class Match extends MY_Controller
{
	public $postData = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);
    public $data = array('referer' =>'', 'refresh' => 'false', 'state' => 'error', 'message' => '');

    protected $limit = 10;//分页

    protected $pageConfig = array(
        'first_tag_open' => '<li>',
        'first_tag_close' => '</li>',
        'last_tag_open' => '<li>',
        'last_tag_close' => '</li>',
        'next_tag_open' => '<li>',
        'next_tag_close' => '</li>',
        'prev_tag_open' => '<li>',
        'prev_tag_close' => '</li>',
        'cur_tag_open' => "<li class='active'><a hef='#'>",
        'cur_tag_close' => "</a></li>",
        'num_tag_open' => "<li>",
        'num_tag_close' => "</li>",
    );

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

        $this->env = get_cookie($this->_wenenv);
        if($this->env == 1){
            $this->_url = $this->config->item('officialUrl');
        }else{
            $this->_url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }
	}

	/**
	*	比赛场 首页
	*/
	public function index($page = 0)
	{
		$data = array('list' => [], 'total' => '', 'pageurl' => '');
        if($this->env == 1){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }
        $this->postData['mod'] = 'match';
        $this->postData['act'] = 'index';
        $this->postData['page'] = $page;
        $this->postData['limit'] = $this->limit;
        $retData = $this->curl->req($url, $this->postData);
        $list = json_decode($retData, TRUE);
        //获取后的处理
        if( !empty($list) ){
            $data['total'] = $list['total'];

            //处理数据
            foreach ($list['list'] as &$val){
                $val['MatchType'] = $val['MatchType'] == 0 ? 'SNG' : 'MTT';
                //$val['TicketMoney'] = $val['TicketMoney'] - $val['service_fee'];
            	//$val['match_disable'] = $val['match_disable'] == 0 ? '否' : '禁赛';

            	//处理奖励
            	$reward = json_decode($val['matchreward'], 1);
            	if( is_array($reward) ){
            		$matchreward = '';
        			$i = 1;
                    foreach ($reward as $content) {
            			$matchreward .= '第'.$i.'名奖励: ';
            			foreach ($content as $type => $v) {
            				switch ($type) {
            					case 'money':
            					default:
            						$matchreward .= '筹码'.$v.',';
            						break;
            				}
            			}
            			$i++;
            		    $val['matchrewardstr'] = rtrim($matchreward, ',');
                    }
            	}
            }
            $data['list'] = $list['list'];

            //分页
            $pageConfig = $this->pageConfig;
            $pageConfig['base_url'] = base_url('#match/index');
            $pageConfig['total_rows'] = $list['total'];
            $pageConfig['per_page'] = $this->limit;
            $this->pagination->initialize($pageConfig);
            $pageurl = $this->pagination->create_links();
            $data['pageurl'] = $pageurl;
        }
        $this->load->view('match/index', $data);
	}

    /**
     * 比赛场统计
     */
    public function statistics()
    {
        //时间查询
        $dateArr = [];
        if( $stime = get_cookie('match_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('match_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['sidList'] = json_encode($this->_getSidList());
        $postData['flag'] = 2;
        $postData['typeStr'] = '201,202,1100';//比赛场相关的actid
        $postData['mod'] = 'Statistics';
        $postData['act'] = 'moneyinout';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);
        $dayList = $this->getDays($data['etime'], $data['stime']);

        $seriesStr = '';
        if(!empty($retData)) {
            foreach ($retData['actlist'] as $type => $value) {
                $actionMoneyTypeList = $retData['updatemoney'];
                $updateMoneyData = $value;
                //print_r($retData);
                $list = array();
                foreach ($dayList as $day){//循环日期
                    if( isset($updateMoneyData[$day]) ){
                        array_push($list, $updateMoneyData[$day]);
                    }else{
                        array_push($list, 0);
                    }
                }
//                $data['actionMoneyList'] = $actionMoneyTypeList;
//                $data['list'] = $list;
                $curName = $actionMoneyTypeList[$type] ?? '';
                $seriesStr .= "{name:'".$curName."',data:[".implode(',', $list).']},';
            }

        }

        //获取数据
        $postData = array_merge($dateArr, $this->postData);
        $postData['mod'] = 'Levelinfo';
        $postData['act'] = 'player';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, TRUE);
        //统计数据
        $matchStr = '';
        $matchPlayerStr = '';
        $avgNumList = [];
       if( !empty($retData) ){
            $matchInfo = $retData['matchInfo'];//比赛场
            $matchNumList = $retData['matchNumList'];
            $matchTotalNumList = $retData['matchTotalNumList'];//比赛场总的玩牌局数
            $list = array();

            foreach ($dayList as $day) {
                $day = date('Ymd', strtotime($day));
                $avgNumList[$day] = empty($matchTotalNumList[$day]) ? 0 : round($matchTotalNumList[$day] / $matchNumList[$day], 2);
            }
            //比赛场
            $matchList = $retData['matchList'] ?? [];
            foreach ($matchInfo as $level => $val) {
                $matchStr .= !isset($matchList[$level]) || empty($matchList[$level]) ? "{ name:'场次".$level."',data:[" : "{ name:'".$matchList[$level]."',data:[";
                foreach ($val as $num) {
                    $list[$level][] = $num;
                    $matchStr .= $num.',';
                }
                $matchStr .= ']},';
            }

           $matchPlayerStr .= "{ name:'比赛场总玩牌局数', data:[" .implode(',', $matchTotalNumList). "]},";
           $matchPlayerStr .= "{ name:'比赛场人均玩牌局数', data:[" .implode(',', $avgNumList). "]},";

            $matchStr = rtrim($matchStr, ',');
            $matchPlayerStr .= "{ name:'人数',data:[" .implode(',', $matchNumList). "]}";
        }
        $data['matchStr'] = $matchStr;
        $data['matchPlayerStr'] = $matchPlayerStr;
        $data['seriesStr'] = $seriesStr;
        $data['dayList'] = $dayList;
        $this->load->view('match/statistics', $data);
    }


    /**
     *	计算天数差
     */
    private function getDays($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($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;
    }

    /**
    * 编辑
    */
    public function edit( $matchlevel = 0 )
    {
        if($this->env == 1){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        $this->postData['mod'] = 'match';
        $this->postData['act'] = 'edit';
        $this->postData['matchlevel'] = $matchlevel;
        $retData = $this->curl->req($url, $this->postData);
        $info = json_decode($retData, TRUE);

        $this->load->view('match/edit', $info);
    }

    /**
    *  更新
    */
    public function actionEdit()
    {
        $data = $this->data;
        $this->postData['matchlevel'] = $this->input->post('matchlevel');
        $this->postData['MaxUserCount'] = $this->input->post('MaxUserCount');
        //$this->postData['matchreward'] = $this->input->post('matchreward');
        $this->postData['service_fee'] = $this->input->post('service_fee');
        $this->postData['TicketMoney'] = $this->input->post('TicketMoney');
        $this->postData['init_money'] = $this->input->post('init_money');
        $this->postData['zhangmang_jiange'] = $this->input->post('zhangmang_jiange');
        $this->postData['smallblinds'] = $this->input->post('smallblinds');
        $this->postData['match_disable'] = $this->input->post('match_disable');

        $matchNameArr = [];
        $matchNameArr['matchname'] = $this->input->post('matchname');
        $matchNameArr['matchname_zh'] = $this->input->post('matchname_zh');
        $matchNameArr['matchname_tw'] = $this->input->post('matchname_tw');
        $matchNameArr['matchname_en'] = $this->input->post('matchname_en');
        $this->postData['name'] = serialize($matchNameArr);

        $level = $this->input->post('level');

        if($this->postData['MaxUserCount'] > 9) {
            $data['state'] = 'error';
            $data['message'] = '编辑失败,最大人数不能超过9人';
            $data['refresh'] = true;
            die(json_encode($data));
        }
        $matchreward = [];
        $i = 1;
        foreach ($level as $value) {//后悔这种记录方式
            if (empty($value)) {
                continue;
            }
            $matchreward['r'.$i] = array('money' => $value);
            $i++;
        }
        $this->postData['matchreward'] = json_encode($matchreward);

        $this->postData['mod'] = 'match';
        $this->postData['act'] = 'actionEdit';
        if($this->env == 1){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }
        //print_r($url);
        //print_r($this->postData);
        $retData = $this->curl->req($url, $this->postData);
        //print_r($retData);
        $ret = json_decode($retData, TRUE);
        if( $ret['code'] > 0 ){
            $data['state'] = 'success';
            $data['message'] = '编辑成功';
            $data['refresh'] = true;
        }else {
            $data['message'] = $ret['msg'] ?? '';
        }
        die(json_encode($data));
    }


    /**
    *   添加比赛场
    */
    public function actionAdd()
    {
        $data = $this->data;
        $this->postData['matchlevel'] = $this->input->post('matchlevel');
//        $this->postData['matchname'] = $this->input->post('matchname');
        $this->postData['MaxUserCount'] = $this->input->post('MaxUserCount');
        //$this->postData['matchreward'] = $this->input->post('matchreward');
        $this->postData['service_fee'] = $this->input->post('service_fee');
        $this->postData['TicketMoney'] = $this->input->post('TicketMoney') + $this->input->post('service_fee');
        $this->postData['init_money'] = $this->input->post('init_money');
        $this->postData['zhangmang_jiange'] = $this->input->post('zhangmang_jiange');
        $this->postData['smallblinds'] = $this->input->post('smallblinds');
        $this->postData['match_disable'] = $this->input->post('match_disable');

        //比赛场名称
        $matchNameArr = [];
        $matchNameArr['matchname'] = $this->input->post('matchname');
        $matchNameArr['matchname_zh'] = $this->input->post('matchname_zh');
        $matchNameArr['matchname_tw'] = $this->input->post('matchname_tw');
        $matchNameArr['matchname_en'] = $this->input->post('matchname_en');

        $this->postData['name'] = serialize($matchNameArr);

        $rewardList = $this->input->post('rewardList');

        if($this->postData['MaxUserCount'] > 9) {
            $data['state'] = 'error';
            $data['message'] = '新增失败,最大人数不能超过9人';
            $data['refresh'] = true;
            die(json_encode($data));
        }

        $matchreward = [];
        $i = 1;
        foreach ($rewardList as $value) {//后悔这种记录方式
            if( $value ){
                $matchreward['r'.$i] = array('money' => $value);
                $i++;
            }
        }
        $this->postData['matchreward'] = json_encode($matchreward);

        $this->postData['mod'] = 'match';
        $this->postData['act'] = 'actionAdd';
        if($this->env == 1){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }
        //print_r($url);
        //print_r($this->postData);die;
        $retData = $this->curl->req($url, $this->postData);
        //print_r($retData);
        $ret = json_decode($retData, TRUE);
        if( $ret['code'] > 0 ){
            $data['state'] = 'success';
            $data['message'] = '添加成功';
            $data['refresh'] = true;
        }else{
            $data['message'] = $ret['msg'] ?? '';
        }
        die(json_encode($data));
    }


    /**
    *   关闭比赛场
    */
    public function closeMatch()
    {
        $data = $this->data;
        $this->postData['matchlevel'] = $this->input->post('matchlevel');
        $this->postData['match_disable'] = $this->input->post('match_disable');
        $this->postData['mod'] = 'match';
        $this->postData['act'] = 'closeMatch';
        if($this->env == 1){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }
        $retData = $this->curl->req($url, $this->postData);
        $ret = json_decode($retData, TRUE);
        die(json_encode($ret));
    }

}