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

/**
 * Class SystemMail
 * Created by: Richard
 * Created on: 2021/03/04 11:08
 */
class SystemMail extends MY_Controller
{
	protected $page = 25;//分页
    protected $langs = [];
    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>",
    );

    private $sids = [
        0 => '全部',
        1 => '安卓',
        2 => '苹果',
    ];

    private $coins = [201=>"coins01",202=>"coins02",203=>"coins03",204=>"coins04",205=>"coins05",206=>"coins06"];

	public function __construct()
	{
        parent::__construct();
		$this->load->helper('url');
		$this->load->helper('cookie');
        $this->load->library('pagination');
		$this->load->model('oo');
        $this->langs = oo::commonOprModel('config')->getCurLangs();
	}

    /**
     * 系统邮件列表
     */
    public function index($page = 0){
        $data = ['stime' => '', 'etime' => '', 'langs' => $this->langs, 'sids' => $this->sids];
        $dateArr = array();
        if( $stime = get_cookie('create_stime') ){
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime.'0:0:1');
        }else{
            $data['stime'] = '';
            $dateArr['stime'] = 0;
        }

        if( $etime = get_cookie('create_etime') ){
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime.' 23:59:59');
        }else{
            $data['etime'] = date("Y-m-d");
        }

        $where = '1 = 1';
        if(!empty($dateArr['stime'])){
            $where .= " AND create_time >= {$dateArr['stime']}";
        }
        if(!empty($dateArr['etime'])){
            $where .= " AND create_time < {$dateArr['etime']}";
        }

        $table = otable::sysMailMsg();
        $data['page'] = $page;
	    $limitStr = " limit $page, {$this->page}";
	    $sql = "SELECT * FROM {$table} WHERE {$where} ORDER BY create_time DESC {$limitStr}";

        $data['list'] = oo::commonOprDb('slavedb')->getAll($sql, 1);
        foreach ($data['list'] as $k => $mail){
            $title = json_decode($mail['title'], true);
            $data['list'][$k]['title'] = $title['ZH'];
        }

        //获取总数
        $totalSql = " SELECT COUNT(*) AS t FROM {$table} WHERE {$where}";
        $totalRet = oo::commonOprDb('slavedb')->getOne($totalSql, MYSQLI_ASSOC);
        $data['total'] = (int)$totalRet['t'];

        //分页
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#SystemMail/index');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = $this->page;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;

        $this->load->view('systemmail/index', $data);
    }

    public function editBak($id = 0){
        if(empty($id)){
            $info = [];
        }else{
            $tb = otable::sysMailMsg();
            $info  = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id='{$id}'",1);
            if(!empty($info)){
                $info['title'] = (array)json_decode($info['title'], true);
                $info['body'] = (array)json_decode($info['body'], true);
                $info['langs'] = (array)json_decode($info['langs'], true);           
                $info['rewards'] = (array)json_decode($info['rewards'], true);           
                $info['uids'] = implode(',', (array)json_decode($info['uids'], true));
                $info['version'] = explode(',', $info['version']);
                if(empty($info['version'])){
                    $info['version'] = [0, 0];
                }

                foreach($info['rewards'] as $k => $v){
                    if(!isset($v['coins'])){
                        continue;
                    }
                    foreach($this->coins as $kk => $vv){
                        $v['propsId'] = $kk;
                    }
                    $info['rewards'][$k] = $v;
                }
            }
        }

        $posts = ['frombg'=>1,'lid' =>1,'sid'=>1];
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $url  = $this->config->item('officialUrl');
        $config = $this->curl->req($this->config->item('officialUrl'), $posts);
        $props  = json_decode($config,true)['props'];
        $versions  = oo::commonOprModel('config')->versions;
        $this->load->view('systemmail/edit2', ['props' => $props, 'data'=>$info, 'id'=>$id, 'langs' => $this->langs, 'sids' => $this->sids, 'versions' => $versions]);
    }

    public function edit($id = 0){
        if(empty($id)){
            $info = [];
        }
        else{
            $tb = otable::sysMailMsg();
            $info  = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id='{$id}'",1);
            if(!empty($info)){
                $info['title'] = (array)json_decode($info['title'], true);
                $info['body'] = (array)json_decode($info['body'], true);
                $info['langs'] = (array)json_decode($info['langs'], true);
                $info['rewards'] = (array)json_decode($info['rewards'], true);
                $info['uids'] = implode(',', (array)json_decode($info['uids'], true));
                $info['version'] = explode(',', $info['version']);
                if(empty($info['version'])){
                    $info['version'] = [0, 0];
                }

                foreach($info['rewards'] as $k => $v){
                    if(!isset($v['coins'])){
                        continue;
                    }
                    foreach($this->coins as $kk => $vv){
                        $v['propsId'] = $kk;
                    }
                    $info['rewards'][$k] = $v;
                }
            }
        }

//        $posts = ['frombg'=>1,'lid' =>1,'sid'=>1];
//        $posts['mod'] = 'Config';
//        $posts['act'] = 'getPropsConfig';
//        $url  = $this->config->item('officialUrl');
//        $config = $this->curl->req($this->config->item('officialUrl'), $posts);
//        $props  = json_decode($config,true)['props'];
        $propsConfig  = oo::commonOprModel('config')->getPropsConfigFromLocal();
        $rewardData =[];
        foreach ($info['rewards'] as $v){
            $one=[
                "propsId"=>intval($v['propsId']),
                "num"=>intval($v['num']),
                "rtype"=>$v['rtype']?$v['rtype']:1,
                "skin"=>$v['skin']?$v['skin']:0,
            ];
            $rewardData[] = $one;
        }

        $versions  = oo::commonOprModel('config')->versions;
        $this->load->view('systemmail/edit2', ['propsConfig' => $propsConfig,"rewardData"=>$rewardData,'data'=>$info, 'id'=>$id, 'langs' => $this->langs, 'sids' => $this->sids, 'versions' => $versions]);
    }

    public function actionEdit(){
        $data = $this->input->post();
        $id = $data['id'];
        $title = addslashes(json_encode($data['title']));
        $body = addslashes(json_encode($data['body']));
        $langs = json_encode($data['langs']);
        $data['online_start'] = $onlineStart = strtotime($data['online_start']);
        $data['online_end'] = $onlineEnd = strtotime($data['online_end']);
        $data['days'] = isset($data['days']) ? (int)$data['days'] : 1;
        $rewards = [];

        if(!empty($data['props']['rewardData'])){
//            foreach($data['props'][]['id'] as $k => $propsId){
//                if(!isset($data['props']['num'][$k])){
//                    continue;
//                }
//                $rewards[] = ['propsId' => $propsId, 'num' => $data['props']['num'][$k]];
//            }
            foreach($data['props']['rewardData'] as $k => $items){
                $rewards[] = [
                    'propsId' => $items['propsId'],
                    'num' => $items['num'],
                    'rtype' => $items['rtype'],
                    'skin' => $items['skin'],
                ];
            }
            unset($data['props']);
        }
        if(!empty($data['uids'])){
            $data['uids'] = explode(',', str_replace('，', ',', $data['uids']));
        }else{
            $data['uids'] = '';
        }

        $data['version'] = $data['versionMin'].",".$data['versionMax'];
        
        $uidStr = !empty($data['uids']) ? json_encode($data['uids'], JSON_NUMERIC_CHECK) : '';
        $data['rewards'] = $rewards;
        $time = time();
        $endTime = $data['days'] * 86400 + $time;
        $endTime = max($endTime, $onlineEnd);

        $rewardStr = json_encode($rewards);
        $tb = otable::sysMailMsg();
        if($id){
            $sql = "UPDATE {$tb} SET days='{$data['days']}',uids='{$uidStr}',online_start='{$onlineStart}',online_end='{$onlineEnd}',end_time='{$endTime}',level_start='{$data['level_start']}',level_end='{$data['level_end']}',score_start='{$data['score_start']}',score_end='{$data['score_end']}',sid='{$data['sid']}',langs='{$langs}',title='{$title}',body='{$body}',rewards='{$rewardStr}',version='{$data['version']}' WHERE id={$id}";
        }else{
            $sql = "INSERT INTO {$tb} (id,days,online_start,online_end,end_time,level_start,level_end,score_start,score_end,sid,langs,title,body,create_time,rewards,uids,version) VALUES(NULL,'{$data['days']}','{$onlineStart}','{$onlineEnd}',{$endTime},'{$data['level_start']}','{$data['level_end']}','{$data['score_start']}','{$data['score_end']}','{$data['sid']}','{$langs}','{$title}','{$body}','{$time}','{$rewardStr}','{$uidStr}','{$data['version']}')";
        }
        $res  = oo::commonOprDb('games')->query($sql);
        if($res == 0){
            return $this->response(1, '操作失败');
        }
        unset($data['package'], $data['lang'], $data['versionMin'], $data['versionMax']);
        //更新缓存
        $key = okeys::sysMailMsg();
        oo::commonOprRedis('games')->delete($key);
        $ttl = oo::commonOprRedis('games')->ttl($key);
        if($data['end_time'] - time() > $ttl){
            oo::commonOprRedis('games')->expireAt($key, $data['end_time'] + 600);
        }
        return $this->response(0, '操作成功');
    }
}
