<?php

namespace Business\User;

use Our\ApiConst;
use Our\NameConst;
class MemberCenterServiceModel extends \Business\AbstractModel
{


    public function init() {

    }

    /**
     * 个人中心首页
     * @param $memberId
     * @return array
     * @throws \Our\Exception
     */
    public function index($memberId){
        $memberCenter = $this->getStatistics($memberId);
        $memberInfo = \DAO\MemberModel::getInstance()->getInfo($memberId);
        //用户名
        $memberCenter['memberName'] = $memberInfo['memberName'];
        //头像
        $memberCenter['memberAvatar'] = \DAO\MemberModel::getInstance()->getMemberAvatarUrl($memberId,$memberInfo['memberAvatar']);
        //是否配送员
        $memberInfo['diliverymanId'] ? $memberCenter['isDeliveryman'] = 1 : $memberCenter['isDeliveryman'] = 0;
        //是否店主
        $memberCenter['isSeller'] = 0;
        if($memberInfo['storeId']) {
            $store = \DAO\StoreModel::getInstance()->getStoreInfoCache($memberInfo['storeId']);
            $store['is_own_shop'] ? $memberCenter['isSeller'] = 0 : $memberCenter['isSeller'] = 1;
        }

        if(!empty($memberInfo['pushSet'])){
            $memberInfo['pushSet']=unserialize($memberInfo['pushSet']);
        }else{
            $memberInfo['pushSet']=array(
                'canPush'=>ApiConst::openMessae,
                'sound'=>ApiConst::openMessae,
                'vibrate'=>ApiConst::openMessae,
            );
        }
        //是否销售员
        $saleInstance = \DAO\SaleModel::getInstance();
        //$sale_act_id = \DAO\SaleModel::getInstance()->getOne(array('member_id'=>$memberId,'is_closing'=>0),'sale_act_id');
        //$sale_act = \Our\RedisHelper::cachedFunction(\Redis\Db1\SaleRedisModel::getInstance(),array(&$saleInstance, 'getOne'),array(array('member_id'=>$memberId,'is_closing'=>0),'sale_act_id'),0,array($memberId));
        $sale_act = $saleInstance->getOneByMIdCache($memberId);
        $sale_act ? $memberCenter['isSalesman'] = 1 : $memberCenter['isSalesman'] = 0;
        $memberCenter['memberMobile'] = \DAO\MemberModel::getInstance()->getInfo($memberId)['memberMobile'];
        $memberCenter['canSendMsg']= (int)$memberInfo['pushSet']['canPush'];
        $memberCenter['sound']= (int)$memberInfo['pushSet']['sound'];
        $memberCenter['vibrate']=(int)$memberInfo['pushSet']['vibrate'];
        return $memberCenter;
    }

