<?php

namespace Business\Order;

use DAO\Order\OrderCommonModel;
use Error\CodeConfigModel;
use Error\ErrorModel;
use Order\OrderConfirmUtil;
use Our\ApiConst;
use Our\ArrayConst;
use Our\Common;
use Our\DbNameConst;
use Our\DescribeConst;
use Our\ExpressConst;
use Our\ImageConst;
use Our\NameConst;
use Our\PageConst;
use Our\Push;
use Our\RedisHelper;

/**
 * 店铺service
 *
 * @date 2018-5-15
 * @author zhz
 */
class OrderServiceModel extends \Business\AbstractModel
{
    private $orderField = "order_id as orderId,order_sn as orderSn,store_name as storeName,evaluation_state as evaluationState,add_time as addTime,store_id as storeId,goods_amount as goodsAmount,shipping_fee as shippingFee,order_amount as orderAmount,shipping_type as shippingType,payment_type as paymentType,payment_time as paymentTime,order_state as orderState,shipping_fee as shippingFee,refund_state as refundState,order_type as orderType,is_receive_payment as isReceivePayment,gmt_update as gmtUpdate";
    private $orderGoodsField = "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,refund_state_name as refundStateName,refund_id as refundId";

    private $addressField = " mob_phone as MobPhone,tel_phone as TelPhone,address as address,area_info as areaInfo,lng,lat,address_id as addressId,subaddress as subAddress";

    private $storeField = "offline_payway as offlinePayway";

    private $orderMessageField = "order_id as orderId,order_sn as orderSn,store_name as storeName,add_time as addTime,store_id as storeId,goods_amount as goodsAmount,shipping_fee as shippingFee,order_amount as orderAmount,shipping_type as shippingType,payment_type as paymentType,order_state as orderState,shipping_fee as shippingFee,refund_state as refundState,order_type as orderType,is_receive_payment as isReceivePayment,buyer_id as buyerId,buyer_name as buyerName,accept_time as acceptTime";


    private $order;
    //地址
    private $address;
    //收货人地址
    //收货人信息
    private $orderCommon;
    //定单商品表
    private $orderGoodsList;
    private $diliveryman;
    //商店相关信息
    private $store;

    public function init()
    {

    }

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

    public function getOrderIndexWhere($memberId, $keyword, $pageIndex, $pageSize)
    {
//        $query1= array('match' => array('buyerId' => $memberId));
//        $res1['must']=$query1;
//       // $query2[]= array('match' => array('orderSn' => $keyword"));
//        $query2[]= array('match' => array('storeName' => $keyword));
//        $query2[]= array('match' => array('goodsName' => $keyword));
//        $res1['should']=$query2;
        //     $allQuery['bool']=$res1;
        $query1[] = array('match' => array('buyerId' => $memberId));
        $query1[] = array('match' => array('deleteState' => ApiConst::undeleteOrder));
        $res1['must'][0] = $query1;
        // $query2[]= array('match' => array('orderSn' => $keyword"));
        $query2[] = array('match' => array('storeName' => $keyword));
        $query2[] = array('match' => array('goodsName' => $keyword));
        $query2[] = array('wildcard' => array('orderSn' => "*{$keyword}*"));
        $res1['must'][1]['bool']['should'] = $query2;
        $allQuery['bool'] = $res1;
        // echo json_encode($allQuery);exit;
        // echo json_encode($allQuery);exit;
        //array_push($allQuery['bool'],$res2);
        // echo json_encode($allQuery);exit;
        //  echo json_encode($allQuery);exit;
        $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;
    }

    /**
     * 订单,获得订单列表
     *
     * @date 2018-5-15
     * @author ccw
     */
    public function getList($memberId, $keyWord = false, $pageIndex = ApiConst::pageIndex, $pageSize = ApiConst::pageSize, $orderState = false)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsDao = \DAO\GoodsModel::getInstance(DbNameConst::salveDBConnectName);
        //$refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::salveDBConnectName);
        if ($keyWord !== false) {
            $where = $this->getOrderIndexWhere($memberId, $keyWord, $pageIndex, $pageSize);
            if($where===false){
                return Array(
                    'orders'=>[],
                    'totalCount'=>ApiConst::zero,
                );
            }
        } else {
            $where['delete_state'] = ApiConst::undeleteOrder;

            $where['buyer_id'] = $memberId;
            //$where['lock_state'] = ApiConst::zero;

            if ($orderState != false) {
                if($orderState==ApiConst::orderStateComplete){
                    $where['evaluation_state']=ApiConst::waitEvaluation;
                    $where['order_state']=array('eq',ApiConst::orderStateComplete);
                }
                if($orderState==ApiConst::orderStateWaitRecieveOne){
                    $where['shipping_type']=array('eq',ApiConst::bySeller);
                    $where['order_state'] =array('in',array(ApiConst::orderStateWaitSend,ApiConst::orderStateWaitRecieve));
                }
                if($orderState==ApiConst::orderStateWaitSendOne){
                    $where['shipping_type']=array('eq',ApiConst::bySelf);
                    $where['order_state']=array('eq',ApiConst::orderStateWaitRecieve);
                }
              //  $where['order_state'] = array('in', explode(',', $orderState));
            }
        }

