<?php

namespace Business\Store;

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 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();
        $orderGoodsDao=\DAO\Order\OrderGoodsModel::getInstance();
        $goodsCount=\Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsCountByStoreId'), array($storeId), ApiConst::tenDaySecond, array($storeId));
        $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);
        //获取店铺今日销售额和订单量
        $storeStats = $orderDao->getShopKeeperCountByStoreIdCache($storeId);
        $storeFavariteCount=$favoritesStoreDao->getFavoritesCountByStoreIdCache($storeId);
        $data['storeId'] = $store['store_id'];
        $data['storeName'] = $store['store_name'];
        $data['storeLabel'] = $store['store_label'];
        $data['goodsCount'] =  $goodsCount;
        $data['orderCount'] =$storeStats['orderCount'];
        $data['orderTotal'] = $storeStats['orderTotal'];
        $data['favCount'] = $storeFavariteCount['favCount'];
        $data['todayOrderCount'] = $storeStats['todayOrderCount'];
        $data['todayOrderTotal'] = $storeStats['todayOrderTotal'];
        $data['tadayFavCount'] = $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;
            $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($where, $pageIndex, $pageSize)
    {
        $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;
    }

    public function getOrders($memberId, $pageIndex, $pageSize, $orderState, $keyword)
    {
        $storeId = $this->_getStoreByMemberId($memberId);
      //  'query' => array('bool'=>array('should' => $where)),
        $allQuery=array();
        $allQuery['bool']=array();
        if(!empty($keyword)){
            $query1[]= array('match' => array('storeId' => $storeId));
            $query1[]= array('match' => array('goodsName' => $keyword));
            // $where['storeId']=$storeId;
            if(!empty($orderState)){
                $query1[]= array('match' => array('orderState' => $orderState));
            }
            $res2=array('must'=>$query1);
            $allQuery['bool']=$res2;
            //array_push($allQuery['bool'],$res2);
           // echo json_encode($allQuery);exit;
          //  echo json_encode($allQuery);exit;
            $elasticTool=ElasticsToolModel::getInstance(NameConst::ordersIndex);
            $res=$elasticTool->searchMatch($allQuery,$pageIndex,$pageSize);
                $orderIdsField=array_column($res['list'],'orderId');
                $orderIds=implode(',',$orderIdsField);
                if($orderIds){
                    $where=Common::format(" han_order.store_id={0} and (han_order.order_id in({1}) or han_order.order_sn like '%{2}%')",$storeId,$orderIds,$keyword);
                }else{
                    $where=Common::format(" han_order.store_id={0} and han_order.order_sn like '%{1}%'",$storeId,$keyword);
                }
        }else{
                    $where = 'han_order.store_id=' . $storeId;
                    if (!empty($orderState)) {
                        $where .= ' and han_order.order_state=' . $orderState;
                     }
        }
        if(!empty($where)){
                $returnData = $this->getRetrunDatas($where, $pageIndex, $pageSize);
        }else{
            $returnData=new \stdClass();
        }




        return $returnData;
    }

    private function getGoodsDetailField()
    {
        return $this->orderGoodsField . ',goods_commonid as goodsCommonid,goods_commonid as goodsCommonId,goods_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,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);
        //地址
        $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 = 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);
        $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++;
                $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);
                $arr = array();
                if(!empty($goodsNumCount)&&!empty($ordersCount)){
                    foreach($goodsNumCount as $k=>$r){
                        $arr[] = array_merge($r,$ordersCount[$k]);
                    }
                    $addDatas=$arr;
                }else{
                    if(!empty($goodsNumCount)){
                        $addDatas=$goodsNumCount;
                    }else{
                        $addDatas=$goodsNumCount;
                    }
                }
                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.add_time>={0} and han_order.add_time<{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);

        $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);
            $this->reduceRefundModel($storeMemberStatisticData);
        } 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;
    }

}
