<?php

namespace Business\User;

use DAO\MbUserTokenModel;
use DAO\MemberModel;
use Error\CodeConfigModel;
use Error\ErrorModel;
use Our\ApiConst;
use Our\Common;
use Our\CommonExtension;
use Our\DbNameConst;
use Our\ImageConst;
use Our\ImageUtil;
use Our\NameConst;
use Our\PathConst;


/**
 * 用户登录业务
 */
class ShareServiceModel extends \Business\AbstractModel
{

    private $memberDao;
    private $memberDb0Redis;
    private $sessionDb0Redis;
    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub

    }

    public function getSaveData($data){
        $driverType = \Our\Common::getDriverType();
        $data['driverType'] = $driverType;
        if($data['type']==ApiConst::shareGoods){
            if(!empty($data['id'])){
                $goodsDao=\DAO\GoodsModel::getInstance();
                $goods=$goodsDao->getOnlineOne($data['id']);
                $data['goodsId']=$goods['goods_id'];
                $data['goodsCommonid']=$goods['goods_commonid'];
                $data['storeId']=$goods['store_id'];

            }
        }
        if($data['type']==ApiConst::shareGroup){
            if(!empty($data['id'])){
                $pBundlingDao=\DAO\PBundlingModel::getInstance();
                $pBundling=$pBundlingDao->findById($data['groupId']);
                $data['groupId']=$data['groupId'];
                $data['storeId']=$pBundling['store_id'];
            }
        }
        $data['qrCode']=$this->growQrcode($data);
        if($data['type']==ApiConst::shareStore || $data['type']== ApiConst::shareSaler){
            if(!empty($data['id'])){
                $storeDao=\DAO\StoreModel::getInstance(DbNameConst::salveDBConnectName);
                $store=$storeDao->getStoreInfoCache($data['id']);
                $data['address']=$store['store_address'];
                $data['imgUrl']=$storeDao->getStoreBanner($store['store_index_banner']);
                $data['storeName']=$store['store_name'];
                $data['desc']=$store['store_notice'];
                $data['storeWorkingtime']=$store['store_workingtime'];
                $data['buyerDistribution']=$store['buyer_distribution'];
                $data['sellerDistribution']=$store['seller_distribution'];
                $data['startShippingPrice']=$store['start_shipping_price'];
                $data['freeShippingPrice']=$store['free_shipping_price'];
                $data['storeStartTime']=$store['store_start_time'];
                $data['storeCloseTime']=$store['store_close_time'];
            }

        }


       // $data['qrCode']=\Our\RedisHelper::cachedFunction(\Redis\Db0\MemberRedisModel::getInstance(), array(&$this, 'growQrcode'), array($data));
        return $data;

    }
    public function saveDataToSession($data){
        $this->memberDb0Redis=\Redis\Db0\MemberRedisModel::getInstance();
        $res= $this->memberDb0Redis->tableCacheSet($data['key'],json_encode($data),ApiConst::oneDaySecond);
        return $res;
    }
    //二进制转图片image/png
    public function dataUri($contents, $mime)
    {
        $base64   = base64_encode($contents);
        return ('data:' . $mime . ';base64,' . $base64);
    }
    public function getQrcode($page,$scene){
        $wechatCommon= \Our\WechatCommon::getInstance();
        $accessToken=$wechatCommon->getAccessToken();
        $scene= $scene;
        $page=$page;
        $url=\Our\Common::format(\Our\PathConst::getWxQrCode,$accessToken);
        $res=$wechatCommon->httpsPostJson($url,array(
            'scene'=>$scene,
            'page'=>$page
        ));
        return $res;
    }
    public function getQrUrl($data,$type='store'){
        if($type=='store'){
            return Common::format(PathConst::shareStore,$data['id']);
        }
        if($type=='goods'){
            return Common::format(PathConst::shareGoods,$data['goodsId'],$data['goodsCommonid'],$data['storeId']);
        }
        if($type=='group'){
            return Common::format(PathConst::shareGroups,$data['groupId'],$data['storeId']);
        }

        if($type='smallPrograme'){
            $host=\Bootstrap::getUrlIniConfig('resourcesHost');
            $url=Common::format($host."/index/getQrcodeFlow?imageKey={0}",$data);
            return $url;
        }

    }

    public function growQrcode($data){
        $this->memberDb0Redis=\Redis\Db0\MemberRedisModel::getInstance();
        if($data['type']==\Our\ApiConst::shareStore){
            if($data['shareType']==ApiConst::shareWxFriend || $data['shareType']==ApiConst::shareWxFriends){
                if(\Our\ApiConst::isWxPublish){
                    $scene= \Our\Common::format(\Our\PathConst::wxStoreParams,$data['id']);
                    $page=\Our\PathConst::wxStorePath;
                    $res=$this->getQrcode($page,$scene);
                    if(Common::isJson($res)){
                            $res=json_decode($res,true);
                           if($res['errcode']==ApiConst::shareLimitProgrameError){
                            $memberRedis = \Redis\Db0\MemberRedisModel::getInstance();
                            $memberRedis->tableDel('wechatAccessToken');
                            $res=$this->getQrcode($page,$scene);
                        }
                    }
                    $fileName=md5($res);
                    //$fileName=$fileName.NameConst::jpgSuffix;
                   // $base64image=$this->dataUri($res,ImageConst::imagePgn);
                  //  $url= ImageUtil::uploadBase64Image($base64image,ImageConst::shareImage,$fileName);
                    $this->memberDb0Redis->tableCacheSet($fileName,$res,ApiConst::oneDaySecond);
                    $qrcodeUrl=$this->getQrUrl($fileName,'smallPrograme');
                    return $qrcodeUrl;
                }else{
                   return $this->getQrUrl($data);
                   // return PathConst::wxDefaultPath;
                }
            }else{
                return $this->getQrUrl($data);
                //不是微信分享就是普通下载的二维码图片
                //return PathConst::downLoadQrcode;
            }
        }
        if($data['type']==\Our\ApiConst::shareGoods){
            if(($data['shareType']==ApiConst::shareWxFriend || $data['shareType']==ApiConst::shareWxFriends)){
                    if(\Our\ApiConst::isWxPublish){
                        //$scene= \Our\Common::format(\Our\PathConst::wxGoodsParams,$data['id']);
                          $scene= \Our\Common::format(\Our\PathConst::wxGoodsParams,$data['goodsCommonid']);
                        $page=\Our\PathConst::wxGoodsPath;
                        $res=$this->getQrcode($page,$scene);
                        if(Common::isJson($res)){
                            $res=json_decode($res,true);
                            if($res['errcode']==ApiConst::shareLimitProgrameError){
                                $memberRedis = \Redis\Db0\MemberRedisModel::getInstance();
                                $memberRedis->tableDel('wechatAccessToken');
                                $res=$this->getQrcode($page,$scene);
                            }
                        }
                       // var_dump($res);exit;
//                        header('Content-type: image/jpg');
//                        echo $res;exit;
                        $fileName=md5($res);
                        //$fileName=$fileName.NameConst::jpgSuffix;
                        // $base64image=$this->dataUri($res,ImageConst::imagePgn);
                        //  $url= ImageUtil::uploadBase64Image($base64image,ImageConst::shareImage,$fileName);
                        $this->memberDb0Redis->tableCacheSet($fileName,$res,ApiConst::oneDaySecond);
                        $qrcodeUrl=$this->getQrUrl($fileName,'smallPrograme');
                        return $qrcodeUrl;
                    }else{
                        return $this->getQrUrl($data,'goods');
                        //return PathConst::wxDefaultPath;
                    }
            }else{
                //不是微信分享就是普通下载的二维码图片
                 return $this->getQrUrl($data,'goods');
                //return PathConst::downLoadQrcode;
            }
        }
        if($data['type']==\Our\ApiConst::shareGroup){
            if(($data['shareType']==ApiConst::shareWxFriend || $data['shareType']==ApiConst::shareWxFriends)){
                if(\Our\ApiConst::isWxPublish){
                    $scene= \Our\Common::format(\Our\PathConst::wxGoodsParams,$data['id']);
                    $page=\Our\PathConst::wxGoodsPath;
                    $res=$this->getQrcode($page,$scene);
                    $fileName=md5($page.$res);
                    $fileName=$fileName.NameConst::jpgSuffix;
                    $base64image=$this->dataUri($res,ImageConst::imagePgn);
                    $url= ImageUtil::uploadBase64Image($base64image,ImageConst::shareImage,$fileName);
                    $this->memberDb0Redis->tableCacheSet($fileName,$url,ApiConst::zero);
                    return $url;
                }else{
                    return $this->getQrUrl($data,'group');
                    //return PathConst::wxDefaultPath;
                }
            }else{
                //不是微信分享就是普通下载的二维码图片
                return $this->getQrUrl($data,'group');
                //return PathConst::downLoadQrcode;
            }
        }
        if($data['type']==\Our\ApiConst::sharePlat){
            return PathConst::sharePlat;
        }
        if($data['type']==\Our\ApiConst::shareSaler){
            return $data['qrCode'];
        }
    }
    public function excuteCommand($key){
        $command=\Bootstrap::getUrlIniConfig("convert");
        $domain=\Bootstrap::getUrlIniConfig("resourcesHost");
        $converSource=$domain.\Our\PathConst::getHtml;
        $params=$key.PathConst::cutVertical.TIMESTAMP;
        $params=base64_encode($params);
        $convertUrl=$converSource.PathConst::params.'key='.$params;
        $savePath=\Our\PathConst::shareSavePath;
        $saveImageName=ImageUtil::getFileName().\Our\NameConst::jpgSuffix;
        $saveFile=$savePath.$saveImageName;
        $shell = \Our\Common::format("{0} --crop-w 750 --width 750 {1} {2}",$command,$convertUrl,$saveFile);
        system($shell, $status);
        if( $status ){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::shareGrowImageError);
        } else {
            $returnData['shareImage']=\Our\ImageUtil::uploadImage($saveFile,\Our\ImageConst::shareImage,$saveImageName);
           return $returnData;
        }
    }
    private static $_instance = null;

    /**
     * 获取类实例
     *
     * @return \DAO\UserModel
     */
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
   }
