<?php

namespace Business\Store;

use DAO\StoreModel;
use DAO\MemberModel;
use DAO\StoreStatisticsModel;
use Error\CodeConfigModel;
use Error\ErrorModel;
use Our\ApiConst;
use Our\Common;
use Our\DbNameConst;
use Our\ImageConst;
use Our\PageConst;
use Our\PathConst;


/**
 * 店主service
 *
 * @date 2018-5-11
 * @author csw
 */
class ShopkeeperServiceModel extends \Business\AbstractModel
{

    private $storeDao;
    private $storeStatisticsDao;
    //统计我是店主任务脚本属性
    private $lastOrderId;
    private $lastFavId;
    private $taskIndex;
    private $taskSize;

    public function init()
    {
        $this->storeDao = StoreModel::getInstance();
    }

    private $orderListField = 'han_order.order_id as orderId,han_order.order_sn as orderSn,han_order.store_name as storeName,han_order.add_time as addTime,han_order.store_id as storeId,han_order.goods_amount as goodsAmount,han_order.shipping_fee as shippingFee,han_order.order_amount as orderAmount,han_order.shipping_type as shippingType,han_order.payment_type as paymentType,han_order.order_state as orderState,han_order.shipping_fee as shippingFee,han_order.refund_state as refundState,han_order.order_type as orderType,han_order.is_receive_payment as isReceivePayment,han_order_common.order_message as orderMessage';
    private $orderGoodsField = "commis_rate as commisRate,goods_type as goodsType,order_id as orderId,rec_id as recId,goods_id as goodsId,goods_name as goodsName,goods_price as goodsPrice,goods_num as goodsNum,goods_image as goodsImage,goods_pay_price as goodsPayPrice,sale_act_id as saleActId,sale_id as saleId,comment_state as commentState,is_refund as isRefund,goods_spec as goodsSpec,goods_group as goodsGroup";
    private $storeField = "offline_payway as offlinePayway";