        //获得订单列表
        $orders = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'getList'), array($where, $this->orderField, $pageIndex, $pageSize, $order = array('gmt_update' => 'desc')), \Our\ApiConst::oneDaySecond, array($memberId));
        if (!empty($orders['list'])) {
            $orderIds = array_column($orders['list'], 'orderId');
            //获得订单商品列表
            if (!empty($orderIds)) {
                $orderGoods = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByOrderIds'), array($orderIds, $this->getGoodsDetailField()), \Our\ApiConst::oneDaySecond, array($memberId));
                $orderMerge = Common::intergrateOneToMany($orders['list'], $orderGoods, 'orderId', 'orderId', 'orderGoods');
                foreach ($orderMerge as &$value) {
                    $value['orderStateName'] = $orderDao->getStatusText($value);
                    $value['orderText'] = $orderDao->getText($value, ApiConst::orderListDescribe);
//                    if ($value['lock_state'] == 0) {
//                        $value['refunStateName'] = NameConst::emptyString;
//                    } else {
//                        if(!empty($value['orderGoods'])){
//
//                        }
//                        $value['refunsStateName'] = $refundReturnDao->getStatusText($value['orderId']);
//                    }
                    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'] = $orders['totalCount'];
                return $returnData;
            } else {
                return Array(
                    'orders'=>[],
                    'totalCount'=>ApiConst::zero,
                );
            }
        } else {
            return Array(
                'orders'=>[],
                'totalCount'=>ApiConst::zero,
            );
        }


    }

    public function getDeleteField()
    {
        return $this->orderField . ',delete_state as deleteState';
    }

    public function delete($memberId, $orderId)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $memberDao = \DAO\MemberModel::getInstance(DbNameConst::masterDBConnectName);
        $order = $orderDao->findByMemberIdAndOrderId($memberId, $orderId, $this->getDeleteField());
        if (empty($order)) {
            ErrorModel::throwException(CodeConfigModel::orderNotExist);
        }
        if ($orderDao->getOrderOperateState(NameConst::delete, $order)) {
            if ($orderDao->deleteByOrderId($order['orderId'])) {
                $orderDao->deleteOrderCache($memberId, $orderId);
                $memberDao->deleteTotalCache($memberId);
                return true;
            } else {
                ErrorModel::throwException(CodeConfigModel::orderDeleteError);
            }
        }else{
            ErrorModel::throwException(CodeConfigModel::notAllowCancel);
        }

    }


    private function getDeliveryManFields()
    {
        return array(
            'qrcode_path' => 'qrcodePath',
            'true_name' => 'trueName',
            'mobile' => 'mobile',
        );
    }

    /**
     * 订单,获得订单详情
     *
     * @date 2018-5-15
     * @author ccw
     */
    public function getOrderDetail($orderId)
    {
       // error_reporting(E_ALL);
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $addressDao = \DAO\AddressModel::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){
            ErrorModel::throwException(CodeConfigModel::orderNotExist);
        }
        $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,array($orderId));
        //$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);
//        if ($this->orderCommon['daddressId'] > ApiConst::zero) {
//            $this->address = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$addressDao, 'getAddressByAddressId'), array($this->orderCommon['daddressId'], $this->addressField), \Our\ApiConst::oneDaySecond);;
//            $this->address['lat'] = $this->address['lat'] ? $this->address['lat'] : ApiConst::zero;
//            $this->address['lng'] = $this->address['lng'] ? $this->address['lng'] : ApiConst::zero;
//            $this->address['subAddress'] = $this->address['subAddress'] ? $this->address['subAddress'] : '';
//        } else {
//            $this->address = new \stdClass();
//        }
        //定单商品表

        $this->orderGoodsList = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByOrderIds'), array($orderId, $this->getGoodsDetailField()), \Our\ApiConst::oneDaySecond, array($orderId));
        //商店相关信息