    public function getMessageSet($memberId){
        $memberInfo = \DAO\MemberModel::getInstance()->getInfo($memberId);
        // $pushSet=array();
        if(!empty($memberInfo['pushSet'])){
            $pushSet=unserialize($memberInfo['pushSet']);
            $pushSet=array(
                'canPush'=>(int)$pushSet['canPush'],
                'sound'=>(int)$pushSet['sound'],
                'vibrate'=>(int)$pushSet['vibrate'],
                'timeDiff'=>$pushSet['timeDiff'],
            );
        }else{
            $pushSet=array(
                'canPush'=>ApiConst::openMessae,
                'sound'=>ApiConst::openMessae,
                'vibrate'=>ApiConst::openMessae,
                'timeDiff'=>'',
            );
        }
        return $pushSet;
    }
    public function getStatistics($memberId){
        $memebrCenterDb1Redis = \Redis\Db1\MemberCenterRedisModel::getInstance();
        $memberCenter = $memebrCenterDb1Redis->tableHGAll($memberId);
        if(!$memberCenter){
            $memberCenter = array();
            $orderDAO = \DAO\Order\OrderModel::getInstance();
            //待付款数量
            $memberCenter[NameConst::waitPay] = $orderDAO->getCount(array('order_state'=>ApiConst::orderStateWaitPay,'buyer_id'=>$memberId));
            //待发货数量
            $memberCenter[NameConst::waitShipments] = $orderDAO->getCount(array('order_state'=>ApiConst::orderStateWaitSend,'buyer_id'=>$memberId));
            //待收货数量
            $memberCenter[NameConst::waitReceiving] = $orderDAO->getCount(array('order_state'=>ApiConst::orderStateWaitRecieve,'buyer_id'=>$memberId));
            //待自提数量
            $memberCenter[NameConst::waitSelfLifting] = $orderDAO->getCount(array('order_state'=>ApiConst::orderStateComplete,'buyer_id'=>$memberId,'evaluation_state'=>ApiConst::waitEvaluation));
            //待评价数量
            $memberCenter[NameConst::waitEvaluate] = $orderDAO->getCount(array('order_state'=>ApiConst::orderStateWaitRecieve,'buyer_id'=>$memberId,'shipping_type'=>ApiConst::bySelf));
            //退款中数量
            $memberCenter[NameConst::refund] = \DAO\Order\RefundReturnModel::getInstance()->getCount('refund_state != '.ApiConst::refundStateComplete.' AND buyer_id = '.$memberId);
            //店铺收藏数量
            $memberCenter[NameConst::storeCollection] = \DAO\FavoritesStoreModel::getInstance()->getFavoritesStoreCount(array('member_id'=>$memberId,'fav_type'=>1));
            //商品收藏数量
            $memberCenter[NameConst::goodsCollection] = \DAO\FavoritesModel::getInstance()->getFavoritesCountWithCommon(null, $memberId);
            //足迹数量
            $memberCenter[NameConst::footprint] = \DAO\GoodsBrowseModel::getInstance()->getBrowseCount(array('member_id'=>$memberId));
            $memebrCenterDb1Redis->tableHMSet($memberId,$memberCenter,\Our\ApiConst::sevenDaySecond);
        }else{
            if($memebrCenterDb1Redis->tableHExists($memberId,NameConst::footprint) === false){
                $memberCenter[NameConst::footprint] = \DAO\GoodsBrowseModel::getInstance()->getBrowseCount(array('member_id'=>$memberId));
                $memebrCenterDb1Redis->tableHSet($memberId,NameConst::footprint,$memberCenter[NameConst::footprint],\Our\ApiConst::sevenDaySecond);
            }
            if($memebrCenterDb1Redis->tableHExists($memberId,NameConst::goodsCollection) === false){
                $memberCenter[NameConst::goodsCollection] = \DAO\FavoritesModel::getInstance()->getFavoritesCountWithCommon(null, $memberId);
                $memebrCenterDb1Redis->tableHSet($memberId,NameConst::goodsCollection,$memberCenter[NameConst::goodsCollection],\Our\ApiConst::sevenDaySecond);
            }
            if($memebrCenterDb1Redis->tableHExists($memberId,NameConst::waitPay) === false){
                $memberCenter[NameConst::waitPay] = \DAO\Order\OrderModel::getInstance()->getCount(array('order_state'=>ApiConst::orderStateWaitPay,'buyer_id'=>$memberId));
                $memebrCenterDb1Redis->tableHSet($memberId,NameConst::waitPay,$memberCenter[NameConst::waitPay],\Our\ApiConst::sevenDaySecond);
            }
            if($memebrCenterDb1Redis->tableHExists($memberId,NameConst::waitShipments) === false){
                $memberCenter[NameConst::waitShipments] = \DAO\Order\OrderModel::getInstance()->getCount(array('order_state'=>ApiConst::orderStateWaitSend,'buyer_id'=>$memberId));
                $memebrCenterDb1Redis->tableHSet($memberId,NameConst::waitShipments,$memberCenter[NameConst::waitShipments],\Our\ApiConst::sevenDaySecond);
            }
            if($memebrCenterDb1Redis->tableHExists($memberId,NameConst::waitReceiving) === false){
                $memberCenter[NameConst::waitReceiving] = \DAO\Order\OrderModel::getInstance()->getCount(array('order_state'=>ApiConst::orderStateWaitRecieve,'buyer_id'=>$memberId));
                $memebrCenterDb1Redis->tableHSet($memberId,NameConst::waitReceiving,$memberCenter[NameConst::waitReceiving],\Our\ApiConst::sevenDaySecond);
            }
            if($memebrCenterDb1Redis->tableHExists($memberId,NameConst::waitSelfLifting) === false){
                $memberCenter[NameConst::waitSelfLifting] = \DAO\Order\OrderModel::getInstance()->getCount(array('order_state'=>ApiConst::orderStateComplete,'buyer_id'=>$memberId,'evaluation_state'=>ApiConst::waitEvaluation));
                $memebrCenterDb1Redis->tableHSet($memberId,NameConst::waitSelfLifting,$memberCenter[NameConst::waitSelfLifting],\Our\ApiConst::sevenDaySecond);
            }
            if($memebrCenterDb1Redis->tableHExists($memberId,NameConst::waitEvaluate) === false){
                $memberCenter[NameConst::waitEvaluate] = \DAO\Order\OrderModel::getInstance()->getCount(array('order_state'=>ApiConst::orderStateComplete,'buyer_id'=>$memberId,'evaluation_state'=>ApiConst::waitEvaluation));
                $memebrCenterDb1Redis->tableHSet($memberId,NameConst::waitEvaluate,$memberCenter[NameConst::waitEvaluate],\Our\ApiConst::sevenDaySecond);
            }
            if($memebrCenterDb1Redis->tableHExists($memberId,NameConst::refund) === false){
                $memberCenter[NameConst::refund] = \DAO\Order\RefundReturnModel::getInstance()->getCount('refund_state != '.ApiConst::refundStateComplete.' AND buyer_id = '.$memberId);
                $memebrCenterDb1Redis->tableHSet($memberId,NameConst::refund,$memberCenter[NameConst::refund],\Our\ApiConst::sevenDaySecond);
            }
            foreach ($memberCenter as &$v){
                $v = (int)$v;
            }
        }
        return $memberCenter;
    }

