<?php
/**
 * 系统设置
 */

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request as Req;
use Request;

/**
 *
 */
class BaseSetController extends SystemController {
    /**
     *
     */
    function Index() {
        $db = new \App\Models\Setinfo();
        $notice = $db->getInfo(8);//公告
        $bank = $db->getInfos(10);//银行卡
        $tan_box = $db->getInfo(6);//弹框内容
        $tan_box['extinfo'] = explode(',', $tan_box['extinfo']);
        $new_box = $db->getInfos(33);//新版弹框内容

        //dump($tan_box);
        $ser_qq = $db->getInfo(16);//QQ
        $connectioninfo = $db->getInfos(1017);//联系我们
        $agent = $db->getInfo(13);//代理
        $plat = $db->getInfo(17);//平台
        $game = $db->getInfo(15);//游戏
        $run = $db->getInfo(9);//跑马灯
        $two = $db->getInfo(20);//二级密码
        $url = $db->getInfo(18);//api
        $add_token = $db->getInfo(19);
        $agent_box = $db->getInfo(21);
        $quickUrl = $db->getInfo(22);    //快捷支付网关地址
        $ipLimit = $db->getInfo(23);//IP设置
        $net = $db->getInfos(24);//网站设置
        $agentUrl = $db->getInfo(30);//网站设置
        $nagentFxUrl = $db->getInfo(1018);//级差代理分享域名设置
        $extension = $db->getInfo(31);//广告
        $open = $db->getInfo(1000);//开奖token
        $info = $db->getInfo(1024); //分享注册页面信息设置
        $startup = $db->getInfo(1111); //启动页设置设置
        $fsnum = $db->getInfo(1001); //启动页设置设置
        $stsource = $db->getInfo(1002); //启动页设置设置
        $wsport = $db->getInfo(9501);//websocket聊天服务器ip 端口设置
        $jnd = $db->getInfo(40);//加拿大28维护
        $playtest = $db->getInfo(2000);//试玩账号设置
        $oggame = $db->getInfo(2001);//真人
        $liao = $db->getInfo(2002);//聊天白名单
        $word = $db->getInfo(2003);//敏感字
        $imglink = $db->getInfo(2004);//图片服务器地址
        $H5ShareLink = $db->getInfo(2005);//h5代理分享链接
        $tokentime = $db->getInfo(100);//token前端处理失效时间
        $updateOdds = $db->getInfo(1911);//是否更新赔率
        $updateTime = $db->getInfo(1912);//缓存更新时间
        $paymentCate = $db->getInfo(20060);//充值排序设置
        $source = \App\Models\Stzqlocalleague::select('source')->groupby('source')->get()->toArray();//体育比分数据源设置
        if(count($source)>1){
            $source[] = Array("source" => "混合数据");
        }
        if (!empty($jnd['extinfo'])) {
            $jnd['extinfo'] = explode('~', $jnd['extinfo']);
        }
        if (is_array($net) && count($net) > 0) {
            $net = $this->netData($net);
        }
        if (is_array($connectioninfo) && count($connectioninfo) > 0) {
            $connectioninfo = $this->netData($connectioninfo);
        }
        if (is_array($new_box) && count($new_box) > 0) {
            $new_box = $this->netData($new_box);
        }
// var_dump($fsnum);die;//infotype
        $db_reg = new \App\Models\Settings();
        $reg = $db_reg->getSet();
        return view('admin.baseSet/index', ['notice' => $notice, 'bank' => $bank, 'tan_box' => $tan_box, 'new_box' => $new_box, 'qq' => $ser_qq, 'connectioninfo' => $connectioninfo,
            'agent' => $agent, 'plat' => $plat, 'game' => $game, 'run' => $run, 'two' => $two,
            'url' => $url, 'reg' => $reg, 'add_token' => $add_token, 'agent_box' => $agent_box,
            'quickUl' => $quickUrl, 'ip' => $ipLimit, 'net' => $net, 'agentUrl' => $agentUrl,
            'extension' => $extension,'fsnum'=>$fsnum,'stsource'=>$stsource, 'open' => $open, 'nagentFxUrl' => $nagentFxUrl, 'regInfo' => $info,
            'startup' => $startup, 'wsport' => $wsport, 'jnd' => $jnd, 'playtest' => $playtest,
            'oggame' => $oggame, 'liao' => $liao, 'word' => $word, 'imglink' => $imglink, 'H5ShareLink' => $H5ShareLink,
            'tokentime' => $tokentime, 'updateOdds' => $updateOdds, 'updateTime' => $updateTime,'paymentCate'=>$paymentCate,'source'=>$source]);
    }