//         $this->store=$storeDao->get($this->order['storeId']);
//        $this->store=Common::convertUnderline($this->store[0]);
         $this->store = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$storeDao, 'getInfoById'), array($this->order['storeId'], $storeDao->detailField), \Our\ApiConst::sevenDaySecond,array($this->order['storeId']));
        $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['dlyoPickupCode'] = intval(substr($returnData['orderSn'], ApiConst::positionPickupCodeBegin));
        $returnData['paymentName'] = $orderDao->getPayTypeName($returnData['paymentType']);
        $returnData['discountAmount'] = $returnData['goodsAmount'] - $returnData['orderAmount'] + $returnData['shippingFee'];
        $returnData['orderText'] = $orderDao->getStatusDetailText($this->order);
        $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());
            if(empty($returnData['deliveryman']['qrcodePath'])){
                $returnData['deliveryman']['qrcodePath']='';
            }
        } else {
            $returnData['diliverymanId'] = ApiConst::zero;
            $returnData['deliveryman'] = new \stdClass();
        }
        $returnData['storeMemberId']=$this->store['memberId'];
        $returnData['totalGoodsNum'] = $orderGoodsDao->getGoodsCount($this->orderGoodsList);
        $returnData['offlinePayway'] = $this->store['offlinePayway'] ? $this->store['offlinePayway'] : '';
        $this->address['address']=$orderCommonDao->convertReceiveAddress($this->address['address']);
        $returnData['reciverInfo'] = $this->address;
        $returnData['reciverInfo']['lng']=!empty($returnData['reciverInfo']['lng'])?$returnData['reciverInfo']['lng']:ApiConst::zero;
        $returnData['reciverInfo']['lat']=!empty($returnData['reciverInfo']['lat'])?$returnData['reciverInfo']['lat']:ApiConst::zero;
        $refundStateName = $orderDao->getRefundText($this->order);
        $returnData['orderGoods'] = $goodsDao->convert($this->orderGoodsList, $refundStateName);
        return $returnData;
    }


    /**
     * 取消订单
     *
     * @date 2018-5-15
     * @author ccw
     */
    public function cancel($orderId, $memberId = false)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
        $order = $orderDao->findByOrderId($orderId,$orderDao->getOrderDetailField());
        //判断订单目前状态是否允许取消
        $isAllowCancel = $orderDao->isAllowCancel($order);
        if ($isAllowCancel) {
            $res = $orderDao->updateStatusByOrderId($orderId, ApiConst::orderStateCancel);
            if ($res) {
                $order['refundOrderNo']=$refundReturnDao->getRefundsn($order['storeId']);
                if($order['paymentTime']>ApiConst::zero){
                    $resultRefund=$refundReturnDao->refundMoney($order);
                    if($resultRefund){
                        $where['order_id']=$order['orderId'];
                        //$orderGoodsUpdateData['refund_state_name']='退款成功';
                        $orderGoodsUpdateData['is_refund']=ApiConst::refundSuccess;
                        $orderGoodsDao->update($where,$orderGoodsUpdateData);
                    }
                }
                \Our\RedisHelper::rpush('client_push',array('storeId'=>$order['storeId'],'type'=>ApiConst::messageWaitReceive,'op'=>NameConst::reduce,'num'=>ApiConst::one,'params'=>array('c'=>'shopkeeper','m'=>'orderDetail','orderId'=>$order['orderId'])));
                if ($memberId) {
                    $orderDao->deleteOrderCache($memberId, $orderId, $order['storeId'],true);
                    // $memberDao->fromOrderStateToOrderState($memberId,$order['order_state'],ApiConst::orderStateCancel);
                }
            }
            return $res;
        } else {
            ErrorModel::throwException(CodeConfigModel::notAllowCancel);
        }

    }

    //确认收货
    public function confirmRecieve($orderId, $memberId)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        // $orderDao->deleteOrderCache($memberId, $orderId);
        $order = $orderDao->findByOrderId($orderId);
        //$orderDao->deleteOrderCache($memberId, $orderId, $order['store_id'],true,true);
        //判断订单目前状态是否允许取消
        $isAllowConfirm = $orderDao->isAllowConfirm($order);
        if ($isAllowConfirm) {
            $res = $orderDao->updateStatusByOrderId($orderId, ApiConst::orderStateComplete, TRUE);
            if ($res) {
                if($order['shipping_type']==ApiConst::bySelf){
                    $type=ApiConst::messageWaitGet;
                }else{
                    $type=ApiConst::messageWaitSend;
                }
                \Our\RedisHelper::rpush('client_push',array('storeId'=>$order['storeId'],'type'=>$type,'op'=>NameConst::reduce,'num'=>ApiConst::one,'params'=>array('c'=>'shopkeeper','m'=>'orderDetail','orderId'=>$order['orderId'])));
                $orderDao->deleteOrderCache($memberId, $orderId, $order['store_id'],true,true);
                return true;
            } else {
                ErrorModel::throwException(CodeConfigModel::receiveError);
            }
        } else {
            ErrorModel::throwException(CodeConfigModel::notAllowComplete);
        }
    }

    public function getOrderExpressField()
    {

        return $this->orderField . ',shipping_html as shippingHtml,shipping_code as shippingCode,send_time as sendTime,shipping_sign as shippingSign,shipping_status as shippingStatus,shipping_arrival_time as shippingArrivalTime';
    }

    //获得物流信息
    public function getExpressInfo($orderId)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $orderGoods = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::salveDBConnectName);
        $expressDao = \DAO\Order\ExpressModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsCommonDao = \DAO\GoodsCommonModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsDao = \DAO\GoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $shippingExpress = $orderCommonDao->findByOrderId($orderId, 'shipping_express_id as shippingExpressId');
        if (!empty($shippingExpress)) {
            $shippingExpressInfo = $expressDao->getInfoById($shippingExpress['shippingExpressId'], $expressDao->detailField);
        } else {
            $shippingExpressInfo = new \stdClass();
        }

        $order = $orderDao->findByOrderId($orderId, $this->getOrderExpressField());
        if(empty($order)){
            return new \stdClass();
        }
        $eCode=$shippingExpressInfo['eCode'];
        $shippingCode=$order['shippingCode'];
        $order['shippingHtml']=$order['shippingHtml'] ? unserialize($order['shippingHtml']) : array();;
        $expressResult=Common::aliyunExpressApi($shippingCode,$eCode);
        if($order['shippingOver']!=ApiConst::one){
            if($expressResult['status']==ApiConst::getExpressSuccess){
                $order['shippingHtml']=$expressResult['result']['list'];
                $listData['orderId']=$order['orderId'];
                $listData['expressInfo']=$expressResult['result'];
                RedisHelper::rpush(NameConst::expressList,$listData);
            }
        }
        $orderGoods = $orderGoods->getOneByOrderId($orderId, $this->orderGoodsField);
        if (!empty($order) && !empty($orderGoods)) {
            $return['shippingCode'] = $order['shippingCode'];
            $return['expressName'] = $shippingExpressInfo['eName'];
            $return['expressImage'] = Common::getStaticFile($shippingExpressInfo['eImage'], ImageConst::expressPath);
            $return['goodsName'] = $orderGoods['goodsName'];
            $return['goodsId'] = $orderGoods['goodsId'];
            $return['goodsImage'] = \Our\ImageUtil::getGoodsImgUrl($orderGoods['goodsImage'], ArrayConst::goodsImageExt[ApiConst::goodsSmallSize]);
            $return['goodsAttr'] = $goodsDao->getFormatGoodsAttr($orderGoods['goodsSpec']);
            $return['orderPrice'] = $order['orderAmount'];
            $return['expressInfo'] = !empty($order['shippingHtml'])?$order['shippingHtml']:[];
            $return['shippingStatus'] = $order['shippingStatus'];
            $return['sendTime'] = $order['sendTime'];
            $return['rechedTime'] = $order['shippingSign'];
            $return['shippingArrivalTime'] = $order['shippingArrivalTime'];
            return $return;
        } else {
            return new \stdClass();
        }

    }

    public function pushRecieveOrder($order){
        $push = Push::getInstance();
        $push->recieveWait($order['storeId'], $order['orderId'], $order['orderSn']);
        \Our\RedisHelper::rpush('client_push',array('storeId'=>$order['storeId'],'type'=>ApiConst::messageWaitReceive,'op'=>NameConst::add,'num'=>ApiConst::one,'params'=>array('c'=>'shopkeeper','m'=>'orderDetail','orderId'=>$order['orderId'])));
        $push->sendTcpMessage();
        $messageService=\Business\Message\MessageServiceModel::getInstance(\Our\DbNameConst::masterDBConnectName);
        $messageService->addMessageCenterToDb();
    }
    //推送接单消息到店铺
    public function pushRecieveWaitOrder()
    {
        $baseConfDir = \Our\Common::getConfig('out.config');
        $savePath = $baseConfDir . \Our\PathConst::orderWaitRecieveTaskAddTime;
        $addTime = file_get_contents($savePath);
        $addTime = $addTime ? $addTime : ApiConst::zero;
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $pageBegin = PageConst::taskPageBegin;
        $push = Push::getInstance();
        do {
            $orders = $orderDao->getRecieveOrders(ApiConst::orderStateWaitConfirm, $addTime, $pageBegin, PageConst::taskPageSize);
            foreach ($orders['list'] as $order) {
                $push->recieveWait($order['storeId'], $order['orderId'], $order['orderSn']);

            }
            $pageBegin++;
        } while (!empty($orders['list']));
        $push->sendTcpMessage();
        file_put_contents($savePath, TIMESTAMP);
    }

    //推送确认收货消息到用户 和配送
    public function pushConfirmOrder()
    {
        $baseConfDir = \Our\Common::getConfig('out.config');
        $savePath = $baseConfDir . \Our\PathConst::orderConfirmTaskAddTime;
        $addTime = file_get_contents($savePath);
        $addTime = $addTime ? $addTime : ApiConst::zero;
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $qmDeliverymanLogDao = \DAO\Order\QmDeliverymanLogModel::getInstance(DbNameConst::salveDBConnectName);
        $pageBegin = PageConst::taskPageBegin;
        $push = Push::getInstance();
        do {
            $orders = $orderDao->getRecieveOrders(ApiConst::orderStateWaitRecieve, $addTime, $pageBegin, PageConst::taskPageSize, 'send_time');
            foreach ($orders['list'] as $order) {
                if($order['shippingType']==ApiConst::bySelf){
                    $push->reacheRemind($order['buyerId'], $order['orderId'], $order['orderSn']);
                }
                if($order['shippingType']==ApiConst::express && $order['shippingOver']==ApiConst::shippingOver){
                    $push->reacheRemind($order['buyerId'], $order['orderId'], $order['orderSn']);
                }
            }

            $pageBegin++;
        } while (!empty($orders['list']));
        $push->sendTcpMessage();
        file_put_contents($savePath, TIMESTAMP);
    }
    public function refundReturnMessage(){

    }
    public function changeOrderStateCancelUnconditional($orderInfo)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
         $orderGoodsDao=\DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
        // $orderGoods=$orderGoodsDao->getOrderGoodsByOrderIds($orderInfo['orderId']);
        try {
            $orderId = $orderInfo['orderId'];
            $update=array();
            $refundSn = $refundReturnDao->getRefundsn($orderInfo['storeId']);
            //生成退款记录
            $update['order_id'] = $orderInfo['orderId'];
            $update['order_sn'] = $orderInfo['orderSn'];
            $update['refund_sn'] = $refundSn;
            $update['store_id'] = $orderInfo['storeId'];
            $update['store_name'] = $orderInfo['storeName'];
            $update['buyer_id'] = $orderInfo['buyerId'];
            $update['buyer_name'] = $orderInfo['buyerName'];
            $update['goods_id'] = ApiConst::zero;
            $update['goods_name'] = '订单商品全部退款';
            $update['refund_amount'] = $orderInfo['orderAmount'];
            $update['seller_state'] = 2;
            $update['refund_state'] = 3;
            $update['goods_state'] = 5;
            $update['add_time'] = time();
            $waitDiff=(ApiConst::orderStateWaitConfirmBeyond/ApiConst::oneMinSecond);
            $update['reason_info'] = '用户付款' . $waitDiff . '分钟内，店铺未接单,自动取消订单';
            $update['buyer_message'] = '用户付款' . $waitDiff. '分钟内，店铺未接单,自动取消订单';
            $update['is_suc_refund'] = 1;
            //$res = $refundReturnDao->addRefundReturn($update);
            $res=true;
            if (!$res) {
                echo '退款记录:' . json_encode($orderInfo) . '写入失败!!' . "\r\n";
            }else{
//                $param['refundOrderNo'] = $refundSn;
//                //这个有可能多次退款的时候要变
//                $param['outTradeNo'] = $orderInfo['paySn'];
//                $param['totalFee'] = $orderInfo['orderAmount'];
//                $param['refundFee'] = $orderInfo['orderAmount'];//全额退款
//                $param['storeId']=$orderInfo['storeId'];
//                $param['buyerId']=$orderInfo['buyerId'];
//                if (intval($orderInfo['paymentType']) == ApiConst::wxAppPayType) {
//                    $wxpay = \Payment\WxPay::getInstance();
//                    $refund_return = $wxpay->refund($param);
//                    echo "微信返回:".json_encode($refund_return);
//                    if (!($refund_return['return_code'] == 'SUCCESS' && $refund_return['result_code'] == 'SUCCESS')) {
//                        echo '微信退款操作执行失败！'.$orderInfo['orderId']."\r\n";
//                        return false;
//                    }
//                } else if (intval($orderInfo['paymentType']) == ApiConst::alipay) {
//                    $aliPay=\Payment\Alipay::getInstance();
//                    $return = $aliPay->refund($param);
//                    echo "支付宝返回:".json_encode($return);
//                    $resultCode = $return->code;
//                    if(!empty($resultCode)&&$resultCode == 10000){
//                        return true;
//                    } else {
//                        echo '支付宝退款操作执行失败:'.$orderInfo['orderId']."\r\n";
//                        return false;
//                    }
//                }
                $orderInfo['refundOrderNo']=$refundSn;
                if($refundReturnDao->refundMoney($orderInfo)){
                    $where['order_id']=$orderInfo['orderId'];
                    //$orderGoodsUpdateData['refund_state_name']='退款成功';
                    $orderGoodsUpdateData['is_refund']=1;
                    $orderGoodsDao->update($where,$orderGoodsUpdateData);
                    echo " 退款操作操作成功:".$orderId;
                    return true;
                }else{
                    echo $refundReturnDao->errorMessage;
                }


            }


        } catch (Exception $e) {
           throw new \Exception($e->getMessage(),$e->getCode());
        }
    }

    public $baseDir;

    //订单任务脚本关闭订单
    public function cancelOrderTask()
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::masterDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
        $orderConfirmUtilDao=OrderConfirmUtil::getInstance(DbNameConst::masterDBConnectName);
        $beginTime = file_get_contents($this->baseDir . \Our\PathConst::orderCancelTime, TIMESTAMP);
        $beginTime = $beginTime ? $beginTime : ApiConst::zero;
        $endTime = TIMESTAMP - ApiConst::orderCancelBeyondTime;
        $orders = $orderDao->getMustCecelOrders($beginTime, $endTime, $orderDao->getOrderDetailField());
        if (!empty($orders)) {

            foreach ($orders as $order) {
                //更新订单信息
                $updateData = array('order_state' => ApiConst::orderStateCancel);
                $update = $orderDao->update(array('order_id' => $order['orderId']),$updateData);
                $updateCommonData['order_message']=DescribeConst::cancelOrderMessage;
                $res=$orderCommonDao->update(array('order_id'=>$order['orderId']),$updateCommonData);
                if(!$update || !$res){
                       echo '订单:'.$order['orderId'].'没取消成功!';
                }
                //$orderGoodsUpdateData['refund_state_name']='退款成功';
                $orderGoodsUpdateData['is_refund']=1;
                $whereOrderGoods['order_id']=$order['orderId'];
                $orderGoodsUpdateRes=$orderGoodsDao->update($whereOrderGoods,$orderGoodsUpdateData);
                if(!$orderGoodsUpdateRes){
                    echo '订单:'.$order['order_id'].'is_refund'.'没更新成功';
                }
                $orderDao->deleteOrderCache($order['buyerId'],(string)$order['orderId'],$order['storeId'],true);
            }
            $orderIds = array_column($orders, 'orderId');
            //更新商品库存
            $orderGoods = $orderGoodsDao->getOrderGoodsByOrderIds($orderIds, $this->getGoodsDetailField());
            $storeCartsList=array();
            $storeCarts=array();
            $storeCarts['storeCarts']=array();
            foreach($orderGoods as $orderGood){
                $orderGood['type']=!empty($orderGood['goodsGroup'])? \Our\ApiConst::addBundingToCart:\Our\ApiConst::addGoodsToCart;
                $orderGood['goodsNum']=$orderGood['goodsNum'];
                $orderGood['goodsList']=\Our\Common::isSerialized($orderGood['goodsGroup'])?unserialize($orderGood['goodsGroup']):array();
                array_push($storeCarts['storeCarts'],$orderGood);
            }
            if(!empty($storeCarts['storeCarts'])){
                array_push($storeCartsList,$storeCarts);
            }
            // $orderDao->updateNotRecieveOrders(ApiConst::orderStateWaitConfirm, ApiConst::orderStateClose, 'add_time', ApiConst::orderStateWaitConfirmBeyond, $this->orderMessageField);
            try{
                $orderConfirmUtilDao->updateGoodsStorage($storeCartsList,\Our\ApiConst::plus);
            }catch(\Exception $ex){
                $orderidsStr=implode(',',array_column($orders,'orderId'));
                echo '商品库存更新失败:'.$ex->getMessage().$ex->getCode().":".$orderidsStr;
            }
//            //发送消息
//            $push = Push::getInstance();
//            $push->pushOrderCloseMessage($orders);

        }
        file_put_contents($this->baseDir . \Our\PathConst::orderCancelTime, $endTime);
    }
    public function changeOrderStatus()
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
        $orderConfirmUtilDao=OrderConfirmUtil::getInstance(DbNameConst::masterDBConnectName);
        $beginTime = file_get_contents($this->baseDir . \Our\PathConst::orderCloseWaitRecieveOrder, TIMESTAMP);
        $beginTime = $beginTime ? $beginTime : ApiConst::zero;
        $endTime = TIMESTAMP - ApiConst::orderStateWaitConfirmBeyond;
       // $beginTime=0;
        $orders = $orderDao->getMustCecelRecieveOrders($beginTime, $endTime, $orderDao->getOrderDetailField());
        if (!empty($orders)) {
                foreach ($orders as $order) {
                    //更新订单信息
                    $updateData = array('order_state' => ApiConst::orderStateClose,'refund_amount'=>$order['orderAmount']);
                    $update = $orderDao->update(array('order_id' => $order['orderId']),$updateData);
                    if($update){
                        if ($order['paymentTime'] > ApiConst::zero && in_array($order['paymentType'], ArrayConst::orderPayTypeOnlines)) {
                            $this->changeOrderStateCancelUnconditional($order);
                        }
                    }
                    $orderDao->deleteOrderCache($order['buyerId'],(string)$order['orderId'],$order['storeId'],true);
                }

            $orderIds = array_column($orders, 'orderId');
            //更新商品库存
            $orderGoods = $orderGoodsDao->getOrderGoodsByOrderIds($orderIds, $this->getGoodsDetailField());
            $storeCartsList=array();
            $storeCarts=array();
            $storeCarts['storeCarts']=array();
            foreach($orderGoods as $orderGood){
                $orderGood['type']=!empty($orderGood['goodsGroup'])? \Our\ApiConst::addBundingToCart:\Our\ApiConst::addGoodsToCart;
                $orderGood['goodsNum']=$orderGood['goodsNum'];
                $orderGood['goodsList']=\Our\Common::isSerialized($orderGood['goodsGroup'])?unserialize($orderGood['goodsGroup']):array();
                array_push($storeCarts['storeCarts'],$orderGood);
            }
            if(!empty($storeCarts['storeCarts'])){
                array_push($storeCartsList,$storeCarts);
            }
            // $orderDao->updateNotRecieveOrders(ApiConst::orderStateWaitConfirm, ApiConst::orderStateClose, 'add_time', ApiConst::orderStateWaitConfirmBeyond, $this->orderMessageField);
            try{
                $orderConfirmUtilDao->updateGoodsStorage($storeCartsList,\Our\ApiConst::plus);
            }catch(\Exception $ex){
                $orderidsStr=implode(',',array_column($orders,'orderId'));
                echo '商品库存更新失败:'.$ex->getMessage().$ex->getCode().":".$orderidsStr;
            }
            //发送消息
            $push = Push::getInstance();
            $push->pushOrderCloseMessage($orders);

        }
        file_put_contents($this->baseDir . \Our\PathConst::orderCloseWaitRecieveOrder, $endTime);
    }

    //订单任务脚本自动确认收货
    public function canformRecieveOrder()
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $qmDeliverymanLogsDao = \DAO\Order\QmDeliverymanLogModel::getInstance(DbNameConst::masterDBConnectName);
        $orders = $orderDao->getOrdersByOrderState(ApiConst::orderStateWaitRecieve, 'accept_time', ApiConst::orderWaitRecieveTwentyFourHours, $this->orderMessageField, array(ApiConst::bySeller, ApiConst::express));
        if (!empty($orders)) {
            $sellerTypeOrderIds = $orderDao->getShippingTypeSellerOrdersByOrders($orders);
            $qmDeliverymanLogs = $qmDeliverymanLogsDao->getFinishDeliveryByOrderId($sellerTypeOrderIds);
            if (!empty($qmDeliverymanLogs)) {
                $qmDeliverymanLogsOrderIds = array_column($qmDeliverymanLogs, 'orderId', 'orderId');
            }
            $sellerOrderIds = array();
            $expressOrderIds = array();
            foreach ($orders as $order) {
                //如果是配送订单
                if ($order['shippingType'] == ApiConst::bySeller) {
                    if (isset($qmDeliverymanLogsOrderIds[$order['orderId']])) {
                        array_push($sellerOrderIds, $order['orderId']);
                        $orderDao->deleteOrderCache($order['buyerId'], $order['orderId'], $order['storeId'],true);
                    }
                } else {
                    $limitTime = TIMESTAMP - ApiConst::orderWaitRecieveThreeDays;
                    if ($order['acceptTime'] < $limitTime) {
                        array_push($expressOrderIds, $order['orderId']);
                        $orderDao->deleteOrderCache($order['buyerId'], $order['orderId'], $order['storeId'],true);
                    }
                }
                \Our\RedisHelper::memberTotalFromStateToState($order['buyerId'], $order['orderState'], ApiConst::orderStateComplete);
            }
            $updateOrderIds = array_merge($sellerOrderIds, $expressOrderIds);
            echo '更新的订单id为：';
            var_dump($updateOrderIds);
            $orderDao->updateStatusByOrderId($updateOrderIds, ApiConst::orderStateComplete, TRUE);
        }
    }

    public function updateOrderExpress()
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::salveDBConnectName);
        while($result=RedisHelper::lpop(NameConst::expressList)){
            if($result){
                $expressInfo=$result['expressInfo'];
            }
            if ($expressInfo['deliverystatus'] == 3) {
                $data['shipping_over'] = 1;
            }
            if ($expressInfo['list']) {
                $data['shipping_sign'] = strtotime($expressInfo['list'][0]['time']);//签收时间
                $data['shipping_html'] = serialize($expressInfo['list']);
                $data['shipping_status'] = $expressInfo['deliverystatus'];
            }
            //$output;
            //更新订单物流
            $result = $orderDao->update(array('order_id' => $result['orderId']), $data);
            if ($result !== false) {
                echo '物流信息更新成功订单号:' . $result['orderId'] . "\r\n";
            }
        };
    }

    /**
     * 订单,获得配送订单列表
     *
     * @date 2018-5-15
     * @author ccw
     */
    public function getQmDeliveryLogList($memberId, $type = ApiConst::orderTypeBuy, $pageIndex = ApiConst::pageIndex, $pageSize = ApiConst::pageSize)
    {
        $qmDeliveryLogDao = \DAO\Order\QmDeliverymanLogModel::getInstance(DbNameConst::salveDBConnectName);
        $qmDeliveryMan=\DAO\Order\DiliverymanModel::getInstance(DbNameConst::salveDBConnectName);
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::salveDBConnectName);
        $memberDao = \DAO\MemberModel::getInstance(DbNameConst::salveDBConnectName);
        $qmMans=$qmDeliveryMan->getListByMemberId($memberId);
        $diliverymanIds=array_column($qmMans,'id');
        $diliverymanId = $memberDao->getInfo($memberId, 'diliveryman_id');
        if (empty($diliverymanIds)) {
            ErrorModel::throwException(CodeConfigModel::commonError);
        }
        $qmDeliveryLogList = $qmDeliveryLogDao->getListByDeliverymanIdAndTypeCache($diliverymanIds, $type, $pageIndex, $pageSize,array('get_time' => 'desc'),$memberId);
        $orderIds = array_column($qmDeliveryLogList['list'], 'orderId');
      //  echo json_encode($orderIds);exit;
       // $where['delete_state'] = ApiConst::undeleteOrder;

        $orderIds=implode(',',$orderIds);


        //获得订单商品列表
        if (!empty($orderIds)) {
            $where =Common::format(" order_id in({0})",$orderIds);
            // $where['lock_state'] = ApiConst::zero;

            //获得订单列表
            //  $orders=$orderDao->getList($where, $this->orderField, $pageIndex, $pageSize, $order = array('add_time' => 'desc'));
            $orders = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'getList'), array($where, $this->orderField, ApiConst::zero, $pageSize, $order = array('add_time' => 'desc')), \Our\ApiConst::oneDaySecond, array($diliverymanId));
            $goodsDao = \DAO\GoodsModel::getInstance();
            $orderIds = array_column($orders['list'], 'orderId');
            $orderCommons = $orderCommonDao->getAllByOrderIdsCache($orderIds, $diliverymanId, $orderCommonDao->orderCommonField);
            $orderGoods = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByOrderIds'), array($orderIds, $this->getGoodsDetailField()), \Our\ApiConst::oneDaySecond, array($diliverymanId.'_'));
            $orderMerge = Common::intergrateOneToMany($orders['list'], $orderGoods, 'orderId', 'orderId', 'orderGoods');
            $orderMerge = Common::intergrateOneToOne($orderMerge, $orderCommons, 'orderId', 'orderId');
            $orderMerge = $orderDao->convertOrderList($orderMerge);
            $convertResult = array();
            //$orderGoods = $goodsDao->convert($orderGoods);
            foreach ($qmDeliveryLogList['list'] as &$value) {
                $delivery = $orderMerge[$value['orderId']];
                $delivery['id'] = $value['id'];
                $delivery['reciverInfo'] = unserialize($delivery['reciverInfo']);
                $delivery['mobPhone'] = $delivery['reciverInfo']['mob_phone'];
                $delivery['getTime'] = $value['getTime'];
                $delivery['finishTime'] = $value['finishTime'];
                $delivery['mobPhone'] = $delivery['mobPhone'] ? $delivery['mobPhone'] : '';
                $delivery['finishTime'] = $delivery['finishTime'] ? $delivery['finishTime'] : ApiConst::zero;
                $delivery['orderGoods'] = !empty($goodsDao->convert($orderMerge[$value['orderId']]['orderGoods']))?$goodsDao->convert($orderMerge[$value['orderId']]['orderGoods']):array();
                $delivery['street'] =$orderCommonDao->convertReceiveAddress($delivery['reciverInfo']['address']);
                $delivery['lng'] = $delivery['reciverInfo']['lng'] ? $delivery['reciverInfo']['lng'] : 0.0;
                $delivery['lat'] = $delivery['reciverInfo']['lat'] ? $delivery['reciverInfo']['lat'] : 0.0;
                $delivery['subAddress'] = isset($delivery['reciverInfo']['sub_address']) ? $delivery['reciverInfo']['sub_address'] : '';
                $delivery['distributionFee']=$value['distributionFee'];
                unset($delivery['goodsAmount']);
               // unset($delivery['orderState']);
                unset($delivery['refundState']);
                unset($delivery['goodsAmount']);
                unset($delivery['reciverInfo']);
                array_push($convertResult, $delivery);
            }
            $returnData['orders'] = $convertResult;
            $returnData['totalCount'] = $orders['totalCount'];
            return $returnData;
        } else {
            return new \stdClass();
        }

    }

    public function updateOrderAmount($storeId,$orderId,$newOrderAmount,$memberName)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $orderLogDao=\DAO\Order\OrderLogModel::getInstance(DbNameConst::masterDBConnectName);
        $orderDetail=$orderDao->getByOrderId($orderId,$orderDao->getOrderDetailField());
        $orderDetail=$orderDetail[ApiConst::arrBegin];
        if($orderDetail['storeId']!=$storeId){
            ErrorModel::throwException(CodeConfigModel::orderNotExist);
        }
        if($orderDetail['isReceivePayment'] != ApiConst::noreceivePayment){
            ErrorModel::throwException(CodeConfigModel::notAllowUpdataOrderAmount);
        }
        $data['order_amount']=$newOrderAmount;
        $res=$orderDao->updateByOrderId($data,$orderId);
        $orderLogDao->add($orderDetail['orderId'],ArrayConst::logMsgType[ApiConst::sellerUpdateOrderAmount],DescribeConst::sellerLog,$memberName,$orderDetail['orderState']);
        return $res;
    }

    /**
     * 获得配送详情
     *
     * @date 2018-5-15
     * @author ccw
     */
    public function getDeliveryDetail($deliveryId)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $addressDao = \DAO\AddressModel::getInstance(DbNameConst::salveDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::salveDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $diliverymanDao = \DAO\Order\DiliverymanModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsDao = \DAO\GoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $qmDeliverymanLog = \DAO\Order\QmDeliverymanLogModel::getInstance(DbNameConst::salveDBConnectName);
        $storeDao = \DAO\StoreModel::getInstance(DbNameConst::salveDBConnectName);
        $delivery = $qmDeliverymanLog->findByIdCache($deliveryId);
        if (empty($delivery)) {
            ErrorModel::throwException(CodeConfigModel::notExsitDeliver);
        }
        $orderId = $delivery['orderId'];
        //订单

        $order = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'findByOrderId'), array($orderId), \Our\ApiConst::oneDaySecond,array($orderId));
        if (empty($order)) {
            ErrorModel::throwException(CodeConfigModel::notExsitOrder);
        }
        $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);
        $reciverInfo = unserialize($this->orderCommon['reciverInfo']);
        //定单商品表
        $this->orderGoodsList = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByOrderIds'), array($orderId, $this->getGoodsDetailField()), \Our\ApiConst::oneDaySecond);
        if (empty($this->orderGoodsList)) {
            ErrorModel::throwException(CodeConfigModel::notExistOrderGoods);
        }

        //商店相关信息
        $this->store = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$storeDao, 'getInfoById'), array($this->order['storeId'],$storeDao->detailField), \Our\ApiConst::oneDaySecond);
        $orderGoods = $goodsDao->convert($this->orderGoodsList);

        if (empty($orderGoods)) {
            $orderGoods = array();
        }
        if($delivery['deliveryState']==ApiConst::deliveryStateWait||$delivery['deliveryState']==ApiConst::deliveryStateWaitTen){
            $delivery['deliveryState']=ApiConst::deliveryStateWait;
        }
        // $reciverInfo['sub_address']
        $returnData = array(
            'orderId' => $this->order['orderId'],
            'storeName' => $this->order['storeName'],
            'orderSn' => $this->order['orderSn'],
            'orderAmount' => $this->order['orderAmount'],
            'deliveryState' => $delivery['deliveryState'],
            'orderType' => $delivery['orderType'],
            'id' => $deliveryId,
            'finishTime' => $delivery['finishTime'],
            'getTime' => $delivery['getTime'],
            'reciverName' => $this->orderCommon['reciverName'],
            'mobPhone' => $reciverInfo['mob_phone'],
            'street' =>$orderCommonDao->convertReceiveAddress($reciverInfo['address']),
            'lng' => isset($reciverInfo['lng']) ? $reciverInfo['lng'] : ApiConst::zero,
            'lat' => isset($reciverInfo['lat']) ? $reciverInfo['lat'] : ApiConst::zero,
            'subAddress' => isset($reciverInfo['sub_address'])?$reciverInfo['sub_address']:'',
            'orderGoods' => $orderGoods,
            'shippingFee' => $this->order['shippingFee'],
            'distributionFee'=>$delivery['distributionFee'],
            'isReceivePayment'=>$this->order['isReceivePayment']

        );
        return $returnData;
    }