    /**
     * 关注的店铺列表
     * @param $param
     * @param $memberId
     * @return array
     * @throws \Exception
     * @throws \Our\Exception
     */
    public function getStores($param,$memberId){
//        $pageSize = intval($param['pageSize']);
//        $pageIndex = intval($param['pageIndex']);
//        if($pageSize === 0){
//            \Error\ErrorModel::throwException(\Error\CodeConfigModel::commonError);
//        }
//        $pageIndex=$pageIndex+\Our\ApiConst::one;
//        $keyword = trim($param['keyword']);

//        $memberCenter = $this->getStatistics($memberId);
//        $totalCount = (int)$memberCenter['storeCollection'];
//
//        $field = 'evaluation_score,evaluation_number,han_store_score_statistics.store_collect,store_name,store_label,han_store.store_id,favid';
//        $param['keyword'] && $where = "store_name like '%{$param['keyword']}%'";
        //$list = \DAO\FavoritesStoreModel::getInstance()->getList($where,$field,$pageIndex,$pageSize,$memberId);
        $favoritesInstance = \DAO\FavoritesStoreModel::getInstance();

        $list = $favoritesInstance->getFavoritesStores(array('member_id'=>$memberId,'fav_type'=>1),'fav_from,store_id,favid');
        $brandsAround = [];
        $concernedShops = [];
        $stores = [];
        if($list) {
            $storeIds = array_column($list,'store_id');
            $storeIds = implode(',',$storeIds);
            $where =\Our\Common::format(" store_id in({0})",$storeIds);
            $storeScores = \DAO\StoreScoreStatisticsModel::getInstance()->getStoreScoreStatistics($where,'store_id,evaluation_score,evaluation_number');
            $list = \Our\Common::intergrateOneToOne($list, $storeScores, 'store_id', 'store_id');
            $stores = \DAO\StoreModel::getInstance()->getStores($where,'store_id,store_label,store_name');
            $list = \Our\Common::intergrateOneToOne($list, $stores, 'store_id', 'store_id');
            foreach ($list as $v) {
                $grade = isset($v['evaluation_score']) ? number_format(($v['evaluation_score']/3/$v['evaluation_number']),1,'.',''):'5.0';
                $tempStore = array('favId'=>$v['favid'],'storeId'=>$v['store_id'],'storeLabel'=>\DAO\StoreModel::getInstance()->getStoreLabelSrc($v['store_label'],\Our\ImageConst::storeCollectionImg),'storeName'=>$v['store_name'],'grade'=>$grade,'collectCount'=>$favoritesInstance->getFavoritesStoreCountByStoreId($v['store_id']));
                if($v['fav_from'] == 1) {
                    $concernedShops[] = $tempStore;
                }elseif($v['fav_from'] == 3){
                    $brandsAround[] = $tempStore;
                }
                $stores[] = $tempStore;
            }
        }
        return array('concernedShop'=>$concernedShops,'brandsAround'=>$brandsAround,'stores'=>$stores,'totalCount'=>count($stores));
    }

