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

/**
* 兑换码相关
*/
class Exchange extends MY_Controller
{
	
	public $postData = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);

	public function __construct()
	{
		parent::__construct();
		$this->load->helper('cookie');
		$this->load->library('curl');
		$this->env = get_cookie($this->_wenenv);
	}

	/**
	*	兑换码列表页
	*/
	public function index()
	{
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $url  = $this->config->item('officialUrl');
        $config = $this->curl->req($url, $posts);
        $data = json_decode($config,true);
        unset($data['props'][14], $data['props'][15]);
        $this->load->view('exchange/index', $data);
	}

    public function indexNew()
    {

        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $url  = $this->config->item('officialUrl');
        $config = $this->curl->req($url, $posts);
        $data = json_decode($config,true);

        $data['chestSkin']  = array_column(oo::commonOprModel('config')->chestSkin(),'name','id');
        $data['easterEggSkin'] = array_column(oo::commonOprModel('config')->getActivityActionList('easter_egg'),'name','id');
        $data['treasureSkin']  = array_column(oo::commonOprModel('config')->getActivityActionList('treasure'),'name','id');//宝藏活动
        $data['crazyCardGroup']  = array_column(oo::commonOprModel('config')->getActivityActionList('crazy_card_group'),'name','id');
        $this->load->view('exchange/indexNew',$data);
    }

    /**
     * 加载兑换码列表数据
     */
    public function listData()
    {
        $start = $this->input->post('start');
        $length = $this->input->post('length');
        $uid = $this->input->post('uid');

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

        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $config = $this->curl->req($url, $posts);
        $props = json_decode($config,true);
        $props = $props['props'];

        $this->postData['mod'] = 'Exchange';
        $this->postData['act'] = 'getList';
        $this->postData['start'] = $start;
        $this->postData['length'] = $length;
        $this->postData['uid'] = $uid;
        $retData = $this->curl->req($url, $this->postData);

        $retData= json_decode($retData, TRUE);
        $list = $retData['list'];
        if (is_array($list) && !empty($list)) {
            foreach ($list as $key => &$v) {
                $reward = '';
                $rewardInof = json_decode($v['rwd'], true);
                if(!empty($rewardInof) && is_array($rewardInof)) {
                    foreach ($rewardInof as $type => $num) {//遍历奖励
                        switch ($type) {
                            case 'coins':
                                $reward .= " 金币:{$num} ";
                                break;
                            case 'spins':
                                $reward .= " 体力:{$num} ";
                                break;
                            case 'props':
                                $reward .= " 道具:";
                                foreach ($num as $row){
                                    $reward .= $props[$row['propsId']]['msg']."X".$row['num'].",";
                                }
                                $reward = trim($reward,',');
                                break;
                        }
                    }
                    $v['reward'] = $reward;
                }
                //检查是否被兑换完毕
                $v['status'] = '未兑换完毕';
                if( $v['rwdNum'] >= $v['limit'] ){
                    $v['status'] = '已兑换完';
                }
                $v['expire'] = date('Y-m-d H:i:s', $v['expire']);
                $v['time'] = date('Y-m-d H:i:s', $v['time']);
                $v['index'] = $key + 1;
            }
            $data['data'] = $list;
            $data['recordsTotal'] = $retData['total'];
            $data['recordsFiltered'] = $retData['total'];
        }else {
            $data = $this->withNodata();
        }

        die(json_encode($data));
    }


	/**
	*	创建兑换码
	*/
	public function actionCreateCode()
	{
		if( $this->env == 1 ){
			$url = $this->config->item('officialUrl');
		}else{
			$url = $this->config->item('localUrl');
			$this->postData['demo'] = 1;
		}
		$reward = [
		    'spins' => intval($this->input->post('spins')),
		    'coins' => intval($this->input->post('coins')),
        ];
        if($reward['spins'] > 20000){
        	$data['state'] = '';
			$data['message'] = '生成失败';
			die(json_encode($data));
        }
        
        $props = $this->input->post('props');
        foreach ($props['id'] as $key=>$row){
            if($props['num'][$key] <= 0){
                continue;
            }else{
                $reward['props'][] = [
                    'propsId' => $row,
                    'num'     => $props['num'][$key],
                ];
            }
        }
		
        $this->postData['reward'] = json_encode($reward,JSON_NUMERIC_CHECK);
        $this->postData['userType'] = $this->input->post('userType'); //领取的用户类型
		$this->postData['limit']    = $this->input->post('limitnum'); //兑换数量
		$this->postData['day']      = $this->input->post('day')." ".$this->input->post('time');      //过期时间
		$this->postData['remake']   = $this->input->post('remake');   //过期时间
		$this->postData['userLimit']= $this->input->post('userLimit');//限定用户
		$this->postData['mod'] = 'Exchange';
		$this->postData['act'] = 'createCode';
		$retData = $this->curl->req($url, $this->postData);
		
		$retData = json_decode($retData, TRUE);
		
		$data = array('referer' => '',  "refresh" => true);
		if( $retData['code'] == 1 ){
			$data['state'] = 'success';
			$data['message'] = '生成成功';
		}else{
			$data['state'] = '';
			$data['message'] = '生成失败';
		}
		die(json_encode($data));
	}

    //兑换码搜索
    public function queryRedeemCode()
    {
        $params = $this->input->get();
        $redeemCode = $params['redeemCode'];

        $table = otable::exchangeCode();
        $sql = " SELECT * FROM {$table} where code={$redeemCode}";
        $list = oo::commonOprDb('slavedb')->getAll($sql);

        if (is_array($list) && !empty($list)) {
            if( $this->env == 1 ){
                $url = $this->config->item('officialUrl');
            }else{
                $url = $this->config->item('localUrl');
                $this->postData['demo'] = 1;
            }

            $posts = $this->postData;
            $posts['mod'] = 'Config';
            $posts['act'] = 'getPropsConfig';
            $config = $this->curl->req($url, $posts);
            $props = json_decode($config,true);
            $props = $props['props'];

            foreach ($list as $key => &$v) {
                $reward = '';
                $rewardInof = json_decode($v['rwd'], true);
                if(!empty($rewardInof) && is_array($rewardInof)) {
                    foreach ($rewardInof as $type => $num) {//遍历奖励
                        switch ($type) {
                            case 'coins':
                                $reward .= " 金币:{$num} ";
                                break;
                            case 'spins':
                                $reward .= " 体力:{$num} ";
                                break;
                            case 'props':
                                $reward .= " 道具:";
                                foreach ($num as $row){
                                    $reward .= $props[$row['propsId']]['msg']."X".$row['num'].",";
                                }
                                $reward = trim($reward,',');
                                break;
                        }
                    }
                    $v['reward'] = $reward;
                }
                //检查是否被兑换完毕
                $v['status'] = '未兑换完毕';
                if( $v['rwdNum'] >= $v['limit'] ){
                    $v['status'] = '已兑换完';
                }
                $v['expire'] = date('Y-m-d H:i:s', $v['expire']);
                $v['time'] = date('Y-m-d H:i:s', $v['time']);
                $v['index'] = $key + 1;
            }
            $data['data'] = $list;
            $data['recordsTotal'] = 1;
            $data['recordsFiltered'] = 1;
        }else {
            $data = $this->withNodata();
        }

        die(json_encode($data));
    }
}