<?php

namespace Business\Store;

use DAO\Order\DiliverymanModel;
use DAO\StoreModel;
use DAO\MemberModel;
use DAO\StoreStatisticsModel;
use Elastics\ElasticsToolModel;
use Error\CodeConfigModel;
use Error\ErrorModel;
use Our\ApiConst;
use Our\Common;
use Our\DbNameConst;
use Our\ImageConst;
use Our\NameConst;
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 $clientType = false;

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

    private $orderListField = 'han_order.order_id as orderId,han_order.order_sn as orderSn,han_order.delete_state as deleteState,han_order.buyer_id as buyerId,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)
    {
        $memberDao = \DAO\MemberModel::getInstance();
        $storeId = $memberDao->getInfo($memberId, 'store_id');
        //$storeId = $this->_getStoreByMemberId($memberId);
//        $storeStatisticsDayDao = \DAO\Store\StoreStatisticsDayModel::getInstance();
//        $storeStatisticsDao = \DAO\StoreStatisticsModel::getInstance();
        $orderDao = \DAO\Order\OrderModel::getInstance();
        $favoritesStoreDao = \DAO\FavoritesStoreModel::getInstance();
        $memberFavoritesStoreStoreMemberStatisticsDao = \DAO\Store\MemberFavoritesStoreStoreMemberStatisticsModel::getInstance();
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance();
        //$goodsCount = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsCountByStoreId'), array($storeId), ApiConst::tenDaySecond, array($storeId));
        $totalOrderCount = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$memberFavoritesStoreStoreMemberStatisticsDao, 'getGoodsCountOrderTotalByStoreId'), array($storeId), ApiConst::oneDaySecond, array($storeId));
        $condition['store_id'] = $storeId;
        //获取店铺信息
        $store = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$this->storeDao, 'getInfo'), array($condition), ApiConst::oneDaySecond, array($storeId));
        //获取店铺数据统计
        //$storeStats = $storeStatisticsDao->find($condition);
        //获取店铺今日销售额和订单量
        // $storeStats=$orderDao->getShopKeeperCountByStoreId($storeId);
        $storeStats = $orderDao->getShopKeeperCountByStoreIdCache($storeId);
        $storeFavariteCount = $favoritesStoreDao->getFavoritesCountByStoreIdCache($storeId);

        $goodsCount = $totalOrderCount['orderGoodsCount'];
        $orderTotal = $totalOrderCount['orderTotal'];
        $data['storeId'] = $store['store_id'];
        $data['storeName'] = $store['store_name'];
        $data['storeLabel'] = $store['store_label'];
        $data['goodsCount'] = $goodsCount?$goodsCount:ApiConst::zero;
        $data['orderCount'] = $storeStats['orderCount'];
        $data['orderTotal'] = $orderTotal?$orderTotal:ApiConst::zero;
        $data['favCount'] = $storeFavariteCount['favCount'];
        $data['todayOrderCount'] = $storeStats['todayOrderCount'];
        $data['todayOrderTotal'] = $storeStats['todayOrderTotal'];
        $data['tadayFavCount'] = $storeFavariteCount['todayFavCount'];
        $data['todayFavCount'] = $storeFavariteCount['todayFavCount'];
        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;
            $update_data['accept_time'] = TIMESTAMP;
            $result = $orderDao->update($where, $update_data);
            $orderDao->deleteOrderCache($order['buyer_id'], $orderId, $order['store_id'], true);
            //   \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 getRetrunDatas($storeId, $where, $pageIndex, $pageSize,$order = array('gmt_update' => 'desc'))
    {
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance();
        $orderDao = \DAO\Order\OrderModel::getInstance();
        $goodsDao = \DAO\GoodsModel::getInstance();
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance();

        $returnData = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'getList'), array($where, $orderDao->getOrderDetailField(), $pageIndex, $pageSize, $order, \Our\ApiConst::oneDaySecond, array($storeId)));
        //$returnData = $orderDao->getOrders($where, $this->orderListField, $pageIndex, $pageSize);
        $orders = $returnData['list'];
        if (!empty($orders)) {
            $orderIds = array_column($orders, 'orderId');
            if (!empty($orderIds)) {
                $orderGoods = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByOrderIds'), array($orderIds, $orderGoodsDao->orderGoodsField), \Our\ApiConst::oneDaySecond, array($storeId));
                //$orderGoods = $orderGoodsDao->getOrderGoodsByOrderIds($orderIds, $orderGoodsDao->orderGoodsField);
                $orderCommons = $orderCommonDao->getAllByOrderIds($orderIds, $orderCommonDao->orderCommonField);
                $ordersOrderCommons = Common::intergrateOneToOne($orders, $orderCommons, 'orderId', 'orderId');
                $orderMerge = \Our\Common::intergrateOneToMany($ordersOrderCommons, $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();
                    }
                    if ($this->clientType && $this->clientType == NameConst::pcClient) {
                        $value['couponAmount'] = ($value['goodsAmount'] + $value['shippingFee']) - $value['orderAmount'];//优惠券金额
                        $value['receiveAmount'] = $value['goodsAmount'] - $value['couponAmount'];
                        $value['orderAmount'] = $value['orderAmount'] + $value['couponAmount'];
                        $value['reciverInfo'] = unserialize($value['reciverInfo']);
                        $value['dlyoPickupCode'] = intval(substr($value['orderSn'], ApiConst::positionPickupCodeBegin));
                        $value['shippingArrivalTimeEnd'] = $value['shippingArrivalTime'] + ApiConst::arriveTimeRadius;
                        if ($value['diliverymanId']) {
                            $diliverymanDao = DiliverymanModel::getInstance();
                            $res = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$diliverymanDao, 'findById'), array($value['diliverymanId']), \Our\ApiConst::oneDaySecond, array($value['diliverymanId']));
                            $value['deliveryman'] = $diliverymanDao->convert($res);
                        }
                    } else {
                        unset($value['reciverInfo']);
                    }
                    unset($value['couponId']);
                    unset($value['refundAmount']);
                    unset($value['paymentTime']);
                    unset($value['finnshedTime']);
                    unset($value['paymentCode']);
                    unset($value['needShippingFee']);
                    unset($value['refundCondition']);
                    unset($value['delayTime']);
                    unset($value['reciverName']);
                    unset($value['daddressId']);
                }
                $return['orders'] = $orderMerge;
                $return['totalCount'] = $returnData['totalCount'];
            } else {
                $return = new \stdClass();
            }
        } else {
            $return = new \stdClass();
        }
        return $return;
    }

    public function getOrderIndexWhere($storeId, $keyword, $pageIndex, $pageSize, $orderState = false)
    {
        $query1[] = array('match' => array('storeId' => $storeId));
        if ($orderState != false) {
            $query1[] = array('match' => array('orderState' => $orderState));
        }
        $res1['must'][0] = $query1;
        $query2[] = array('match' => array('goodsName' => $keyword));
        $query2[] = array('wildcard' => array('orderSn' => "*{$keyword}*"));
        $res1['must'][1]['bool']['should'] = $query2;
        $allQuery['bool'] = $res1;
        $elasticTool = \Elastics\ElasticsToolModel::getInstance(NameConst::ordersIndex);
        $res = $elasticTool->searchMatch($allQuery, $pageIndex, $pageSize);
        $orderIdsField = array_column($res['list'], 'orderId');
        $orderIds = implode(',', $orderIdsField);
        if ($orderIds) {
            $where = Common::format(" order_id in({0})", $orderIds);
        } else {
            $where = false;
        }
        return $where;
    }

    public function getOrders($memberId, $pageIndex, $pageSize, $orderState, $keyword)
    {

        $order = array('gmt_update' => 'desc');
        $storeId = $this->_getStoreByMemberId($memberId);
        if (empty($storeId)) {
            ErrorModel::throwException(CodeConfigModel::paramsError);
        }
        $allQuery = array();
        $allQuery['bool'] = array();
        if (!empty($keyword)) {
            $orderState = !empty($orderState) ? $orderState : false;
            if (strlen($keyword) == ApiConst::four) {
                $where = 'han_order.store_id=' . $storeId;
                $where .= Common::format(" and SUBSTRING(order_sn, {0}, {1})='{2}'", ApiConst::positionPickupCodeBeginMysql, ApiConst::four, $keyword);
            } else {
                $where = $this->getOrderIndexWhere($storeId, $keyword, $pageIndex, $pageSize, $orderState);
            }
        } else {
            $where = 'han_order.store_id=' . $storeId;
            if ($orderState == ApiConst::oneHandred || (int)$orderState == ApiConst::oneHandredOne) {
                if ($orderState == ApiConst::oneHandred) {
                    $where .= ' and han_order.shipping_type=' . ApiConst::bySelf;
                } else {
                    $order=array(
                        'diliveryman_id'=>'asc',
                        'gmt_update'=>'asc'
                    );
                    $where .= ' and han_order.shipping_type=' . ApiConst::bySeller;
                }

            } else {
                if (!empty($orderState)) {
                    $where .= ' and han_order.order_state=' . $orderState;
                }
            }

        }
        if (!empty($where)) {
            $returnData = $this->getRetrunDatas($storeId, $where, $pageIndex, $pageSize,$order);
        } else {
            $returnData = new \stdClass();
        }
        return $returnData;
    }

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

    public function getDiliveryManByStoreId($memberId)
    {
        $memberDao = \DAO\MemberModel::getInstance();
        $storeId = $memberDao->getInfo($memberId, 'store_id');
        if (empty($storeId)) {
            ErrorModel::throwException(CodeConfigModel::emptyStoreId);
        }
        $diliveryMan = \DAO\Order\DiliverymanModel::getInstance();
        return \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$diliveryMan, 'getDeliveryManByStoreId'), array($storeId), \Our\ApiConst::oneHourCache, array($storeId));
    }

    public function confirmReceivePayment($memberId,$orderId){
        $memberDao = \DAO\MemberModel::getInstance();
        $storeId = $memberDao->getInfo($memberId, 'store_id');
        $orderDao=\DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $where['order_id']=$orderId;
        $where['store_id']=$storeId;
        $count=$orderDao->getCountByWhere($where);
        if($count){
            $data['is_receive_payment']=TIMESTAMP;
            $updateId=$orderDao->updateByOrderId($data,$orderId);
            return $updateId;
        }else{
            ErrorModel::throwException(CodeConfigModel::notExsitOrder);
        }

    }

    /**
     * 订单详情
     */
    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, array($orderId));
        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, array($returnData['diliverymanId']));
        //地址
        $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 ($this->clientType && $this->clientType == NameConst::pcClient) {
            $returnData['couponAmount'] = ($returnData['goodsAmount'] + $returnData['shippingFee']) - $returnData['orderAmount'];//优惠券金额
            $returnData['receiveAmount'] = $returnData['goodsAmount'] - $returnData['couponAmount'];
            $returnData['orderAmount'] = $returnData['orderAmount'] + $returnData['couponAmount'];
            $returnData['dlyoPickupCode'] = intval(substr($returnData['orderSn'], ApiConst::positionPickupCodeBegin));
            $returnData['shippingArrivalTimeEnd'] = $returnData['shippingArrivalTime'] + ApiConst::arriveTimeRadius;
        } else {
            unset($returnData['reciverInfo']);
        }
        if ($returnData['diliverymanId']) {
            $returnData['deliveryman'] = $diliverymanDao->convert($this->diliveryman, $diliverymanDao->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;
    }

    /**
     * 判断是否是店主
     */
    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 = Common::format(" add_time > {0} and add_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 = 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);
        $orderDao = \DAO\Order\OrderModel::getInstance();
        $storeMemberStatisticDao = \DAO\StoreMemberStatisticsModel::getInstance(DbNameConst::masterDBConnectName);
        $reufndReturnDao = \DAO\Order\RefundReturnModel::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 {
            $storeMemberStatisticData = $orderGoodDao->getMemberStoreStaticsByCreateTime($beginTime, $this->taskIndex, $this->taskSize);
            $storeMemberStatisticData = isset($storeMemberStatisticData['list']) ? $storeMemberStatisticData['list'] : false;
            if ($storeMemberStatisticData) {
                $this->taskIndex++;
                $storeId = array_column($storeMemberStatisticData, 'storeId');
                $memberId = array_column($storeMemberStatisticData, 'buyerId');
                $storeIds = array_unique($storeId);
                $memberIds = array_unique($memberId);
                $goodsNumCount = $orderGoodDao->getMemberStoreOrderGoodsCount($storeIds, $memberIds);
                $ordersCount = $orderDao->getSumAmountCountByMemberAndStoreId($storeIds, $memberIds);
                $refundLists = $reufndReturnDao->getRefundSuccessMoneyByStoreIdAndMemberId($storeIds, $memberIds);
                if (!empty($ordersCount) && !empty($refundLists)) {
                    foreach ($ordersCount as &$order) {
                        foreach ($refundLists as $refund) {
                            if ($order['buyerId'] == $refund['buyerId'] && $order['storeId'] == $refund['storeId']) {
                                $order['orderTotal'] = $order['orderTotal'] - $refund['refundTotal'];
                            }
                        }
                    }
                }
                if (!empty($goodsNumCount)) {
                    $storeMemberStatisticDao->addAll($goodsNumCount, 'orderGoodsCount');
                }
                if (!empty($ordersCount)) {
                    $storeMemberStatisticDao->addAll($ordersCount, 'orderTotal');
                }
            }


        } while ($storeMemberStatisticData);
        file_put_contents($this->baseDir . PathConst::orderGoodsCreateTime, TIMESTAMP);

    }
//任务脚本
//    public function insertStoreMemberStatics()
//    {
//        $orderGoodDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
//        $orderDao=\DAO\Order\OrderModel::getInstance();
//        $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;
//            $orderIds=array_column($storeMemberStatisticData,'orderId');
//            array_unique($orderIds);
//            if(!empty($orderIds)){
//                $orders=$orderDao->getByOrderId($orderIds,'order_amount as orderAmount,order_id as orderId','orderId');
//            }else{
//                $orders=[];
//            }
//            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'];
//                        $addDatas[$value['buyerId'] . '-' . $value['storeId']]['orderTotal'] +=$orders[$value['orderId']]['orderAmount'];
//                    } else {
//                        $addDatas[$value['buyerId'] . '-' . $value['storeId']]['orderTotal'] = $orders[$value['orderId']]['orderAmount'];
//                    }
//                }
//            }
//            $addDatas = array_values($addDatas);
//            $storeMemberStatisticDao->addAll($addDatas);
//        } while ($storeMemberStatisticData);
//        file_put_contents($this->baseDir . PathConst::orderGoodsCreateTime, TIMESTAMP);
//
//    }

    //创建索引
    public function createOrdersIndex()
    {

        $elasticsTool = ElasticsToolModel::getInstance('orders');
        // $elasticsTool->deleteIndex();
        $indexsFiled = array(
            'goodsName' => array(
                'type' => 'string',
                "analyzer" => "ik_max_word"
            ),
            'storeName' => array(
                'type' => 'string',
                "analyzer" => "ik_max_word"
            ),
            'orderSn' => array(
                'type' => 'string',
                "index" => "not_analyzed"
            ),
        );
        $elasticsTool->createIkField($indexsFiled);
    }
    //grow orderIndex
    //创建索引
    public function growOrdersIndex()
    {
        $orderGoodDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $gmtCreate = file_get_contents($this->baseDir . PathConst::orderLastCreateTime);
        $gmtCreate = !empty($gmtCreate) ? $gmtCreate : ApiConst::zero;
        $beginTime = $gmtCreate;
        $this->taskIndex = PageConst::taskPageBegin;
        $this->taskSize = PageConst::taskPageSize;
        $elasticsTool = ElasticsToolModel::getInstance(NameConst::ordersIndex);
        do {
            $where = Common::format(" han_order.gmt_update>={0} and han_order.gmt_update<{1}  ", $beginTime, TIMESTAMP);
//            $orders = $this->getRetrunDatas($where, $this->taskIndex, $this->taskSize);
//            if (!empty($orders['orders'])) {
//                $this->taskIndex++;
//                $indexs = array();
//                echo json_encode($orders['orders']);exit;
//                foreach ($orders['orders'] as $result) {
//                    $one['orderId'] = $result['orderId'];
//                    $one['orderSn'] = $result['orderSn'];
//                    $namesArr = array_column($result['orderGoods'], 'goodsName');
//                    $nameStr = implode(',', $namesArr);
//                    $one['goodsName'] = $nameStr;
//                    $one['deleteState'] = $result['deleteState'];
//                    $one['orderState'] = $result['orderState'];
//                    $one['addTime'] = $result['addTime'];
//                    $one['type'] = 'orders' . ($result['buyerId'] + $result['storeId']) % ApiConst::orderIndexRank;
//                    $one['fields'] = json_encode($result);
//                    array_push($indexs, $one);
//                 }
//                $elasticsTool->postBulkDoc($indexs, 'orderId');
//            }
            $orders = $orderDao->getList($where, "order_id as orderId,order_sn as orderSn,delete_state as deleteState,order_state as orderState,add_time as addTime,store_name as storeName,buyer_id as buyerId,store_id as storeId", $this->taskIndex, $this->taskSize, array('add_time' => 'desc'));
            if (!empty($orders['list'])) {
                $this->taskIndex++;
                $indexs = array();
                $orderIds = array_column($orders['list'], 'orderId');
                $orderGoods = $orderGoodDao->getOrderGoodsByOrderIds($orderIds, 'order_id as orderId,goods_name as goodsName');
                $resultOrders = Common::intergrateOneToMany($orders['list'], $orderGoods, 'orderId', 'orderId', 'orderGoods');
                foreach ($resultOrders as $result) {
                    $one['orderId'] = $result['orderId'];
                    $one['orderSn'] = $result['orderSn'];
                    $namesArr = array_column($result['orderGoods'], 'goodsName');
                    $nameStr = implode(',', $namesArr);
                    $one['goodsName'] = $nameStr;
                    $one['storeName'] = $result['storeName'];
                    $one['deleteState'] = $result['deleteState'];
                    $one['orderState'] = $result['orderState'];
                    $one['storeId'] = $result['storeId'];
                    $one['buyerId'] = $result['buyerId'];
                    $one['addTime'] = $result['addTime'];
                    //$one['type']=NameConst::ordersIndex.($result['storeId'])%ApiConst::orderIndexRank;
                    array_push($indexs, $one);
                }
                $elasticsTool->postBulkDoc($indexs, 'orderId');
            }
        } while ($orders['list']);
        file_put_contents($this->baseDir . PathConst::orderLastCreateTime, TIMESTAMP);

    }

    public function reduceRefundModel($storeMemberDatas)
    {
        $convertStoreMember = array();
        if ($storeMemberDatas) {
            foreach ($storeMemberDatas as $order) {
                if (isset($convertStoreMember[$order['storeId']])) {
                    $convertStoreMember[$order['storeId']]['orderCount'] = $convertStoreMember[$order['storeId']]['orderCount'] - ApiConst::one;
                    $convertStoreMember[$order['storeId']]['orderTotal'] = $convertStoreMember[$order['storeId']]['orderTotal'] + $order['refundAmount'];

                } else {
                    $convertStoreMember[$order['storeId']]['orderCount'] = ApiConst::one;
                    $convertStoreMember[$order['storeId']]['orderTotal'] = $order['refundAmount'];
                    $convertStoreMember[$order['storeId']]['gmtCreate'] = isset($order['gmtUpdate']) ? date($order['gmtUpdate']) : date('Y-m-d', TIMESTAMP);
                }
            }
            $convertStoreMember = array_values($convertStoreMember);
            $storeStatisticDayDao = \DAO\Store\StoreStatisticsDayModel::getInstance(DbNameConst::masterDBConnectName);
            $storeStatisticDayDao->addAllReduce($convertStoreMember);
        }

    }

    //任务脚本
    public function reduceStoreMemberStatics()
    {
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::salveDBConnectName);
        $storeMemberStatisticDao = \DAO\StoreMemberStatisticsModel::getInstance(DbNameConst::masterDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
        $orderDao = \DAO\Order\OrderModel::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 {
            $storeMemberStatisticData = $refundReturnDao->getMemberStoreStaticsByGmtUpdate($gmtUpdate, $this->taskIndex, $this->taskSize);
            $storeMemberStatisticData = isset($storeMemberStatisticData['list']) ? $storeMemberStatisticData['list'] : false;
            if (!empty($storeMemberStatisticData)) {
                foreach ($storeMemberStatisticData as $item) {
                    $orderDao->deleteOrderCache($item['buyerId'], $item['orderId'], $item['storeId'], true, true);
                }
                $orderIds = array_column($storeMemberStatisticData, 'orderId');
                foreach ($orderIds as $orderId) {
                    $res = $orderGoodsDao->find(array('order_id' => $orderId, 'refund_id' => ApiConst::zero));
                    if (empty($res)) {
                        $orderDao->update(array('order_id' => $orderId), array('order_state' => ApiConst::orderStateClose));
                    }
                }
            }
            $this->taskIndex++;
        } 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);
    }

    public function sellerLogin($sellerName)
    {
        $sellerDao = \DAO\Store\SellerModel::getInstance(DbNameConst::masterDBConnectName);
        $sellerGroupDao=\DAO\Store\SellerGroupModel::getInstance(DbNameConst::masterDBConnectName);
        $sellerInfo = $sellerDao->getInfoBySellerName($sellerName);
        if($sellerInfo['sellerGroupId'] > ApiConst::zero){
            $allowMenus=$sellerGroupDao->getInfoById($sellerInfo['sellerGroupId'],'limits');
            $allowMenuaArr=explode(',',$allowMenus);
            if(!in_array('client',$allowMenuaArr)){
                ErrorModel::throwException(CodeConfigModel::notHaveAccess);
            }
        }
        if ($sellerInfo) {
            $memberDao = \DAO\MemberModel::getInstance(DbNameConst::masterDBConnectName);
            $memberInfo = $memberDao->getInfo($sellerInfo['memberId']);
            $sellerInfo['memberMobile']=$memberInfo['memberMobile'];
            $sellerInfo['trueName']=$memberInfo['memberName'];
            return $sellerInfo;
        }
        ErrorModel::throwException(CodeConfigModel::errorUsernameOrPassword);

    }

    public function getSellerCount($memberId)
    {
        $memberDao = \DAO\MemberModel::getInstance();
        $storeId = $memberDao->getInfo($memberId, 'store_id');
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $waitReceiveCount = $orderDao->getCountByOrderState($storeId, ApiConst::orderStateWaitConfirm);
        $waitDeliveryCount = $orderDao->getCountByShippingTypeAndOrderState($storeId, ApiConst::bySeller, ApiConst::orderStateWaitRecieve);
        $waitGetCount = $orderDao->getCountByShippingTypeAndOrderState($storeId, ApiConst::bySelf, ApiConst::orderStateWaitRecieve);
        $orderCount=$waitReceiveCount+$waitDeliveryCount+$waitGetCount;
        return array('waitReceiveCount' => $waitReceiveCount, 'waitDeliveryCount' => $waitDeliveryCount, 'waitGetCount' => $waitGetCount,'orderCount'=>$orderCount);
    }
    public function getSellerRefundCount($memberId)
    {
        $memberDao = \DAO\MemberModel::getInstance();
        $storeId = $memberDao->getInfo($memberId, 'store_id');
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::salveDBConnectName);
        //待处理
        $waitRefundProccessCount = $refundReturnDao->getCountByRefundState($storeId, ApiConst::orderStateWaitConfirm);
        $waitRefundReceiveCount = $refundReturnDao->getCountByRefundType($storeId, ApiConst::refundTypeGoods);
        $refundCount=$waitRefundProccessCount+$waitRefundReceiveCount;
        return array('waitRefundProccessCount' => $waitRefundProccessCount, 'waitRefundReceiveCount' => $waitRefundReceiveCount, 'refundCount' =>$refundCount);
    }
    public function getStorageAlarmCount($memberId)
    {
        $memberDao = \DAO\MemberModel::getInstance();
        $storeId = $memberDao->getInfo($memberId, 'store_id');
        $goodsDao=\DAO\GoodsModel::getInstance();
        $alertCount=$goodsDao->getAlertCountByStoreId($storeId);
        return array('alertCount'=>$alertCount);
    }
    public function getCount($memberId){
        $orderCount=$this->getSellerCount($memberId);
        $refundCount=$this->getSellerRefundCount($memberId);
        $alertCount=$this->getStorageAlarmCount($memberId);
        $res=array_merge($orderCount,$refundCount,$alertCount);
        return $res;
    }

    public function getDiliveryMan($mobile){
        $memberDao = \DAO\MemberModel::getInstance();
        $member= $memberDao->getByMemberMobile($mobile);
        return $member;

    }

    /**
     * 登录业务
     *
     * @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;
    }

}
