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

/**
 * 信鸽推送
 */
class Push 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();
        $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()
    {
        $data = array( 'list' => array(), 'total' => 0, 'langList' => []);
        if( $this->env == 1 ){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }
        $this->postdata['mod'] = 'Push';
        $this->postdata['act'] = 'getPushSettingList';
        $retData = $this->curl->req($url, $this->postdata);
        $list = json_decode($retData, TRUE);
        if (is_array($list) && !empty($list)) {
            $data['list'] = $list['list'];
            $data['total'] = $list['count'];
            //分页
            $pageConfig = $this->pageConfig;
            $pageConfig['base_url'] = base_url('#push/index');
            $pageConfig['total_rows'] = $list['count'];
            $pageConfig['per_page'] = $this->page;
            $this->pagination->initialize($pageConfig);
            $pageurl = $this->pagination->create_links();
            $data['pageurl'] = $pageurl;
        }
        $data['langList'] = $this->_langList;
        $posts = $this->postdata;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $url  = $this->config->item('officialUrl');
        $config = $this->curl->req($url, $posts);
        $data['props'] = json_decode($config,true)['props'];

        $data['userGroup'] = oo::commonOprModel('config')->getUserGroupConfig2();

        $data['running'] = array_keys(oo::commonOprRedis('games')->hGetAll(okeys::PushNew()));
        $data['size']    = intval(oo::commonOprRedis('games')->lSize(okeys::FireBaseList()));
        $this->load->view('push/index', $data);
    }

    public function log(){
        $data = array( 'list' => array(), 'total' => 0, 'langList' => []);
        if( $this->env == 1 ){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }
        $this->postdata['mod'] = 'Push';
        $this->postdata['act'] = 'getPushNewsList';
        $retData = $this->curl->req($url, $this->postdata);
        $list = json_decode($retData, TRUE);
        if (is_array($list) && !empty($list)) {
            $data['list'] = $list['list'];
            $data['total'] = $list['count'];
            //分页
            $pageConfig = $this->pageConfig;
            $pageConfig['base_url'] = base_url('#push/index');
            $pageConfig['total_rows'] = $list['count'];
            $pageConfig['per_page'] = $this->page;
            $this->pagination->initialize($pageConfig);
            $pageurl = $this->pagination->create_links();
            $data['pageurl'] = $pageurl;
        }
        $this->load->view('push/log', $data);
    }

    /**
     *	新增推送
     */
    public function actionAddNews(){
        $input = $this->input->post();
        if(empty($input['time']) && $input['type'] != 0){
            self::AjaxContent(['message'=>'推送时间不能为空']);
        }
        $userType    = $input['usertype'];
        $deviceType  = $input['devicetype'];
        $accountType = $input['accounttype'];
        $intervalTime = $input['intervalTime'];
        $level       = $input['level']??0;
        if($level){
            $level   = [
                $input['levelMin'],
                $input['levelMax'],
            ];
        }
        $userGroup   = $input['userGroup'];
        if( $userType == 2 ){
            $uidList = implode(',', explode("\n", $input['uidlist']));
            if(empty($uidList)){
                self::AjaxContent(['message'=>'推送对象不能为空']);
            }
        }
        $title   = array_filter($input['title']);
        $content = array_filter($input['content']);
        if(empty($title['en']) || empty($content['en'])){
            self::AjaxContent(['message'=>'推送内容不能为空']);
        }
        $remark    = $input['remark'];
        if(oo::commonOprModel('Push')->actionPush($input['date'],$input['time'],$intervalTime,json_encode($title),json_encode($content),$userType,$input['type'],$uidList,$deviceType,$accountType,$remark,$level,$userGroup)){
            self::AjaxContent(['state'=>'success','message'=>'成功']);
        }
        die(json_encode($this->data));
    }


    /**
     *	新增推送
     */
    public function actionAddNewsExchange()
    {
        $input= $this->input->post();
        $type = $this->input->post('type');
        $date = $this->input->post('date');
        $time = $this->input->post('time');
        $intervalTime = $this->input->post('intervalTime');
        if(empty($time) && $this->postdata['type'] != 0){
            self::AjaxContent(['message'=>'推送时间不能为空']);
        }
        $userType     = $this->input->post('usertype');
        $deviceType   = $this->input->post('devicetype');
        $accountType  = $this->input->post('accounttype');
        if( $userType == 2 ){
            $uidlist = $this->input->post('uidlist');
            $uidList = implode(',', explode("\n", $uidlist));
            if(empty($uidList)){
                self::AjaxContent(['message'=>'推送内容不能为空']);
            }
        }
        $title   = array_filter($this->input->post('title'));
        $content = array_filter($this->input->post('content'));
        if(empty($title) || empty($content)){
            self::AjaxContent(['message'=>'推送内容不能为空']);
        }
        $level       = $input['level']??0;
        if($level){
            $level   = [
                $input['levelMin'],
                $input['levelMax'],
            ];
        }
        $userGroup   = $input['userGroup'];
        /** 新增兑换码 */
        $exchangeData = array('frombg' => 1, 'lid' => 1, 'sid' => 1);
        $reward = [
            'spins' => $this->input->post('spins'),
            'coins' => $this->input->post('coins'),
        ];
        $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],
                ];
            }
        }

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

        $exchangeData['reward']   = json_encode($reward,JSON_NUMERIC_CHECK);
        $exchangeData['userType'] = 0; //领取的用户类型
        $exchangeData['limit']    = $this->input->post('num'); //兑换数量
        $exchangeData['day']      = $this->input->post('exchangeDay')." ".$this->input->post('exchangeTime');      //过期时间
        $exchangeData['remake']   = "自动推送生成";
        $exchangeData['mod'] = 'Exchange';
        $exchangeData['act'] = 'createCode';
        $retData = $this->curl->req($this->config->item('officialUrl'), $exchangeData);
        $retData = json_decode($retData, TRUE);
        $exchangeCode = $retData['num'];
        if(oo::commonOprModel('Push')->actionPush($date,$time,$intervalTime,json_encode($title),json_encode($content),$userType,$type,$uidList,$deviceType,$accountType,$remark,$level,$userGroup,['id'=>1,'content'=>intval($exchangeCode)])){
            self::AjaxContent(['state'=>'success','message'=>'成功']);
        }
        die(json_encode($this->data));
    }

    public function delete(){
        $id = $this->input->post('id');
        oo::commonOprRedis('games')->hDel(okeys::PushNew(),$id);
        if( $this->env == 1 ){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }
        $this->postdata['mod'] = 'Push';
        $this->postdata['act'] = 'deletePushNews';
        $this->postdata['id'] = $id;
        $retData = $this->curl->req($url, $this->postdata);
        $r = json_decode($retData, 1);
        if( $r['code'] == 1 ){
            $this->data['state'] = 'success';
            $this->data['message'] = '成功';
            $this->data['refresh'] = true;
        }
        die(json_encode($this->data));
    }

    public function updateLevel(){
        $downLevel   = oo::commonOprModel('config')->getSysCon('UpdateMaxLevel','downLevel');
        $langContent = oo::commonOprModel('config')->getSysCon('UpdateMaxLevel','push');
        $langContent = json_decode($langContent,true);
        $lang = $this->_langList;
        $data[] =
        $this->load->view('push/updateLevel', [
            'downLevel' => $downLevel,
            'content'   => $langContent,
            'lang'   => $lang,
        ]);
    }

    public function actionDownLevel(){
        $downLevel = $this->input->post('downLevel');
        if(oo::commonOprModel('config')->setSysCon('UpdateMaxLevel','downLevel',$downLevel)){
            self::AjaxContent(['state'=>'success','message'=>'成功']);
        }
        die(json_encode($this->data));
    }

    public function actionUpdateLevel(){
        $input = $this->input->post();
        $lang  = array_keys($input['title']);
        $content = [];
        foreach ($lang as $row){
            $content[strtolower($row)] = [
                'title'   => $input['title'][$row],
                'content' => $input['content'][$row],
            ];
        }
        if(oo::commonOprModel('config')->setSysCon('UpdateMaxLevel','push',json_encode($content))){
            self::AjaxContent(['state'=>'success','message'=>'成功']);
        }
        die(json_encode($this->data));
    }

    //============================
    public function config(){
        $data =[];
        $list = $this->getPushConf(true);
//        echo json_encode($list);die;
        foreach ($list as $k=>$v){
            $currentLangTexts = array_keys($v['conf']);
            foreach ($this->_langList as $langKey => $langText){
                if(!in_array($langKey, $currentLangTexts))$list[$k]['conf'][$langKey] = [
                    'title' => '',
                    'content' => '',
                ];
            }
            $list[$k]['conf']=json_encode($list[$k]['conf'],256);
        }
        array_multisort(array_column($list,'id'),SORT_ASC,$list);
        $data['list'] = $list;
        $postData= array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);
        $postData['mod'] = 'Activitynew';
        $postData['act'] = 'getTypeConf';
        $data['langList'] = $this->_langList;
        $data['acts'] = $this->getDateFromServer($postData)['act_type'] ?? [];
        $this->load->view('push/config', $data);
    }
    public function saveConfig(){
        $input = $this->input->post();
        $id = $input['id'];
        $conf = addslashes(json_encode($input['conf'],256));
        $tb = otable::fasebasePushConf();
        oo::commonOprDb('games')->query("set names utf8mb4");
        $sql = "UPDATE {$tb} SET conf='{$conf}' where id={$id}";
        $res = oo::commonOprDb('games')->query($sql);
        if($res){
            $this->getPushConf(true);
        }
        $this->response(0, '更新成功',$input['conf']);
    }
    public function addConfig(){
        $input = $this->input->post();
        $tb = otable::fasebasePushConf();
        $key = okeys::fasebasePushConf();
        if(empty($input['name'])
        ||($input['class'] == '-1')
        ||($input['type'] == '-1')
        )$this->response(__LINE__ * -1, '请填写完整数据');
        $record = oo::commonOprDb('games')->getOne("select * from {$tb} where class='{$input['class']}' and  type='{$input['type']}' limit 1");
        if($record)$this->response(__LINE__ *-1, '该类型推送点已存在');
        $sql = "insert into  {$tb} (`name`,`class`,`type`,`status`,`conf`) values ('{$input['name']}','{$input['class']}','{$input['type']}',1,'{$input['conf']}')";
        $res = oo::commonOprDb('games')->query($sql);
        if(!$res)$this->response(__LINE__ * -1, '推送点保存失败');
        $id  = oo::commonOprDb('games')->insertID();
        $conf = [
            'name' => $input['name'],
            'class' => $input['class'],
            'type' => $input['type'],
            'status' => $input['status'],
            'conf' => json_decode($input['conf'], true) ?? [],
        ];
        oo::commonOprRedis('games')->hSet($key, $id, json_encode($conf));
        if($res)$this->response(1, '推送点保存成功');
    }

    public function delConfig($id){
        $id = intval($id);
        $tb = otable::fasebasePushConf();
        $key = okeys::fasebasePushConf();
        oo::commonOprRedis('games')->hDel($key, $id);
        $sql = "delete  FROM {$tb} where id =".$id;
        $res = oo::commonOprDb('games')->query($sql);
        if($res)$this->response(__LINE__, '推送点删除成功');
        $this->response(__LINE__ * -1, '推送点删除失败');
    }
}