    function info() {
        $db = new \App\Models\Setinfo();
        $data = $db->getInfos(10);//银行卡
        return \App\Lib\DataTable\DataTable::init()->toJson($data['data'], $data['total']);
    }

    //处理网站设置数据
    private function netData($data) {

        $newarr = array();
        foreach ($data as $key => $value) {
            $newarr[$value['remarks']] = $value;
        }
        return $newarr;
    }

    function show() {
        return view('admin.systemSet/setBase');
    }

    //更新设置数据
    function updateInfo(Req $req) {
        $data = $req->all();
        $data = $data['data'];
        if (empty($data) || count($data) < 1) {
            return responseToJson(-5030002031);
        }
        if (isset($data['contentype'])) {
            if ($data['contentype'] == 2) {
                $data['remarks'] = strip_tags($data['remarks']);
            }
            $data['extinfo'] = $data['contentype'];
            unset($data['contentype']);
        }
        $type = $data['type'];
        unset($data['type']);
        if (is_numeric($type)) {
            $title = $data['infoname'];
            $db = new \App\Models\Setinfo;
            if ($type == 17) {
                //密码校验
                $res = $this->checkPwd($data['password']);
                if ($res < 0) {
                    return responseToJson($res);
                }
                $path = $this->getPath();
                $status = $data['status'] == 1 ? 1 : 2;
                //拼凑token
                $suiji = GenEncryption();
                $token = session('adminInfo.admin_name') . '||' . session('adminInfo.passwd') . '||' . $suiji . '||' . REMOTE_KEY;
                $rtoken = md5(md5($token));
                $url = $path . 'close?status=' . $status . '&token=' . session('adminInfo.admin_name') . '||' . $rtoken . '||' . $suiji;
                $arrA = $this->getUrl($url);
                if ($arrA) {
                    return responseToJson(-200031);
                }
                unset($data['password']);
            }

            if ($type == 24) {
                $netdata = array(
                    'infoname' => $data['infoname'],
                    'infotype' => $type,
                );

                $namedata = $netdata;
                $namedata['infocontent'] = $data['netname'];
                $namedata['remarks'] = 'netname';

                $recedata = $netdata;
                $recedata['infocontent'] = $data['recedata'];
                $recedata['remarks'] = 'recedata';

                $keywordsdata = $netdata;
                $keywordsdata['infocontent'] = $data['netkeywords'];
                $keywordsdata['remarks'] = 'netkeywords';

                $descdata = $netdata;
                $descdata['infocontent'] = $data['netdesc'];
                $descdata['remarks'] = 'netdesc';

                $logourl = $netdata;
                $logourl['infocontent'] = $data['logourl'];
                $logourl['remarks'] = 'logourl';

                $loginlogo = $netdata;
                $loginlogo['infocontent'] = $data['loginlogo'];
                $loginlogo['remarks'] = 'loginlogo';


                $quicklypay = $netdata;
                $quicklypay['infocontent'] = $data['quickly_pay'];
                $quicklypay['remarks'] = 'quickly_pay';

                $appdownload = $netdata;
                $appdownload['infocontent'] = $data['app_download'];
                $appdownload['remarks'] = 'app_download';

                //真人网址
                $realperson = $netdata;
                $realperson['infocontent'] = $data['real_person'];
                $realperson['remarks'] = 'real_person';
                /*	if(empty($data['recedataid'])||empty($data['recedataid'])){
                        $res = $db->addInfo($namedata);
                        $res = $db->addInfo($recedata);
                        $res = $db->addInfo($keywordsdata);
                        $res = $db->addInfo($descdata);
                    }else{*/

				//showhome //前台默认模板
				$showhome = $netdata;
				$showhome['infocontent'] = $data['showhome'];
				$showhome['remarks'] = 'showhome';

                $res = $db->checkdata($quicklypay, $data['quicklypayid']);
                $res = $db->checkdata($appdownload, $data['appdownloadid']);
                $res = $db->checkdata($logourl, $data['logourlid']);
                $res = $db->checkdata($loginlogo, $data['loginlogoid']);
                $res = $db->checkdata($namedata, $data['netnameid']);
                $res = $db->checkdata($recedata, $data['recedataid']);
                $res = $db->checkdata($keywordsdata, $data['netkeywordsid']);
                $res = $db->checkdata($descdata, $data['netdescid']);
                $res = $db->checkdata($realperson, $data['realpersonid']); //真人网址
                $res = $db->checkdata($showhome, $data['showhomeid']);


                /*}*/
            } else if ($type == 33) {
                $condata = array(
                    'infoname' => $data['infoname'],
                    'infotype' => $type,
                );

                // $newsdata = $condata;
                // $newsdata['infocontent'] = $data['important_news'];
                // $newsdata['remarks'] = 'important_news';

                $sitedata = $condata;
                $sitedata['infocontent'] = $data['site_navigation'];
                $sitedata['remarks'] = 'site_navigation';

                $contdata = $condata;
                $contdata['infocontent'] = $data['contact_customer'];
                $contdata['remarks'] = 'contact_customer';

                $timeddata = $condata;
                $timeddata['infocontent'] = $data['con_timed'];
                $timeddata['remarks'] = 'con_timed';


                if (!empty($newsdata['infocontent'])) $res = $db->checkdata($newsdata, $data['important_newsid']);
                if (!empty($sitedata['infocontent'])) $res = $db->checkdata($sitedata, $data['site_navigationid']);
                if (!empty($contdata['infocontent'])) $res = $db->checkdata($contdata, $data['contact_customerid']);
                if (!empty($timeddata['infocontent'])) $res = $db->checkdata($timeddata, $data['con_timedid']);
                /*}*/
            } else if ($type == 1017) {
                $condata = array(
                    'infoname' => $data['infoname'],
                    'infotype' => $type,
                );

                $teldata = $condata;
                $teldata['infocontent'] = $data['con_tel'];
                $teldata['remarks'] = 'con_tel';

                $qqdata = $condata;
                $qqdata['infocontent'] = $data['con_qq'];
                $qqdata['remarks'] = 'con_qq';

                $skypedata = $condata;
                $skypedata['infocontent'] = $data['con_skype'];
                $skypedata['remarks'] = 'con_skype';

                $onlinesdata = $condata;
                $onlinesdata['infocontent'] = $data['con_onlines'];
                $onlinesdata['remarks'] = 'con_onlines';

                $weixindata = $condata;
                $weixindata['infocontent'] = $data['con_weixin'];
                $weixindata['remarks'] = 'con_weixin';

                $emaildata = $condata;
                $emaildata['infocontent'] = $data['con_email'];
                $emaildata['remarks'] = 'con_email';

                if (!empty($teldata['infocontent'])) $res = $db->checkdata($teldata, $data['con_telid']);
                if (!empty($qqdata['infocontent'])) $res = $db->checkdata($qqdata, $data['con_qqid']);
                if (!empty($skypedata['infocontent'])) $res = $db->checkdata($skypedata, $data['con_skypeid']);
                if (!empty($onlinesdata['infocontent'])) $res = $db->checkdata($onlinesdata, $data['con_onlinesid']);
                if (!empty($weixindata['infocontent'])) $res = $db->checkdata($weixindata, $data['con_weixinid']);
                if (!empty($emaildata['infocontent'])) $res = $db->checkdata($emaildata, $data['con_emailid']);

                /*}*/
            } else if ($type == 40) {//qtx 2018-12-12
                /*if(!empty($data['starttime']) && !empty($data['endtime'] && date('H:i:s', strtotime($data['starttime']))  == $data['starttime'] && date('H:i:s', strtotime($data['endtime']))  == $data['endtime'])){}*/
                //2018-12-26 anton liu 修改
                $data['extinfo'] = $data['starttime'] . '~' . $data['endtime'];
                unset($data['starttime']);
                unset($data['endtime']);
                $res = $db->updateInfo($data, $type);

            } else if ($type == 1018) //2019-01-16 级差域名检测 anton liu
            {
                $dom = explode('||', $data['infocontent']);
                foreach ($dom as $k => $v) {
                    $isext = \App\Models\Nagent_detailed::checkDom($v, '');
                    if ($isext) {
                        return responseToJson(-1, $v . '已绑定专属代理');
                    }
                }
                $res = $db->updateInfo($data, $type);
            } else {
                $res = $db->updateInfo($data, $type);
            }
            if ($type == 9501 || $type == 2003) {
                $webSocket = array();
                //聊天配置信息推送
                if ($type == 9501) {   //服务器ip设置
                    $word = $db->getInfo(2003);//敏感字
                    $server = $data['infocontent'];
                    $webSocket = [
                        'sign' => md5(time() . $data['extinfo']),
                        'time' => (int)time(),
                        'word_info' => $word['infocontent'],
                    ];
                }
                if ($type == 2003) { //聊天敏感字符
                    $wsport = $db->getInfo(9501);//websocket聊天服务器ip 端口设置
                    $server = $wsport['infocontent'];
                    $webSocket = [
                        'sign' => md5(time() . $wsport['extinfo']),
                        'time' => (int)time(),
                        'word_info' => $data['infocontent'],
                    ];
                }

                // infocontent 值为ws:192.168.2.200:9501|wss:192.168.2.200:9501
                $server = !empty($server) ? explode('||', $server) : '';
                $server = !empty($server[0]) ? explode(':', $server[0]) : '';
                if (empty($server[1])) {
                    return responseToJson(-9501, '聊天服务器IP地址错误:' . $server[1]);
                }
                $server = count($server) > 2 ? $server[1] . ':' . $server[2] : $server[1];
                $postUrls = $server . '/' . 'whiteList';
                $chs = curl_init();//初始化curl
                curl_setopt($chs, CURLOPT_URL, $postUrls);//抓取指定网页
                curl_setopt($chs, CURLOPT_HEADER, 0);//设置header
                curl_setopt($chs, CURLOPT_TIMEOUT, 15);
                curl_setopt($chs, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
                curl_setopt($chs, CURLOPT_POST, 1);//post提交方式
                curl_setopt($chs, CURLOPT_POSTFIELDS, $webSocket);
                curl_exec($chs);//运行curl
                if (curl_errno($chs) != 0) {
                    $status = -9501;
                    $msg = '--聊天服务器IP地址错误--';
                } else {
                    $status = 1;
                    $msg = '成功';
                }
                curl_close($chs);
                return responseToJson($status, $msg);
            }
        } else {
            $title = '会员注册设置';
            $db_reg = new \App\Models\Settings();
            $res = $db_reg->updateSet($data);
        }

        $log = array(
            session('adminInfo.admin_name'),
            $title,
        );
        OperationLog(session('adminInfo.admin_id'), 'editBaseSet', $log);
        return responseToJson($res);
    }

    //检测密码
    function checkPwd($password) {
        $admin_id = session('adminInfo.admin_id');
        $db = new \App\Models\System_user;
        $admin_info = $db->getAdminInfo($admin_id, 1);
        if (!VerPassword($password, $admin_info['encryption_2'], $admin_info['password_2'])) {
            return -7095167422;
        }
        return 1;
    }

    //访问接口
    function getUrl($url) {
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
//        显示获得的数据
//        print_r($data);
    }

    function getPath() {
        $data = \App\Models\Setinfo::getPath();
        return $data;
    }

    //获取基础设置
    function getBaseSet() {
        $infoname = Request::has('infoname') ? Request::get('infoname') : '';
        $infocontent = Request::has('infocontent') ? Request::get('infocontent') : '';
        $status = Request::has('status') ? Request::get('status') : '';

        $where = array();
        if (!empty($infoname)) {
            $where[] = array('infoname', 'like', '%' . $infoname . '%');
        }
        if (!empty($infocontent)) {
            $where[] = array('infocontent', 'like', '%' . $infocontent . '%');
        }
        if (!empty($status)) {
            if ($status == 2) {
                $where[] = array('status', '=', '0');
            } else {
                $where[] = array('status', '=', $status);
            }
        }

        $db = new \App\Models\Setinfo();
        $data = $db->getAllSet($where);
        return \App\Lib\DataTable\DataTable::init()->toJson($data, count($data));
    }

    function Edit(Req $req) {
        $infotype = $req->infotype;
        if (empty($infotype)) {
            abort(404);
        }
        $db = new \App\Models\Setinfo();
        $arr = array(6, 16, 19, 9, 13); //含有设置框的infotype
        if (!$req->isMethod('post')) {
            $data = $db::where('infotype', $infotype)->first();
            if (!$data) {
                abort(404);
            }
            $data = $data->toArray();
            return view('admin.systemSet/edit', ['data' => $data, 'arr' => $arr]);
        } else {

            $model = $db::where('infotype', $infotype)->first();
            if (!empty($req->input('infocontent'))) {
                $model->infocontent = $req->input('infocontent');
            }
            $model->status = $req->input('status');
            $model->save();
            return responseToJson(1);
        }
    }

    //玩法简介
    function Playdesc() {
        $dt = \App\Lib\DataTable\DataTable::init();
        $dt->setDataSource('/admin/System/active');
        $dt->setLang('notice');
        $dt->addColsFields('id', array('width' => 170, 'fixed' => 'left'));
        $dt->addColsFields('name');
//        $dt->addColsFields('play_desc');
        $dt->addColsFields('table_name');
        $dt->setToolBar(array('view', 'edit'));
        return view('admin.systemSet/arictle', $dt->render());
    }

    /**
     * 公告显示
     */
    function Notice() {
        $db = new \App\Models\Setinfo();
        $data = $db->getNotice();
        return responseToJson($data);
    }


    /**
     * 弹框
     */
    function OutBox() {
        $db = new \App\Models\Setinfo();
        $data = $db->getBoxOut();
        return responseToJson($data);
    }


    /**
     * 客服QQ设置
     */
    function ServerQQ() {
//        $data=DB::table('setinfo')->where('infotype',14)->get();
        //        dump($data->toArray());
        $db = new \App\Models\Setinfo();
        $data = $db->getQQnumber();
        return responseToJson($data);
    }

    /**
     * 代理设置
     */
    function Agent() {
        $db = new \App\Models\Setinfo();
        $data = $db->getAgentSet();
        return responseToJson($data);
    }

    function Fsnum() {
        $db = new \App\Models\Setinfo();
        $data = $db->getFsnumSet();
        return responseToJson($data);
    }

    /**
     * 平台维护
     */
    function PlatFrom() {
        $db = new \App\Models\Setinfo();
        $data = $db->getPlatSet();
        return responseToJson($data);
    }

    /**
     * 平台维护设置
     */
    function PlatFromSet() {

    }

    //虚拟游戏设置显示
    function Flaseprize() {
        $db = new \App\Models\Setinfo();
        $data = $db->getPrizeSet();
        return responseToJson($data);
    }

    //转账银行卡信息
    function BankInfo() {
        $db = new \App\Models\Setinfo();
        $data = $db->getBankInfo();
        return responseToJson($data);
    }

    //跑马灯公告
    function RunNotice() {
        $db = new \App\Models\Setinfo();
        $data = $db->getRunNotice();
        return responseToJson($data);
    }

    //注册设置信息
    function RegisterSet() {
        $db = new \App\Models\Settings();
        $data = $db->getSet();
        return responseToJson($data);
    }

    /**
     * 游戏玩法说明消息
     */
    function Active() {
        $list = Request::has('limit') ? Request::get('limit') : 10;
        $db = new \App\Models\GameType();
        $data = $db->getDescList($list);
        return \App\Lib\DataTable\DataTable::init()->toJson($data['data'], $data['total']);
//        return responseToJson($data);
    }


    /**
     * 系统菜单列表
     */
    function SystemMenu() {
        $db = new \App\Models\Menu();
        $data = $db->getMenuAll();
        return responseToJson($data);
    }

    /**
     * 菜单
     */
    function MenuList() {
        $data = config('menu');
        return responseToJson($data);
    }

    //获取网站设置
    function getWebTitle(Req $req) {
        $data = \App\Models\Setinfo::getWebSet();
        return responseToJson($data);
    }

    public function clearCache() {

        $db = new \App\Models\Setinfo();
        $rec = $db->where('infotype', '1912')->first();
        if (!$rec) {
            $ret = $db->addInfo(['infotype' => '1912','infoname'=>'缓存更新时间', 'infocontent' => date('Y-m-d H:i:s')]);
        } else {
            $ret = $db->where('infotype', '1912')->update(['infocontent' => date('Y-m-d H:i:s')]);
        }

        return responseToJson($ret ? 1 : -999, $ret ? '更新缓存时间成功' : '更新缓存时间失败');
    }
}

