<?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;
        //是否店主
        $memberInfo['storeId'] ? $memberCenter['isSeller'] = 1 : $memberCenter['isSeller'] = 0;
        //是否销售员
        $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'];
        return $memberCenter;
    }
    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::waitEvaluate] = $orderDAO->getCount(array('order_state'=>ApiConst::orderStateComplete,'buyer_id'=>$memberId,'evaluation_state'=>ApiConst::waitEvaluation));
            //退款中数量
            $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);
        }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]);
            }
            if($memebrCenterDb1Redis->tableHExists($memberId,NameConst::goodsCollection) === false){
                $memberCenter[NameConst::goodsCollection] = \DAO\FavoritesModel::getInstance()->getFavoritesCountWithCommon(null, $memberId);
                $memebrCenterDb1Redis->tableHSet($memberId,NameConst::goodsCollection,$memberCenter[NameConst::goodsCollection]);
            }
            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]);
            }
            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]);
            }
            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]);
            }
            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]);
            }
            if($memebrCenterDb1Redis->tableHExists($memberId,NameConst::refund) === false){
                $memberCenter[NameConst::refund] = \DAO\Order\RefundReturnModel::getInstance()->getCount('refund_state != '.ApiConst::refundStateComplete.' AND buyer_id = '.$memberId);
            }
            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 = \Our\RedisHelper::cachedFunction(\Redis\Db6\FavoritesStoreRedisModel::getInstance(),array(&$favoritesInstance, 'getList'),array($where,$field,$pageIndex,$pageSize,$memberId),\Our\ApiConst::oneDaySecond,array($memberId));
        $stores = array();
        if(is_array($list) && !empty($list)){
            foreach ($list as $v){
                $v['evaluation_score'] ? $grade = number_format(($v['evaluation_score']/3/$v['evaluation_number']),1,'.',''):$grade = '5.0';
                $stores[] = array('favid'=>$v['favid'],'storeId'=>$v['store_id'],'storeLabel'=>\DAO\StoreModel::getInstance()->getStoreLabelSrc($v['store_label']),'storeName'=>$v['store_name'],'grade'=>$grade,'collectCount'=>$favoritesInstance->getFavoritesStoreCountByStoreId($v['store_id']));
            }
        }
        return array('stores'=>$stores,'totalCount'=>$totalCount);
    }

    /**
     * 删掉关注的店铺
     * @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),'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),'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),array('store_id'=>$ids,'member_id'=>$memberId));
                }

            }
        }
        if($return === false) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::commonError);
        }
        if(($return = (int)$return) > 0){
            //删除缓存
            foreach ($storeIds as $storeId) {
                //更新店铺收藏数
                $FavoritesStoreInstance->getFavoritesStoreCountByStoreId($storeId, -1);
            }
            if(is_array($ids) && count($ids) <= 20){
                foreach ($ids as $v){
                    \Our\RedisHelper::delCachedFunction(\Redis\Db6\FavoritesStoreRedisModel::getInstance(),array(&$FavoritesStoreInstance, 'getOne'),array('*',array('store_id'=>$v,'member_id'=>$memberId)),array($memberId));
                }
            }elseif (!is_array($ids)){
                \Our\RedisHelper::delCachedFunction(\Redis\Db6\FavoritesStoreRedisModel::getInstance(),array(&$FavoritesStoreInstance, 'getOne'),array('*',array('store_id'=>$ids,'member_id'=>$memberId)),array($memberId));
            }else{
                \Our\RedisHelper::delCachedFunction(\Redis\Db6\FavoritesStoreRedisModel::getInstance(),array(&$FavoritesStoreInstance, 'getOne'),array(),array($memberId));
            }
            \Our\RedisHelper::delCachedFunction(\Redis\Db6\FavoritesStoreRedisModel::getInstance(),array(&$FavoritesStoreInstance, 'getList'),array(),array($memberId));
            //更新个人中心首页数量
            \DAO\MemberModel::getInstance()->_changeNum(\Our\NameConst::storeCollection,$memberId,-$return);
            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)){
//            $storeIds = array_column($list,'store_id');
//            $storeIds = array_unique($storeIds);
//            foreach ($storeIds as $storeId) {
//                $tempStores = [];
//                $queryStores = [];
//                $storeDAO = \DAO\StoreModel::getInstance();
//                $exist = \Our\RedisHelper::cachedFunctionExist(\Redis\Db6\StoreRedisModel::getInstance(),array(&$storeDAO, 'getInfoById'),array($storeId),array($storeId));
//                if($exist) {
//                    $storeInfo = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(),array(&$storeDAO, 'getInfoById'),array($storeId),\Our\ApiConst::sevenDaySecond,array($storeId));
//                    $tempStores[] = $storeInfo;
//                }elseif ($exist === false) {
//                    $queryStores[] = $storeId;
//                }
//            }
//            if($queryStores) {
//                var_dump($queryStores);
//                $storeList = $storeDAO->getList('store_id in('.implode(',',$queryStores).')',\Our\ApiConst::zero,$pageSize);
//                if($storeList) {
//                    foreach ($storeList as $store) {
//                        \Our\RedisHelper::setCachedFunction(\Redis\Db6\StoreRedisModel::getInstance(),array(&$storeDAO, 'getInfoById'),$store,array($storeId),\Our\ApiConst::sevenDaySecond,array($storeId));
//                        $tempStores[] = $store;
//                    }
//                }
//            }
//            $stores = [];
//            foreach ($tempStores as $store) {
//                $stores[$store['store_id']] = [$store['store_state'],$store['open_flag']];
//            }
            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\ApiConst::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('goods_commonid'=>$v,'member_id'=>$memberId)),array($memberId));
                }
            }elseif (!is_array($ids)){
                \Our\RedisHelper::delCachedFunction(\Redis\Db4\FavoritesRedisModel::getInstance(),array(&$favoritesInstance, 'getOne'),array('*',array('goods_commonid'=>$ids,'member_id'=>$memberId)),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;
    }

}