    //获得统计数据
    public function getStatistics($memberId)
    {
        $storeId = $this->_getStoreByMemberId($memberId);

        $storeStatisticsDayDao = \DAO\Store\StoreStatisticsDayModel::getInstance();
        $storeStatisticsDao = \DAO\StoreStatisticsModel::getInstance();
        $condition['store_id'] = $storeId;
        //获取店铺信息
        $store = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$this->storeDao, 'getInfo'), array($condition), ApiConst::tenDaySecond, array($storeId));
        //获取店铺数据统计
        $storeStats = $storeStatisticsDao->find($condition);
        //获取店铺今日销售额和订单量
        $storeTodayStats = $storeStatisticsDayDao->getById($storeId);
        $data['storeId'] = $store['store_id'];
        $data['storeName'] = $store['store_name'];
        $data['storeLabel'] = $store['store_label'];
        $data['goodsCount'] = isset($storeStats['goodsCount']) ? $storeStats['goodsCount'] : ApiConst::zero;
        $data['orderCount'] = isset($storeStats['orderCount']) ? $storeStats['orderCount'] : ApiConst::zero;
        $data['orderTotal'] = isset($storeStats['orderTotal']) ? $storeStats['orderTotal'] : ApiConst::zero;
        $data['favCount'] = isset($storeStats['favCount']) ? $storeStats['favCount'] : ApiConst::zero;
        $data['todayOrderCount'] = isset($storeTodayStats['orderCount']) ? $storeTodayStats['orderCount'] : ApiConst::zero;
        $data['todayOrderTotal'] = isset($storeTodayStats['orderTotal']) ? $storeTodayStats['orderTotal'] : ApiConst::zero;
        $data['tadayFavCount'] = isset($storeTodayStats['favCount']) ? $storeTodayStats['favCount'] : ApiConst::zero;
        return $data;
    }


    public function getSalaList($storeId)
    {
        $condition['store_id'] = $storeId;
        $storeClassSaleStatistics = \DAO\StoreClassSaleStatisticsModel::getInstance();
        $result = $storeClassSaleStatistics->getStoreClassStats($condition);
        if (is_array($result) && !empty($result)) {
            foreach ($result as $k => &$v) {
                $v['src'] = \Our\Common::getStaticFile($v['gc_id'] . '.jpg', ImageConst::defaultPath . ImageConst::categoryPicPrefix);
                $storeClassStats[$k]['gcName'] = $v['gc_name'];
                $storeClassStats[$k]['gcImage'] = $v['src'];
                $storeClassStats[$k]['rank'] = $v['rank'];
                $storeClassStats[$k]['gcId'] = $v['gc_id'];
            }
            return $storeClassStats;
        } else {
            return array();
        }
    }

    /**
     * 我是店主-店主基本信息
     * @param $key
     * @return array
     */
    public function getShopkeeper($memberId)
    {
        $data = $this->getStatistics($memberId);
        $data['storeClassStats'] = $this->getSalaList($data['storeId']);
        return $data;
    }

    /**
     * 获取店铺特定分类店铺排行，及特定分类排行第一页数据
     * @param $key
     * @return array
     */
    public function getMyStoreClassRank($memberId, $gcId, $pageIndex, $pageSize)
    {
        $storeId = $this->_getStoreByMemberId($memberId);
        $statsDao = \DAO\StoreClassSaleStatisticsModel::getInstance();
        $storeStats = $this->getStoreClassRankList($gcId, $pageIndex, $pageSize);
        $myStoreStats = $statsDao->find(array('store_id' => $storeId));
        $data['myStoreRank'] = $myStoreStats['rank'];
        $data['storeStats'] = $storeStats['storeStats'];
        return $data;
    }

    /**
     * 我是店主-获取店铺
     * @param $key
     * @return array
     */
    public function getStoreClassRankList($gcId, $pageIndex, $pageSize)
    {
        $storeClassSaleStatisticsDao = \DAO\StoreClassSaleStatisticsModel::getInstance();
        $storeDao = \DAO\StoreModel::getInstance();
        $list = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$storeClassSaleStatisticsDao, 'getListByGcId'), array($gcId, '*', $pageIndex, $pageSize), ApiConst::tenDaySecond);
        foreach ($list as $k => $v) {
            $storeStats[$k]['storeId'] = $v['store_id'];
            $storeStats[$k]['storeName'] = $v['store_name'];
            $storeStats[$k]['storeLabel'] = $storeDao->getStoreLabelSrc($v['store_label']);
            $storeStats[$k]['rank'] = $v['rank'];
        }
        $data['storeStats'] = $storeStats;
        return $data;
    }


    /**
     * 获取店铺会员统计及列表
     * @param $memberId
     * @param $pageIndex
     * @param $pageSize
     * @return array
     */
    public function getStoreMemberStats($memberId, $pageIndex, $pageSize, $sort, $keyword)
    {
        $storeId = $this->_getStoreByMemberId($memberId);
        $memberFavoritesStoreStoreMemberStaticsDao = \DAO\Store\MemberFavoritesStoreStoreMemberStatisticsModel::getInstance(DbNameConst::salveDBConnectName);
        $memberDao = \DAO\MemberModel::getInstance();
        $sort = $memberFavoritesStoreStoreMemberStaticsDao->getSortBySortType($sort);
        $memberStats = $memberFavoritesStoreStoreMemberStaticsDao->getList($storeId, $pageIndex, $pageSize, $sort, $keyword);
        if (!empty($memberStats['list'])) {
            $memberStats['list'] = $memberDao->getListMemberUrl($memberStats['list']);
        }

        if ($pageIndex == ApiConst::pageIndex) {
            $storeStats = $this->getStatistics($memberId);
            $data['tadayFavCount'] = $storeStats['tadayFavCount'];
            $data['favCount'] = $storeStats['favCount'];
        }
        if ($memberStats['list']) {
            $data['memberStats'] = $memberStats;
        } else {
            $data['memberStats'] = new \stdClass();
        }
        return $data;
    }

    /**
     * 获取店铺会员统计及列表
     * @param $memberId
     * @param $pageIndex
     * @param $pageSize
     * @return array
     */
    public function getMemberStats($memberId, $pageIndex, $pageSize, $sort, $keyword)
    {
        $storeId = $this->_getStoreByMemberId($memberId);
        $storeMemberStatistics = \DAO\StoreMemberStatisticsModel::getInstance();
        switch ($sort) {
            case 1:
                $order = 'fav_time';
                $sort = 'desc';
                break;
            case 2:
                $order = 'fav_time';
                $sort = 'asc';
                break;
            case 3:
                $order = 'order_total';
                $sort = 'desc';
                break;
            case 4:
                $order = 'order_total';
                $sort = 'asc';
                break;
        }
        $result = $storeMemberStatistics->getListByStoreId($storeId, '*', $pageIndex, $pageSize, $keyword, $order, $sort);
        $data['memberStats'] = \Our\Common::convertUnderline($result);
        return $data;
    }

    /**
     * 更新店铺会员统计
     */
    public function updateMemberStats($memberId)
    {
        $storeId = $this->_getStoreByMemberId($memberId);
    }

    /**
     * 接单
     * @param $memberId
     * @param $orderId
     * @return bool
     */
    public function orderReceive($memberId, $orderId)
    {
        $storeId = $this->_getStoreByMemberId($memberId);
        $where['order_id'] = $orderId;
        $where['store_id'] = $storeId;
        $where['order_state'] = ApiConst::orderStateWaitConfirm;
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $order = $orderDao->find($where);
        if (empty($order)) {
            if (empty($storeId)) {
                ErrorModel::throwException(CodeConfigModel::orderNotExist);
            }
        } else {
            $update_data['order_state'] = ApiConst::orderStateWaitSend;
            $result = $orderDao->update($where, $update_data);
            $orderDao->deleteOrderCache($order['buyer_id'], $orderId);
            \Our\RedisHelper::memberTotalFromStateToState($order['buyer_id'], $order['order_state'], ApiConst::orderStateWaitSend);
            return $result;
        }
    }

    public function getStoreOrders($memberId, $pageIndex, $pageSize, $orderState, $keyword)
    {
        $storeId = $this->_getStoreByMemberId($memberId);
        $storeStatisticsDao = \DAO\StoreStatisticsModel::getInstance();
        //获取店铺数据统计
        $storeStats = $storeStatisticsDao->find(array('store_id' => $storeId));
        $data['orderTotal'] = $storeStats['order_total'];
        $data['orderCount'] = $storeStats['order_count'];
        $result = $this->getOrders($memberId, $pageIndex, $pageSize, $orderState, $keyword);
        $data['orders'] = $result['orders'];
        return $data;
    }

    public function getOrders($memberId, $pageIndex, $pageSize, $orderState, $keyword)
    {
        $storeId = $this->_getStoreByMemberId($memberId);
        $where = 'han_order.store_id=' . $storeId;
        if (!empty($orderState)) {
            $where .= ' and han_order.order_state=' . $orderState;
        }
        if (!empty($keyword)) {
            $where .= " and (han_order.order_sn like '%" . $keyword ."%')";
        }
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance();
        $orderDao = \DAO\Order\OrderModel::getInstance();
        $goodsDao = \DAO\GoodsModel::getInstance();
        $returnData = $orderDao->getOrders($where, $this->orderListField, $pageIndex, $pageSize);
        $orders = $returnData['orders'];
        if (!empty($orders)) {
            $orderIds = array_column($orders, 'orderId');
            if (!empty($orderIds)) {
                $orderGoods = $orderGoodsDao->getOrderGoodsByOrderIds($orderIds, $orderGoodsDao->orderGoodsField);
                $orderMerge = \Our\Common::intergrateOneToMany($orders, $orderGoods, 'orderId', 'orderId', 'orderGoods');
                foreach ($orderMerge as &$value) {
                    $value['orderStateName'] = $orderDao->getStatusText($value);
                    $value['orderText'] = $orderDao->getText($value, ApiConst::orderListDescribe);
                    if (!empty($value['orderGoods'])) {
                        $value['totalGoodsNum'] = $orderGoodsDao->getGoodsCount($value['orderGoods']);
                    } else {
                        $value['totalGoodsNum'] = ApiConst::zero;
                    }
                    //$value['blId'] = isset($value['blId']) ? (!is_null($value['blId']) ? $value['blId'] : ApiConst::zero) : ApiConst::zero;
                    if (isset($value['orderGoods'])) {
                        $value['orderGoods'] = $goodsDao->convert($value['orderGoods']);
                    } else {
                        $value['orderGoods'] = array();
                    }
                }
                $returnData['orders'] = $orderMerge;
                $returnData['totalCount'] = $returnData['totalCount'];
            } else {
                $returnData = new \stdClass();
            }
        } else {
            $returnData = new \stdClass();
        }

        return $returnData;
    }

    private function getGoodsDetailField()
    {
        return $this->orderGoodsField . ',goods_commonid as goodsCommonid,goods_spec as goodsSpec ';
    }

    /**
     * 订单详情
     */
    public function getOrderDetail($memberId, $orderId)
    {
        $storeId = $this->_getStoreByMemberId($memberId);
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::salveDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $diliverymanDao = \DAO\Order\DiliverymanModel::getInstance(DbNameConst::salveDBConnectName);
        $storeDao = \DAO\StoreModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsDao = \DAO\GoodsModel::getInstance(DbNameConst::salveDBConnectName);
        //订单
        $order = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'findByOrderId'), array($orderId), \Our\ApiConst::oneDaySecond);
        if ($order['store_id'] != $storeId) {
            ErrorModel::throwException(CodeConfigModel::orderError);
        }
        $fields = $orderDao->getFields();
        $this->order = $orderDao->getConvertOrder($order, $fields);
        //收货人地址
        //收货人信息
        $this->orderCommon = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderCommonDao, 'findByOrderId'), array($orderId, $orderCommonDao->orderCommonField), \Our\ApiConst::oneDaySecond);
        //$this->orderCommon = $orderCommonDao->findByOrderId($orderId, $this->orderCommonField);
        $reciverInfo = $this->orderCommon['reciverInfo'];
        $reciverInfo = unserialize($reciverInfo);
        $reciverInfo['true_name'] = $this->orderCommon['reciverName'];
        $this->address = $orderCommonDao->getReciverInfo($reciverInfo);

        //定单商品表

        $this->orderGoodsList = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByOrderIds'), array($orderId, $this->getGoodsDetailField()), \Our\ApiConst::oneDaySecond);
        //商店相关信息
        $this->store = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$storeDao, 'getInfoById'), array($this->order['storeId'], $this->storeField), \Our\ApiConst::oneDaySecond);
        $returnData = $this->order;
        //配送员信息
        $this->diliveryman = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$diliverymanDao, 'findById'), array($returnData['diliverymanId']), \Our\ApiConst::oneDaySecond);
        //地址
        $returnData['shippingName'] = $orderDao->getShippingName($returnData['shippingType']);
        $returnData['orderMessage'] = $this->orderCommon['orderMessage'];
        $returnData['shippingFeeName'] = $orderDao->getFreightFeeName($returnData['shippingType']);
        $returnData['paymentName'] = $orderDao->getPayTypeName($returnData['paymentType']);
        $returnData['discountAmount'] = $returnData['goodsAmount'] - $returnData['orderAmount'] + $returnData['shippingFee'];
        $returnData['orderText'] = $orderDao->getStatusDetailText($this->order, ApiConst::storeText);
        $returnData['orderExtentText'] = $orderDao->getText($this->order, ApiConst::orderDetailDescribe);
        $returnData['couponId'] = $returnData['couponId'] ? $returnData['couponId'] : ApiConst::zero;
        $returnData['shippingTime'] = $this->orderCommon['shippingTime'];
        if ($returnData['diliverymanId']) {
            $returnData['deliveryman'] = $diliverymanDao->convert($this->diliveryman, $this->getDeliveryManFields());
        } else {
            $returnData['diliverymanId'] = ApiConst::zero;
            $returnData['deliveryman'] = new \stdClass();
        }
        $returnData['totalGoodsNum'] = $orderGoodsDao->getGoodsCount($this->orderGoodsList);
        $returnData['offlinePayway'] = $this->store['offlinePayway'] ? $this->store['offlinePayway'] : '';
        $returnData['reciverInfo'] = $this->address;
        $returnData['orderGoods'] = $goodsDao->convert($this->orderGoodsList);
        return $returnData;
    }
