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

/**
 * 公会配置
 */
class Returns extends MY_Controller{
    public $data = array('referer' =>'', 'refresh' => 'false', 'state' => 'error', 'message' => '');
    public $postdata = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);

    protected $page = 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();
        $config = array(
            'savePath' => 'Excel/uploads',             //存储文件夹
            'maxSize'  => 1024*50,                   //允许的文件最大尺寸，单位KB
            'allowFiles' => array('.xls','.xlsx','.json', '.png','.jpg')  //允许的文件格式
        );
        $this->load->library('uploader', $config);
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');

        $this->load->helper('url');
        $this->load->helper('cookie');
        $this->load->library('curl');
        $this->load->library('pagination');

        $this->env = get_cookie($this->_wenenv);
    }

    /**
     *	回归配置 - 回归条件
     */
    public function index()
    {
        $table = otable::commonConfig();
        $basicKey = okeys::returnsBasicKey();
        $typeKey = $basicKey;
        $config = oo::commonOprRedis('games')->get($basicKey);
        if(empty($config)){
            $config = oo::commonOprDb('slavedb')->getOne("select * from {$table} where type='{$typeKey}' limit 1");
            $config = $config['conf'];
        }
        $config = empty($config) ? [] : (@json_decode($config, true) ?? []);
        $paymentStatusMap = [
            0 => '全部用户',
            1 => '未付费',
            2 => '已付费'
        ];
        $columns = [
            'lostTimes' => $this->inputField('lostTimes','流失时长(小时)', 'text', $config['lostTimes'] ?? ''),
            'minLv' => $this->inputField('minLv','流失等级下限', 'text', $config['minLv'] ?? ''),
            'maxLv' => $this->inputField('maxLv','流失等级上限', 'text', $config['maxLv'] ?? ''),
            'minPay' => $this->inputField('minPay','付费金额下限', 'text', $config['minPay'] ?? ''),
            'maxPay' => $this->inputField('maxPay','付费金额上限', 'text', $config['maxPay'] ?? ''),
//            'payStatus' => $this->inputField('payStatus','是否付费', 'selector', $config['payStatus'] ?? '', $paymentStatusMap),
        ];
        $data = [
            'config' => $config,
            'columns' => $columns,
        ];
        $this->load->view('returns/index', $data);
    }

    public function saveBasicConfig(){
        $input = $this->input->post();
        $table = otable::commonConfig();
        $basicKey = okeys::returnsBasicKey();
        $basicConfig = json_encode($input, 32);
        if(empty($input['id'])){
            $res = oo::commonOprDb('games')->query("insert into {$table} (`type`, `name`, `conf`)  values ('{$basicKey}', '回归条件配置', '{$basicConfig}')");
            $input['id'] = oo::commonOprDb('games')->insertID();
            $basicConfig = json_encode($input, 32);
        }
        $res = oo::commonOprDb('games')->query("update {$table} set  `conf`='{$basicConfig}' where id={$input['id']} ");
        if(!$res)$this->response(__LINE__ * -1, '保存失败');
        oo::commonOprRedis('games')->set($basicKey, $basicConfig);
        $this->response(1, '保存成功');
    }


    public function rewards(){
        $data = [];
        $tbl = otable::returnsRewards();
        $commonTable = otable::commonConfig();
        $returnsRewardsTbl = otable::returnsRewards();
        $openTimesKey = okeys::returnsOpenTimeKey();
        $config = oo::commonOprRedis('games')->get($openTimesKey);
        if(empty($config)){
            $config = oo::commonOprDb('slavedb')->getOne("select * from {$commonTable} where type='{$openTimesKey}' limit 1");
            $config = $config['conf'];
        }
        $config = empty($config) ? [] : (@json_decode($config, true) ?? []);
        $data['info'] = $config;

        $rewards = oo::commonOprDb('slavedb')->getAll("select * from {$returnsRewardsTbl}");
        foreach ($rewards as &$reward){
            $reward['prizeHtml'] = $this->prizesShowHtml(json_decode($reward['rewards'], true) ?? []);
        }
        $data['rewards'] = $rewards;
        $this->load->view('returns/rewards', $data);
    }
    public function saveOpenTimesConf(){
        $input = $this->input->post();
        $table = otable::commonConfig();
        $openTimesKey = okeys::returnsOpenTimeKey();
        list($startDate, $endDate) = explode(' - ', $input['time_range']);
        $timeRange = [
            'start' => strtotime($startDate),
            'end' => strtotime($endDate),
            'id' => intval($input['id']),
        ];

        $basicConfig = json_encode($timeRange, 32);
        if(empty($timeRange['id'])){
            $res = oo::commonOprDb('games')->query("insert into {$table} (`type`, `name`, `conf`)  values ('{$openTimesKey}', '回归奖励开放时间配置', '{$basicConfig}')");
            $timeRange['id'] = oo::commonOprDb('games')->insertID();
            $basicConfig = json_encode($timeRange, 32);
        }
        $res = oo::commonOprDb('games')->query("update {$table} set  `conf`='{$basicConfig}' where id={$timeRange['id']} ");
        if(!$res)$this->response(__LINE__ * -1, '保存失败');
        oo::commonOprRedis('games')->set($openTimesKey, $basicConfig);
        $this->response(1, '保存成功');
    }

    public function importRewards(){
        $dataArray = $this->getExcelSheetsArray()[0] ?? [];
        if(empty($dataArray))$this->response(-1, '导入数据为空');
        $rewards = [];
        $returnsRewardsTbl = otable::returnsRewards();
        $insertSql = "insert into {$returnsRewardsTbl} (`minLv`, `maxLv`, `rewards`) values ";
        foreach ($dataArray as $k => $item){
            if(empty($k))continue;
            $lineNum = $k + 1;
            $minLv = intval($item[0]);
            $maxLv = intval($item[1]);

            $prizes = [];
            $count = count($item);
            for ($i = 2; $i < $count; $i+=3){
                $rewardName = $item[$i] ?? '';
                $isFixNum = $item[$i+1] ?? '';
                $rewardNum = $item[$i+2] ?? '';
                if(empty($rewardName))continue;
                list($type, $skin) = $this->parseRewardTypeAndSkinId($rewardName, $lineNum);
                if(!in_array($rewardName, $this->multiNumTypeReward))$isFixNum = '是';   #非金币奖励，全部固定值奖励
                $isFixNum = ($isFixNum == '是') ? 1 : 2;#固定值奖励 1 按等级取值 2

                $currentId = count($prizes)+1;
                $prizes[] = [
                    'id' => $currentId,
                    "num" => $rewardNum,
                    "type" => $type,
                    "propsId" => $type,
                    "rtype" => $isFixNum,
                    "skin" => intval($skin)
                ];
            }
            if(empty($prizes))$this->response(-1, "第 {$lineNum} 行奖励配置为空");
            $prizesJson = json_encode($prizes, 32);
            $insertSql .= " ({$minLv},{$maxLv}, '{$prizesJson}'),";
        }
        $insertSql = trim($insertSql, ',');
        oo::commonOprDb('games')->query("delete from {$returnsRewardsTbl}");
        oo::commonOprDb('games')->query($insertSql);
        $this->response(1, '保存成功');

    }

    public function saveRewards(){
        $input = $this->input->post();
        $rewards = $input['props']['prizeJson'] ?? [];
        $i = 0;
        foreach ($rewards as  &$reward){
            $i++;
            $reward = [
                'id' => $i,
                "num" => $reward['num'],
                "type" => $reward['propsId'],
                "propsId" => $reward['propsId'],
                "rtype" => $reward['rtype'],
                "skin" => intval($reward['skin']),
            ];
        }
        $rewards = json_encode($rewards, 32);
        $returnsRewardsTbl = otable::returnsRewards();
        $updateSql = "update {$returnsRewardsTbl} set `minLv`={$input['minLv']}, `maxLv`={$input['maxLv']}, `rewards`='{$rewards}' where id=".intval($input['id']);
        oo::commonOprDb('games')->query($updateSql);
        $this->response(1, '保存成功');
    }
}