<?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]);
        $data['blessings'] = ConfigModel::getExchangeBlessingWeights();
        $data['mailList'] = ConfigModel::getSystemMailList();
        $this->load->view('exchange/index', $data);
	}


    /**
     * 加载兑换码列表数据
     */
    public function listData($redeemCode="")
    {
        $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;
        if($redeemCode){
            $this->postData['redeemCode'] = $redeemCode;
        }
        $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) {
                //检查是否被兑换完毕
                $v['status'] = $v['rwdNum'] >= $v['limit'] ? '已兑换完' : '未兑换完毕';
                $v['expire'] = date('Y-m-d H:i:s', $v['expire']);
                $v['time'] = date('Y-m-d H:i:s', $v['time']);
                $v['rwd'] = $this->formatReward($v['rwd']);
                $v['index'] = $key + 1;
                $v['registerTimeRange'] = $v['register_time_min'].'-'.$v['register_time_max'];
            }
            $data['data'] = $list;
            $data['recordsTotal'] = $retData['total'];
            $data['recordsFiltered'] = $retData['total'];
        }else {
            $data = $this->withNodata();
        }

        die(json_encode($data));
    }

    /**
     * 加载兑换码兑换记录列表数据
     */
    public function logData()
    {
        $params = $this->input->get();
        $code = $params['code']??"";
        $uid = $params['uid']??"";

        $where = "Where true ";
        if (!empty($code)) {
            $where .= "And `code` = '{$code}' ";
        }
        if (!empty($uid)) {
            $where .= "And `uid` = '{$uid}' ";
        }

        $start = $this->input->post('start');
        $length = $this->input->post('length');

        $table = otable::exchangeCodeLog();
        $sql = " SELECT * FROM {$table} {$where} ORDER BY `time` DESC  LIMIT {$start}, {$length}";
        $list = oo::commonOprDb('games')->getAll($sql);

        $sql2 = " SELECT count(1) as total FROM {$table} {$where}";
        $list2 = oo::commonOprDb('games')->getOne($sql2);

        if (is_array($list) && !empty($list)) {
            foreach ($list as $key => &$v) {
                //检查是否被兑换完毕
                $v['time'] = date('Y-m-d H:i:s', $v['time']);
            }
            $data['data'] = $list;
            $data['recordsTotal'] = $list2['total'];
            $data['recordsFiltered'] = $list2['total'];
        } else {
            $data = $this->withNodata();
        }

        echo json_encode($data);
    }

    public function formatReward($rwd)
    {
        $rwd = json_decode($rwd, true);
        if (count(array_filter(array_keys($rwd), 'is_string')) > 0) {
            $props = $rwd['props'] ?? [];
            if ($rwd['spins']) {
                $props[] = ['propsId' => 15, 'num' => $rwd['spins']];
            }
            if ($rwd['coins']) {
                $props[] = ['propsId' => 14, 'num' => $rwd['coins']];
            }

            foreach ($props as &$val) {
                $val['rtype'] = 1;
            }
        } else {
            $props = $rwd;
        }


        return json_encode($props);
    }


	/**
	*	创建兑换码
	*/    /**
 *    创建兑换码
 */
    public function actionCreateCode()
    {
        $postData = $this->input->post();
        if (empty($postData['props'])) {
            return $this->response(-1, '兑换码奖励未配置');
        }

        foreach ($postData['props'] as $idx => $oneProp) {
            if ($oneProp['num'] <= 0) {
                unset($postData['props'][$idx]);
                continue;
            }

            if (intval($oneProp['propsId']) == 15 && intval($oneProp['num']) > 20000) {
                return $this->response(-1, '体力值不能大于20000');
            }
        }

        $rwd = json_encode($postData['props'], JSON_NUMERIC_CHECK);
        $code = strtoupper($postData['code']);
        $registerTimeMin = intval($postData['register_time_min']);
        $registerTimeMax = intval($postData['register_time_max']);

        // 兑换码长度在6到12
        if (strlen($code) > 12 || strlen($code) < 6) {
            return $this->response(-1, '兑换码长度在6到12字符之间');
        }

        $userType = $postData['userType'];
        $limit = $postData['limitnum'];
        $expire = strtotime($postData['datetime']);
        $remake = $postData['remake'];
        $userLimit = strtr($postData['userLimit'], ["\r\n" => "\n","，" => "\n","," => "\n",]);
        $uids = explode("\n", $userLimit);
        foreach ($uids as $uid){
            if(strlen($uid) > 8){
                return $this->response(-1, 'uid配置异常：'.$uid);
            }
        }

        $table = otable::exchangeCode();
        $sql = "Select `code` FROM {$table} Where `code` = '{$code}'";
        $ret = oo::commonOprDb('games')->getOne($sql);

        // 出现重复的兑换码号
        if (!empty($ret)) {
            return $this->response(-1, '兑换码重复, 请重新输入兑换码');
        }

        $curTime = time();

        // 删除过期的兑换码 过期7天
        $clearTime = $curTime - 7 * 86400;
        $sql = "DELETE FROM {$table} WHERE `expire` < {$clearTime}";
        oo::commonOprDb('games')->query($sql);

        // 插入新数据
        $blessingId = intval($postData['blessingId']);
        $popUpId = intval($postData['popUpId']);
        $sql = "Insert into {$table} (`code`,`rwd`,`limit`,`expire`,`usertype`,`time`,`remake`,`userLimit`,`blessingId`,`register_time_min`,`register_time_max`,`pop_up_id`) 
values ('{$code}','{$rwd}','{$limit}','{$expire}','{$userType}','{$curTime}','{$remake}','{$userLimit}','{$blessingId}','{$registerTimeMin}','{$registerTimeMax}','{$popUpId}')";
        $ret = oo::commonOprDb('games')->query($sql);
        if (!$ret) {
            return $this->response(-1, 'SQL语句执行出错');
        }

        return $this->response(0, '操作成功');
    }

    //兑换码搜索
    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));
    }



    public function blessingWeights(){
        $config = ConfigModel::getExchangeBlessingWeights();
        $headers = [
            'iid' => 'ID',
            'title' => '标题',
        ];
        $data = [
            'title' => '兑换码祝福语模板配置',
            'headers' => $headers,
            'config' => $config,
            'js' => '/config/blessingWeights.js?v='.time(),
            'topOperators' => [
                '<button type="button" class="btn btn-outline btn-success" id="addBlessingTemplate"  >添加祝福语模板</button>'
            ],
            'operators' => [
                '<button type="button" class="btn btn-outline btn-info edit"  >编辑标题</button>',
                '<button type="button" class="btn btn-outline btn-primary blessingWeightDetail"  >编辑权重</button>',
            ],
        ];
        $this->load->view('common/commonTable', $data);

    }
    public function saveBlessingTemplateDialog(){
        $postData = $this->input->post();
        $postData['iid'] = intval($postData['iid']);
        $tb = otable::exchangeBlessingWeight();
        $config = ConfigModel::getExchangeBlessingWeights();
        foreach ($config as $item){
            if( $postData['title'] == $item['title'] && $postData['iid'] != $item['iid']){
                $this->response(__LINE__, "标题 {$postData['title']} 重复");
            }
        }
        if(empty($postData['iid'])){
            $updateData = [
                'title' => $postData['title'],
                'config' => json_encode([])
            ];
            $res = oo::commonOprDb('games')->query(funs::db_insertSQL($tb, $updateData));
        }else{
            $updateData = [
                'title' => $postData['title'],
                'config' => json_encode([])
            ];
            $res = oo::commonOprDb('games')->query(funs::db_updateSQL($tb, $updateData, '  iid='.$postData['iid']));
        }
        if(!$res)$this->response(__LINE__, '保存失败');
        $this->response(0, '保存成功');
    }
    public function blessingWeightDetail($id){
        $config = ConfigModel::getExchangeBlessingWeights([$id])[0] ?? [];
        $langs = oo::cfg('lang')['en_zh'] ?? [];
        ksort($langs);
        $contents = json_decode($config['config'], true);
        foreach ($contents as $k => $v){
            foreach ($langs as $lang => $langText){
                $contents[$k]["{$lang}_title"] = $v['content'][$lang]['title'];
                $contents[$k]["{$lang}_content"] = $v['content'][$lang]['content'];
            }
        }

        $headers = ['weight' => '权重'];
        foreach ($langs as $lang => $langText){
            $headers["{$lang}_title"] = "{$langText}标题";
            $headers["{$lang}_content"] = "{$langText}内容";
        }
        $data = [
            'title' => '兑换码祝福语权重配置',
            'headers' => $headers,
            'config' => $contents,
            'js' => '',
            'topOperators' => [
                '<input type="file" style="display: none" id="import-file" onchange="commonImport(this)" data-href="/import/blessingWeights/'.$id.'">',
                '<button type="button" class="btn btn-outline btn-success" onclick="$(\'#import-file\').click()"  >导入</button>',
                '<a type="button" class="btn btn-outline btn-primary"  href="/export/blessingWeights/'.$id.'" target="_blank">导出</a>',
            ],
            'operators' => [],
        ];
        $this->load->view('common/commonTable', $data);

    }

}