<?php
use Business\User\LoginV2Model;
use Business\Message\MessageServiceModel;
class IndexController extends \Our\Controller_Abstract  {
    public $req;
    public $memberId;
    public $messageService;
    public function init(){

    }
    public function is_https() {
        if ( !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
            return true;
        } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
            return true;
        } elseif ( !empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
            return true;
        }elseif($_SERVER['SERVER_PORT'] == 89){
            return true;
        }

        return false;
    }
    public function getQrcodeFlowAction(){
        $imageKey=$_GET['imageKey'];
        $memberDb0Redis=\Redis\Db0\MemberRedisModel::getInstance();
        $imageFlow=$memberDb0Redis->tableCacheGet($imageKey);
        header('Content-type: image/jpg');
        echo $imageFlow;
        exit;
    }
    public function getHtmlAction(){
        $this->req=$this->getRequest()->getQuery();
        $postData=$this->req;
        $postData=base64_decode($postData[\Our\NameConst::sessionKey]);
        $params=explode(\Our\PathConst::cutVertical,$postData);
        $this->key=$params[0];
        session_id($this->key);
        $this->sess=\Yaf\Session::getInstance();
        $this->sess->start();
        if($this->sess['key']!=$this->key){
            echo 'error auth!';
            exit;
            // ErrorModel::throwException(CodeConfigModel::authExpire);
        }
        $this->memberDb0Redis=\Redis\Db0\MemberRedisModel::getInstance();

        $paramsStr= $this->memberDb0Redis->tableCacheGet($this->key);
        if($_GET['debug']==1){
            $paramsStr='{
        "desc": "最优质的产品，最实惠的价格，最好的服务质量，欢迎选购",
"deviceWidth": "828",
"id": "1050000",
"imgUrl": "http://qmoss-01.oss-cn-hangzhou.aliyuncs.com/mall/store/05960231407828374.jpg?x-oss-process=image/resize,m_fill,h_186,w_186",
"key": "bda203557fcc08150fc997360d432bfa",
"shareType": "1",
"storeName": "LQ日化用品",
"timestamp": "1543913056",
"type": "4",
"driverType": 2,
"qrCode": "https://img.shenbd.com/mall/salesman_qr/170.png",
"address": "鑫雄盛快捷酒店仓山紫番林幼儿园",
"storeWorkingtime": "",
"buyerDistribution": 1,
"sellerDistribution": 1,
"startShippingPrice": 2000,
"freeShippingPrice": 0,
"storeStartTime": "09:00",
"storeCloseTime": "23:00"
}';
        }

        $paramsStr=json_decode($paramsStr,true);
        if($paramsStr['type']==\Our\ApiConst::shareStore || $paramsStr['type']==\Our\ApiConst::shareSaler){
            $begin=strtotime($paramsStr['storeStartTime']);
            $end=strtotime($paramsStr['storeCloseTime']);
            if($begin>$end){
                $paramsStr['storeCloseTime']=\Our\DescribeConst::storeCloseTimePre.date('H:i',$end+\Our\ApiConst::oneDaySecond);
            }
            if($begin==$end){
                $paramsStr['storeCloseTime']=\Our\DescribeConst::allDay;
            }

        }
        if($paramsStr['startShippingPrice']){
            $paramsStr['startShippingPrice']=ceil(\Our\Common::getDivNum($paramsStr['startShippingPrice']));
        }
        if($paramsStr['freeShippingPrice']){

            $paramsStr['freeShippingPrice']=ceil(\Our\Common::getDivNum($paramsStr['freeShippingPrice']));
        }
        $this->_view->assign("params", $paramsStr);
        if($paramsStr['type']==\Our\ApiConst::sharePlat){
            $this->_view->display('index/plat.phtml');
        }
        if($paramsStr['type']==\Our\ApiConst::shareStore){
            $this->_view->display('index/store.phtml');
        }
        if($paramsStr['type']==\Our\ApiConst::shareGoods || $paramsStr['type']==\Our\ApiConst::shareGroup){

            $this->_view->display('index/goods.phtml');
        }
        if($paramsStr['type']==\Our\ApiConst::shareSaler){
            $this->_view->display('index/saleShare.phtml');
        }
        exit;
    }

    public function testPushAction(){
        $clientPush=\JPush\ClientPush::getInstance();
        $clientPush->pushTest(array());
        exit;
    }

    public function indexAction() {
        $getKey=$_GET['key'];
        if($getKey!='~!@#$`1234qwert'){
            throw new Exception('非法',-1111);
        }
        $orderDao = \DAO\Order\OrderModel::getInstance();
        $res=$orderDao->getList(array('buyer_id'=>1),'*',0,10);
        echo json_encode($res);exit;
        //$list = \Our\RedisHelper::cachedFunction(\Redis\Db4\GoodsBrowserRedisModel::getInstance(),array(&$browseDAO, 'getDistinctDate'),array($memberId,$startTime,$endTime,$order),\Our\ApiConst::twoMinSecond,array($memberId));
//        $clientPush=\JPush\ClientPush::getInstance();
//        $clientPush->pushAll();
//        exit;
//           $mongoDb= new \Mongo\MongoDbModel();
//      $res= $mongoDb->insert('message_history',array('id'=>1,'name'=>'chenchuanwen'));
//        echo json_encode($res);
//        exit;
//        \Our\Log::getInstance()->write('testLog|||||testLog');
//        var_dump($_SERVER);exit;
//       // echo $_SERVER['USER']);exit;
//        $elasticConfig=\Our\Common::getConfig('elastic.master');
//        $configArray=array(
//            $elasticConfig->host.':'.$elasticConfig->port,
//        );
//        $client=\Elasticsearch\ClientBuilder::create()->setHosts($configArray)->build();
//        $res=array(
//            'id'=>'nignx-log*',
//            'index'=>'.kibana',
//            'type'=>'index-pattern'
//        );
//        $res=$client->getSource($res);
//        echo json_encode($res);
//        exit;
    }

    public function check(){
        $this->req=$this->getRequest()->getPost();
        $this->checkEncrypt();
        if(empty($this->req['data']['key'])){
            \Error\ErrorModel::throwException(CodeConfigModel::illegalAccess);
        }
        session_id($this->req['data']['key']);
        ini_set('session.gc_maxlifetime', \Our\ApiConst::tenDaySecond);
        $sess=\Yaf\Session::getInstance();
        $sess->start();
        $this->memberId=$sess->get('member_id');
        if(empty($this->memberId)){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::noLogin);
        }
        //\Yaf\Dispatcher::getInstance()->disableView();
    }

    public function chatRoomAction(){
        $this->check();
        $this->messageService=MessageServiceModel::getInstance();
        $pageIndex=isset($this->req['data']['pageIndex'])?$this->req['data']['pageIndex']:0;
        $pageSize=isset($this->req['data']['pageSize'])?$this->req['data']['pageSize']:20;
        if(!empty($this->req['data']['toType'])){
            $returnMessage=\Our\RedisHelper::cachedFunction(\Redis\Db15\MessageRedisModel::getInstance(),array(&$this->messageService, 'getMemberList'),array($this->memberId,$this->req['data']['fromType'],$this->req['data']['toId'],$this->req['data']['toType'],'*',$pageIndex,$pageSize),3600,array($this->memberId));
        }else{
            $returnMessage=\Our\RedisHelper::cachedFunction(\Redis\Db15\MessageRedisModel::getInstance(),array(&$this->messageService, 'getList'),array($this->memberId,$pageIndex,$pageSize),1,array($this->memberId));
        }
        $push=  \Yaf\Registry::get('config')->get('push');
        $pushUrl=$push['clientHost'];
        $this->_view->assign("key",$this->req['data']['key']);
        $this->_view->assign('users',$returnMessage['list']);
        $this->_view->assign('memberId',$this->memberId);
        $this->_view->assign('pushUrl',$pushUrl);
        $this->_view->assign('totalCount',$returnMessage['totalCount']);
    }

    public function goodsDetailAction() {
        $goodsCommonId=(int)$this->getRequest()->getQuery()['goodsCommonId'];
        if($goodsCommonId > 0) {
            $commonGoodsInstance = \DAO\GoodsCommonModel::getInstance();
            $commonInfo = $commonGoodsInstance->getOneByIdCache($goodsCommonId);
        }
        $this->_view->assign('commonInfo',$commonInfo);
    }

}