//    public function getOrderDetail($memberId,$orderId){
//        $storeId = $this->_getStoreByMemberId($memberId);
//        $orderDao = \DAO\Order\OrderModel::getInstance();
//        $where['store_id'] = $storeId;
//        $where['order_id'] = $orderId;
//        $order = $orderDao->getOrderDetail($where);
//        return $order;
//    }

    /**
     * 判断是否是店主
     */
    private function _getStoreByMemberId($memberId)
    {
        $storeId = $this->storeDao->getInfoByMemberId($memberId, 'store_id', 'store_id');
        if (empty($storeId)) {
            ErrorModel::throwException(CodeConfigModel::storeNotExistOrClose);
        }

        return $storeId;
    }

    /**
     * 判断是否是店主
     */
//我是店主统计任务
    //获得订单统计数据
    public $baseDir;

    public function getOrderTotal()
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $res = file_get_contents($this->baseDir .PathConst::orderPaymentTimeConf);
        $this->lastOrderId = !empty($res) ? $res : ApiConst::zero;
        $where['payment_time'] =Common::format(" payment_time > {0} and payment_time <={1}",$this->lastOrderId,TIMESTAMP);
        $res = $orderDao->getAllByWhere($where, $orderDao->getOrderDetailField());
        $results = array();
        if (!empty($res)) {
            foreach ($res as $re) {
                $date = date('Y-m-d', $re['paymentTime']);
                if (isset($results[$re['storeId'] . '|' . $date])) {
                    $results[$re['storeId'] . '|' . $date]['orderCount'] += ApiConst::one;
                    $results[$re['storeId'] . '|' . $date]['orderTotal'] += $re['orderAmount'];
                } else {
                    $results[$re['storeId'] . '|' . $date]['orderCount'] = ApiConst::one;
                    $results[$re['storeId'] . '|' . $date]['orderTotal'] = $re['orderAmount'];
                }
            }
        }
        return $results;
    }

    public function getMemberTotal()
    {
        $favoritesStoreDao = \DAO\FavoritesStoreModel::getInstance();
        $res = file_get_contents($this->baseDir . PathConst::favoritesStoreFavTimeConf);
        $this->lastFavId = !empty($res) ? $res : ApiConst::zero;
        $where['fav_time'] =Common::format("fav_time >={0} and fav_time <{1}",$this->lastFavId,TIMESTAMP);
        $res = $favoritesStoreDao->getAllByWhere($where, $favoritesStoreDao->favoriteMemberCountField);
        $results = array();
        if (!empty($res)) {
            foreach ($res as $re) {
                $date = date('Y-m-d', $re['favTime']);
                if (isset($results[$re['storeId'] . '|' . $date])) {
                    $results[$re['storeId'] . '|' . $date]['favCount'] += ApiConst::one;
                } else {
                    $results[$re['storeId'] . '|' . $date]['favCount'] = ApiConst::one;
                }
            }
        }
        return $results;
    }