//确认送达操作
    public function finishDeliveryOrder($id, $memberid)
    {
        $memberDao = \DAO\MemberModel::getInstance(DbNameConst::masterDBConnectName);
        $qmDeliverymanLogDao = \DAO\Order\QmDeliverymanLogModel::getInstance(DbNameConst::masterDBConnectName);
        //$deliverymanId = $memberDao->getInfo($memberid, 'diliveryman_id');
        $qmDeliveryManLog = $qmDeliverymanLogDao->findById($id);
        if ($qmDeliveryManLog['deliveryState'] == ApiConst::deliveryStateWait && $qmDeliveryManLog['id'] == $id) {
            $updateResult = $qmDeliverymanLogDao->updateStatusById($id);
            $orderDao = \DAO\Order\OrderModel::getInstance();
            $order = $orderDao->findByOrderId($qmDeliveryManLog['orderId'], $orderDao->getOrderDetailField());
                if ($updateResult) {
                    $push = Push::getInstance();
                    $push->reacheRemind($order['buyerId'], $order['orderId'], $order['orderSn']);
                    $push->sendTcpMessage();
                }
            $orderDao->deleteOrderCache($memberid, $qmDeliveryManLog['orderId'], $order['storeId'],true,true,true,$memberid);
            $qmDeliverymanLogDao->deleteOrderCache($memberid, $id);
            return $updateResult;
        } else {
            return false;
        }
    }

    /**
     * @param $data
     * @param $memberId
     */
    public function getOrderPayResult($data, $memberId)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance();
        $orderList = $orderDao->getListByCon(array('pay_sn' => $data['paySn'], 'buyer_id' => $memberId));
        if (!$orderList) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::noOrderListForPaySn);
        }
        $return = array();
        $totalOrderAmount = array_sum(array_column($orderList, 'order_amount'));
        $orderTips = \Our\DescribeConst::paySuccessTips;
        $orderSubTips = \Our\DescribeConst::paySuccessSubTips;
        $orderContents = array();
        $storeDao = \DAO\StoreModel::getInstance();
        $orderIds = array();
        $orderNos = array();
        $orderState = \Our\ApiConst::one;
        foreach ($orderList as $order) {
            $orderNos[] = $order['order_sn'];
            if ($order['order_state'] == \Our\ApiConst::orderStateWaitPay) {
                $orderTips = \Our\DescribeConst::payFailedTips;
                $orderSubTips = \Our\DescribeConst::payFailedSubTips;
                $orderState = \Our\ApiConst::zero;
                break;
            } else if (($order['payment_type'] == \Our\ApiConst::payOffline||$order['payment_type'] == \Our\ApiConst::payAog) && $order['order_state'] == \Our\ApiConst::orderStateWaitConfirm) {//已下单的待线上支付订单
                $orderTips = \Our\DescribeConst::addOrderSuccessTips;
                $store = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$storeDao, 'getInfoById'), array($order['store_id']), \Our\ApiConst::oneHour);
                $orderContent['storeName'] = $store['store_name'];
                if ($order['payment_type'] == \Our\ApiConst::payOffline) {
                    $orderContent['payway'] = $store['offline_payway'];
                } else if ($order['payment_type'] == \Our\ApiConst::payAog) {
                    $orderContent['payway'] = \Our\DescribeConst::afterPay;
                }
                $orderContent['orderAmount'] = $order['order_amount'];
                $orderContents[]=$orderContent;
            }
            $orderIds[] = $order['order_id'];
        }
        $waitOnelinePayAmount = \Our\ApiConst::zero;
        if($orderState==\Our\ApiConst::zero){
            foreach ($orderList as $order) {
                if ($order['order_state'] == \Our\ApiConst::orderStateWaitPay) {
                    $waitOnelinePayAmount += $order['order_amount'];
                }
            }
        }
        $return['orderState'] = $orderState;
        if(isset($data['wxLitePayFlag'])&&$data['wxLitePayFlag']==\Our\ApiConst::one){
            $return['paySn'] = $data['paySn'];
            if(!$orderState){
                $orderConfirmUtil = \Order\OrderConfirmUtil::getInstance();
                $paySn = $orderConfirmUtil->makeNewPaySnForOrderWithOldPaySn($data['paySn'],$memberId);
                $return['paySn'] = $paySn;
            }
        }

        $return['orderNos'] = $orderNos;
        $return['totalOrderAmount'] = $totalOrderAmount;
        $return['waitOnlinePayAmount'] = $waitOnelinePayAmount;
        $return['orderTips'] = $orderTips;
        $return['orderSubTips'] = $orderSubTips;
        $return['orderContents'] = $orderContents;
        $return['coupons'] = $this->getGiftCouponsByOrderIds($orderIds, $memberId);
        return $return;
    }


    /**
     * 获取当前订单是否有可用优惠券order
     * @param $orderIds
     * @param $memberId
     * @return array
     * @throws \Our\Exception
     */
    public function getGiftCouponsByOrderIds($orderIds, $memberId)
    {
        $returnCoupons = array();
        if ($orderIds) {
            $memberCouponDao = \DAO\Coupon\MemberCouponModel::getInstance();
            $whereSql = ' coupon_state =' . \Our\ApiConst::couponUnused . ' and member_id =' . $memberId . ' and out_time > ' . time() . ' and gift_order_id in (' . implode(',', $orderIds) . ')';
            $memberCouponArray = $memberCouponDao->getMemberCouponsByMemberId($whereSql, $memberId);
            if ($memberCouponArray) {
                $couponDao = \DAO\Coupon\CouponModel::getInstance();
                $couponIds = array_column($memberCouponArray, 'coupon_id');
                if ($couponIds) {
                    $couponDao->setDb();
                    $coupons = $couponDao->getListByCouponIds($couponIds, $memberId);
                    $storeDao = \DAO\StoreModel::getInstance();
                    if ($coupons) {
                        foreach ($coupons as $temp) {
                            $couponList[$temp['id']] = $temp;
                        }
                        foreach ($memberCouponArray as $memberCoupon) {
                            $coupon = $couponList[$memberCoupon['coupon_id']];

                            $temp = array();
                            $temp['type'] = $coupon['coupon_type'];
                            $temp['couponId'] = $coupon['id'];
                            $orderAmount = intval($coupon['order_amount']);
                            if ($coupon['type'] == \Our\ApiConst::noLimitCoupon) {//无门槛优惠券
                                $temp['type'] = \Our\ApiConst::noLimitCouponType;
                                $temp['title'] = intval($coupon['cash_money']);
                                $temp['subTitle'] = \Our\DescribeConst::noLimitCoupon;
                            } else if ($coupon['coupon_type'] == \Our\ApiConst::fullMinusCouponType) {//满额减免券
                                $temp['title'] = intval($coupon['cash_money']);
                                $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponFullAvailable, $orderAmount);
                            } else if ($coupon['coupon_type'] == \Our\ApiConst::discountCouponType) {
                                $temp['title'] = $coupon['discount'];
                                if($orderAmount>0){
                                    $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponTitleFullDiscount,$orderAmount,$coupon['discount']);
                                }else{
                                    if(in_array($coupon['type'],array(\Our\ApiConst::goodsCoupon,\Our\ApiConst::goodsClassCoupon))){
                                        $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponDiscount , $coupon['discount']);
                                    }else{
                                        $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponTitleFullDiscountNoAmoutLimit , $coupon['discount']);
                                    }
                                }
                            } else if ($coupon['coupon_type'] == \Our\ApiConst::fullForCouponCouponType) {
                                $temp['title'] = \Our\DescribeConst::specialCoupon;
                                $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponFullForCoupon, $orderAmount);
                            } else if ($coupon['coupon_type'] == \Our\ApiConst::fullForGiftCouponType) {
                                $temp['title'] = \Our\DescribeConst::specialCoupon;
                                $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponFullForGift, $orderAmount);
                            }
                            $temp['storeId'] = $coupon['store_id'];
                            if ($temp['storeId']) {
                                $storeInfo = $storeDao->get($temp['storeId'],false);
                                if (!$storeInfo) {
                                    continue;
                                }
                                $temp['storeName'] = $storeInfo['store_name'];
                            } else {
                                $temp['storeName'] = \Our\DescribeConst::wholePlatform;
                            }
                            $temp['startTime'] = $memberCoupon['add_time'];
                            $temp['endTime'] = $memberCoupon['out_time'];
                            $returnCoupons[] = $temp;
                        }
                    }
                }

            }

        }
        return $returnCoupons;
    }

    public function goToPay($memberId, $orderId)
    {
        $this->checkOrderForPay($memberId, $orderId);
        $orderConfirmUtil = \Order\OrderConfirmUtil::getInstance();
        $paySn = $orderConfirmUtil->makeNewPaySnForOrderWithOrderId($orderId, $memberId);
        return $paySn;
    }

    public function checkOrderForPay($memberId, $orderId)
    {
        if (!$orderId) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptyOrderIdForPay);
        }
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $order = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'findByOrderId'), array($orderId), \Our\ApiConst::oneDaySecond,array($orderId));
        if (!$order) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptyOrderForPay);
        }
        if ($order['buyer_id'] != $memberId) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::noRightForOrder);
        }
        if (!($order['payment_type'] == \Our\ApiConst::payOnline && $order['order_state'] == \Our\ApiConst::orderStateWaitPay)) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::wrongPayForOrder);
        }
        return $order;
    }

    /**
     * 类实例
     *
     * @var \DAO\UserModel
     */
    private static $_instance = null;

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

        return self::$_instance;
    }
}