    /**
     * 删掉关注的店铺
     * @param $param
     * @param $memberId
     * @return bool
     * @throws \Our\Exception
     */
    public function delStores($param,$memberId){
        $ids = $param['ids'];
        if(!$ids){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::cancleCollectionStore);
        }
        $FavoritesStoreInstance = \DAO\FavoritesStoreModel::getInstance();
        $storeIds = array();
        if(is_array($ids)){
            $ids = array_map(function($v){
                return intval($v);
            },$ids);
            $list = $FavoritesStoreInstance->selectList(array('store_id'=>array('in',$ids),'member_id'=>$memberId,'fav_type'=>1),'store_id');
            if($list) {
                $storeIds = array_column($list, 'store_id');
                $return = $FavoritesStoreInstance->update(array('fav_type'=>0,'fav_from'=>0),'store_id in ('.implode(',',$ids).')',true,$memberId);
            }
        }else{
            if(strpos($ids,']') !== false ) {
                $ids = json_decode($ids, true);
                $list = $FavoritesStoreInstance->selectList(array('store_id'=>array('in',$ids),'member_id'=>$memberId,'fav_type'=>1),'store_id');
                if($list) {
                    $storeIds = array_column($list, 'store_id');
                    $return = $FavoritesStoreInstance->update(array('fav_type'=>0,'fav_from'=>0),'store_id in ('.implode(',',$ids).')',true,$memberId);
                }
            }else{
                $ids = intval($ids);
                $one = $FavoritesStoreInstance->getOne('store_id',array('store_id'=>$ids,'member_id'=>$memberId,'fav_type'=>1));
                if($one) {
                    $storeIds = array($one['store_id']);
                    $return = $FavoritesStoreInstance->update(array('fav_type'=>0,'fav_from'=>0),array('store_id'=>$ids,'member_id'=>$memberId));
                }

            }
        }
        if($return === false) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::commonError);
        }
        $FavoritesStoreInstance->updateStoreCollecitonsCache($storeIds, $memberId);
        return true;
    }

    /**
     * 关注的商品列表
     * @param $param
     * @param $memberId
     * @return array
     * @throws \Exception
     * @throws \Our\Exception
     */
    public function getGoods($param,$memberId){
        $pageSize = intval($param['pageSize']);
        $pageIndex = intval($param['pageIndex']);
        if($pageSize === 0){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::commonError);
        }
        $pageIndex=$pageIndex+\Our\ApiConst::one;
        $keyword = trim($param['keyword']);


        $totalCount = 0;
        $field = 'han_goods_common.goods_commonid,han_goods_common.goods_id,han_goods_common.store_id,goods_name,goods_price,goods_image,favid';
        $param['keyword'] && $where = "goods_name like '%{$param['keyword']}%'";

        //$list = \DAO\FavoritesStoreModel::getInstance()->getList($where,$field,$pageIndex,$pageSize,$memberId);
        $favoritesInstance = \DAO\FavoritesModel::getInstance();
        $list = \Our\RedisHelper::cachedFunction(\Redis\Db4\FavoritesRedisModel::getInstance(),array(&$favoritesInstance, 'getList'),array($where,$field,$pageIndex,$pageSize,$memberId),\Our\ApiConst::oneDaySecond,array($memberId));
        $goods = array();
        if(is_array($list) && !empty($list)){
            foreach ($list as $v){
                //if($stores['store_id'] && $stores['store_id']['open_flag'] == 1 && $stores['store_id']['store_state'] == 1) {
                $goods[] = array('favid'=>$v['favid'],'goodsCommonId'=>$v['goods_commonid'],'goodsImage'=>\Our\ImageUtil::getGoodsImgUrl($v['goods_image'],\Our\ImageConst::goodsCollectionImgSize),'goodsName'=>$v['goods_name'],'goodsPrice'=>$v['goods_price'],'goodsId'=>$v['goods_id']);
                // }
            }
            if($where) {
                $totalCount = $favoritesInstance->getFavoritesCountWithCommon($where, $memberId);
            }else{
                $memberCenter = $this->getStatistics($memberId);
                $totalCount = (int)$memberCenter['goodsCollection'];
            }

        }
        return array('goods'=>$goods,'totalCount'=>$totalCount);
    }

    /**
     * 删掉关注的商品
     * @param $param
     * @param $memberId
     * @return bool
     * @throws \Our\Exception
     */
    public function delgoods($param,$memberId){
        $ids = $param['ids'];
        if(!$ids){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::cancleCollectionGoods);
        }
        $favoritesInstance = \DAO\FavoritesModel::getInstance();
        if(is_array($ids)){
            $ids = array_map(function($v){
                return intval($v);
            },$ids);
            $return = $favoritesInstance->update(array('isdel'=>1),'goods_commonid in ('.implode(',',$ids).')',true,$memberId);
        }else{
            if(strpos($ids,']') !== false ) {
                $ids = json_decode($ids, true);
                $return = $favoritesInstance->update(array('isdel'=>1),'goods_commonid in ('.implode(',',$ids).')',true,$memberId);
            }else{
                $ids = intval($ids);
                $return = $favoritesInstance->update(array('isdel'=>1),array('goods_commonid'=>$ids,'member_id'=>$memberId));
            }

        }
        if($return === false) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::commonError);
        }
        if(($return = (int)$return) > 0){
            //删除缓存
            if(is_array($ids) && count($ids) <= 20){
                foreach ($ids as $v){
                    \Our\RedisHelper::delCachedFunction(\Redis\Db4\FavoritesRedisModel::getInstance(),array(&$favoritesInstance, 'getOne'),array('*',array('member_id'=>$memberId,'goods_commonid'=>$v)),array($memberId));
                }
            }elseif (!is_array($ids)){
                \Our\RedisHelper::delCachedFunction(\Redis\Db4\FavoritesRedisModel::getInstance(),array(&$favoritesInstance, 'getOne'),array('*',array('member_id'=>$memberId,'goods_commonid'=>$ids)),array($memberId));
            }else{
                \Our\RedisHelper::delCachedFunction(\Redis\Db4\FavoritesRedisModel::getInstance(),array(&$favoritesInstance, 'getOne'),array(),array($memberId));
            }
            \Our\RedisHelper::delCachedFunction(\Redis\Db4\FavoritesRedisModel::getInstance(),array(&$favoritesInstance, 'getList'),array(),array($memberId));
            //更新个人中心首页数量
            \DAO\MemberModel::getInstance()->_changeNum(\Our\NameConst::goodsCollection,$memberId,-$return);
            return true;
        }

    }
    private static $_instance = null;

    /**
     * 单例模式获取类实例
     *
     */
    public static function getInstance() {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

}