//任务脚本
    public function insertStoreMemberStatics()
    {
        $orderGoodDao=\DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $storeMemberStatisticDao=\DAO\StoreMemberStatisticsModel::getInstance(DbNameConst::masterDBConnectName);
        $gmtCreate = file_get_contents($this->baseDir . PathConst::orderGoodsCreateTime);
        $gmtCreate = $gmtCreate?$gmtCreate:ApiConst::zero;
        $beginTime=$gmtCreate;
        $this->taskIndex=PageConst::taskPageBegin;
        $this->taskSize=PageConst::taskPageSize;
        do{
            $addDatas=array();
            $storeMemberStatisticData= $orderGoodDao->getMemberStoreStaticsByCreateTime($beginTime,$this->taskIndex,$this->taskSize);
            $storeMemberStatisticData=isset($storeMemberStatisticData['list'])?$storeMemberStatisticData['list']:false;
            if($storeMemberStatisticData){
                $this->taskIndex++;
                foreach($storeMemberStatisticData as $value){
                    $addDatas[$value['buyerId'].'-'.$value['storeId']]['storeId']=$value['storeId'];
                    $addDatas[$value['buyerId'].'-'.$value['storeId']]['memberId']=$value['buyerId'];
                    if(isset($addDatas[$value['buyerId'].'-'.$value['storeId']]['orderGoodsCount'])){
                        $addDatas[$value['buyerId'].'-'.$value['storeId']]['orderGoodsCount']+=$value['goodsNum'];
                    }else{
                        $addDatas[$value['buyerId'].'-'.$value['storeId']]['orderGoodsCount']=$value['goodsNum'];
                    }
                    if(isset($addDatas[$value['buyerId'].'-'.$value['storeId']]['orderTotal'])){
                        $addDatas[$value['buyerId'].'-'.$value['storeId']]['orderTotal']+=$value['goodsPrice'];
                    }else{
                        $addDatas[$value['buyerId'].'-'.$value['storeId']]['orderTotal']=$value['goodsPrice'];
                    }
                }
            }
            $addDatas=array_values($addDatas);
            $storeMemberStatisticDao->addAll($addDatas);
        }while($storeMemberStatisticData);
        file_put_contents($this->baseDir . PathConst::orderGoodsCreateTime, TIMESTAMP);

    }
    //任务脚本
    public function reduceStoreMemberStatics()
    {
        $refundReturnDao=\DAO\Order\RefundReturnModel::getInstance(DbNameConst::salveDBConnectName);
        $storeMemberStatisticDao=\DAO\StoreMemberStatisticsModel::getInstance(DbNameConst::masterDBConnectName);
        $gmtUpdate = file_get_contents($this->baseDir . PathConst::refundRetrunGmtUpdate);
        $gmtUpdate = $gmtUpdate?$gmtUpdate:ApiConst::zero;
        $this->taskIndex=PageConst::taskPageBegin;
        $this->taskSize=PageConst::taskPageSize;
        do{
            $addDatas=array();
            $storeMemberStatisticData= $refundReturnDao->getMemberStoreStaticsByGmtUpdate($gmtUpdate,$this->taskIndex,$this->taskSize);
            $storeMemberStatisticData=isset($storeMemberStatisticData['list'])?$storeMemberStatisticData['list']:false;
            if($storeMemberStatisticData){
                $this->taskIndex++;
                foreach($storeMemberStatisticData as $value){
                    $addDatas[$value['buyerId'].'-'.$value['storeId']]['storeId']=$value['storeId'];
                    $addDatas[$value['buyerId'].'-'.$value['storeId']]['memberId']=$value['buyerId'];
                    if(isset($addDatas[$value['buyerId'].'-'.$value['storeId']]['orderGoodsCount'])){
                        $addDatas[$value['buyerId'].'-'.$value['storeId']]['orderGoodsCount']+=$value['goodsNum'];
                    }else{
                        $addDatas[$value['buyerId'].'-'.$value['storeId']]['orderGoodsCount']=$value['goodsNum'];
                    }
                    if(isset($addDatas[$value['buyerId'].'-'.$value['storeId']]['orderTotal'])){
                        $addDatas[$value['buyerId'].'-'.$value['storeId']]['orderTotal']+=$value['refundAmount'];
                    }else{
                        $addDatas[$value['buyerId'].'-'.$value['storeId']]['orderTotal']=$value['refundAmount'];
                    }
                }
            }
            $addDatas=array_values($addDatas);
            $storeMemberStatisticDao->addAllReduce($addDatas);
        }while($storeMemberStatisticData);
        file_put_contents($this->baseDir . PathConst::refundRetrunGmtUpdate, TIMESTAMP);

    }
    //店铺订单统计任务脚本
    public function storeStatictisTask()
    {

        $orderTotals = $this->getOrderTotal();
        $memberTotals = $this->getMemberTotal();
        $storeStatisticsDayDao = \DAO\Store\StoreStatisticsDayModel::getInstance(DbNameConst::masterDBConnectName);
        $storStatisticsDao = \DAO\StoreStatisticsModel::getInstance(DbNameConst::masterDBConnectName);
        $storeStatisticsData = array();
        foreach ($memberTotals as $key => $mt) {
            $orderTotals[$key]['favCount'] = $mt['favCount'];
        }
        foreach ($orderTotals as $key => $value) {
            if (empty($value['favCount'])) {
                $orderTotals[$key]['favCount'] = ApiConst::zero;
            }
            if (empty($value['orderCount'])) {
                $orderTotals[$key]['orderCount'] = ApiConst::zero;
            }
            if (empty($value['orderTotal'])) {
                $orderTotals[$key]['orderTotal'] = ApiConst::zero;
            }
            $storeDate = explode('|', $key);
            $orderTotals[$key]['storeId'] = $storeDate[ApiConst::zero];
            $orderTotals[$key]['gmtCreate'] = $storeDate[ApiConst::one];
            $one = $orderTotals[$key];
            if (isset($storeStatisticsData[$one['storeId']])) {
                $storeStatisticsData[$one['storeId']]['orderCount'] += $one['orderCount'];
                $storeStatisticsData[$one['storeId']]['orderTotal'] += $one['orderTotal'];
                $storeStatisticsData[$one['storeId']]['favCount'] += $one['favCount'];
            } else {
                $storeStatisticsData[$one['storeId']] = array();
                $storeStatisticsData[$one['storeId']]['storeId'] = $one['storeId'];
                $storeStatisticsData[$one['storeId']]['orderCount'] = $one['orderCount'];
                $storeStatisticsData[$one['storeId']]['orderTotal'] = $one['orderTotal'];
                $storeStatisticsData[$one['storeId']]['favCount'] = $one['favCount'];
            }
        }
        $storeStatisticsData = array_values($storeStatisticsData);
        $orderTotals = array_values($orderTotals);
        if (!empty($orderTotals)) {
            $storeStatisticsDayDao->addAll($orderTotals);
        }
        if (!empty($storeStatisticsData)) {
            $storStatisticsDao->addAll($storeStatisticsData);
        }
    }

    public function updateLastId()
    {
        file_put_contents($this->baseDir . PathConst::favoritesStoreFavTimeConf, TIMESTAMP);
        file_put_contents($this->baseDir . PathConst::orderPaymentTimeConf, TIMESTAMP);
    }

    /**
     * 登录业务
     *
     * @var \Business\User\LoginV2Model
     */
    private static $_instance = null;

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

        return self::$_instance;
    }

}
