<?php

namespace Business\Order;

use Error\CodeConfigModel;
use Error\ErrorModel;
use OSS\OssClient;
use Our\ApiConst;
use Our\ArrayConst;
use Our\Common;
use Our\DbNameConst;
use Our\DescribeConst;
use Our\ImageConst;
use Our\ImageUtil;
use Our\NameConst;
use Our\OrderConst;

/**
 * 店铺service
 *
 * @date 2018-5-15
 * @author zhz
 */
class RefundServiceModel extends \Business\AbstractModel
{
    private $orderField = "buyer_id as buyerId,buyer_name as buyerName,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,need_shipping_fee as needShippingFee,payment_code as paymentCode,delay_time as delayTime,gmt_update as gmtUpdate";
    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,refund_id as refundId";
    private $refundOrderGoodsField = "rec_id as recId,goods_id as goodsId,goods_name as goodsName,goods_num as goodsNum,goods_image as goodsImage,goods_price as goodsPrice,goods_pay_price as goodsPayPrice,goods_spec as goodsSpec,goods_group as goodsGroup";

    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 $daddressField = "address_id as addressId,store_id as storeId,seller_name as sellerName,area_id as areaId,city_id as cityId,area_info as areaInfo,address,telphone,company,is_store_address as isStoreAddress,is_default as isDefault";
    private $orderCommonField = " reciver_name as reciverName,reciver_info as reciverInfo,daddress_id as daddressId";
    private $storeField = "offline_payway as offlinePayway";

    private $refunReasonField = 'reason_id as reasonId,reason_info as reasonInfo,sort';
    //获得退款详情字段
    private $refundReturnField = 'refund_id as refundId,order_id as orderId,order_sn as orderSn,refund_sn as refundSn,store_id as storeId,store_name as storeName,seller_state as sellerState,goods_id as goodsId,order_goods_id as orderGoodsId,goods_name as goodsName,goods_num as goodsNum,refund_amount as refundAmount,goods_image as goodsImage,refund_type as refundType,refund_state as refundState,return_type as returnType,add_time as addTime,seller_time as sellerTime,admin_time as adminTime,reason_info as reasonInfo,pic_info as picInfo,buyer_message as buyerMessage,seller_message as sellerMessage,admin_message adminMessage,express_id as expressId,invoice_no as invoiceNo,ship_time as shipTime,delay_time as delayTime,receive_time as receiveTime,shipping_over as shippingOver,shipping_sign as shippingSign,shipping_html as shippingHtml,is_suc_refund as isSucRefund,refund_shipping_type as refundShippingType,address_id as addressId,diliveryman_id as diliverymanId,is_platform_in as isPlatformIn,platform_in_reason as platformInReason,platform_state as platformState,seller_state as sellerState,return_type as returnType,refund_shipping_type as refundShippingType,buyer_refund_amount as buyerRefundAmount,reason_id as reasonId,receive_message as receiveMessage,goods_state as goodsState';

    private $storeRefundReturnField = 'refund_id as refundId,order_id as orderId,order_sn as orderSn,refund_sn as refundSn,store_id as storeId,store_name as storeName,seller_state as sellerState,goods_id as goodsId,order_goods_id as orderGoodsId,goods_name as goodsName,goods_num as goodsNum,refund_amount as refundAmount,buyer_refund_amount as buyerRefundAmount,goods_image as goodsImage,refund_type as refundType,refund_state as refundState,return_type as returnType,add_time as addTime,seller_time as sellerTime,admin_time as adminTime,reason_id as reasonId,reason_info as reasonInfo,pic_info as picInfo,buyer_message as buyerMessage,seller_message as sellerMessage,admin_message adminMessage,express_id as expressId,invoice_no as invoiceNo,ship_time as shipTime,delay_time as delayTime,receive_time as receiveTime,receive_message as receiveMessage,shipping_over as shippingOver,shipping_sign as shippingSign,shipping_html as shippingHtml,is_suc_refund as isSucRefund,refund_shipping_type as refundShippingType,address_id as addressId,diliveryman_id as diliverymanId,is_platform_in as isPlatformIn,platform_in_reason as platformInReason,platform_state as platformState,return_type as returnType,refund_shipping_type as refundShippingType,goods_state as goodsState';


    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_spec as goodsSpec ';
    }
    /**
     * 订单处理天数
     *
     */
    private function getMaxDay($day_type = 'all') {
        $max_data = array(
            'order_refund' => 15,//收货完成后可以申请退款退货
            'refund_confirm' => 7,//卖家不处理退款退货申请时按同意处理
            'return_confirm' => 7,//卖家不处理收货时按弃货处理
            'return_delay' => 5//退货的商品发货多少天以后才可以选择没收到
        );
        if ($day_type == 'all') return $max_data;//返回所有
        if (intval($max_data[$day_type]) < 1) $max_data[$day_type] = 1;//最小的值设置为1
        return $max_data[$day_type];
    }

    /**
     * 修改收货时间
     * @param $storeId
     * @param $refundId
     * @param $receiveTime
     */
    public function setReceiveTime($storeId, $refundId, $receiveTime) {
        if($receiveTime < TIMESTAMP){
            ErrorModel::throwException(CodeConfigModel::beyondRecieverTime);
        }
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
        $storeDao=\DAO\StoreModel::getInstance(DbNameConst::masterDBConnectName);
        $whereRefund  = array();
        $whereRefund['store_id']= $storeId;
        $whereRefund['refund_id']= $refundId;
        $refund = $refundReturnDao->find($whereRefund);

        if(!$refund) {  //未知的退款信息
            ErrorModel::throwException(CodeConfigModel::notExistRefund);
        }

        $state = $refundReturnDao->update(array('refund_id'=> $refundId), array('receive_time'=> $receiveTime));
        $storeDao->deleteStoreRefundCache($storeId);
        if(!$state){
            return false;
        }
        return true;
    }

    /**
     * 退货收货处理
     * @param $storeId
     * @param $returnId
     * @param int $goodsState
     */
    public function receive($storeId, $sellerId, $sellerName, $returnId, $goodsState= 4)
    {
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $whereRefund  = array();
        $whereRefund['store_id']= $storeId;
        $whereRefund['refund_id']= $returnId;
        $refund = $refundReturnDao->find($whereRefund);
        $return_delay = $this->getMaxDay('return_delay');//发货默认5天后才能选择没收到
        $delay_time = TIMESTAMP - $refund['delay_time'] - 60*60*24*$return_delay;
//        if (($refund['seller_state'] != '2' && $refund['platform_state'] != '1') || $refund['goods_state'] != '2') {//检查状态,防止页面刷新不及时造成数据错误
//            return false;
//        }
        $refund_array = array();
        if ($goodsState == '3' && $delay_time > 0) {
            $refund_array['goods_state'] = 3;
        } else {
            $refund_array['receive_time'] = TIMESTAMP;
            $refund_array['receive_message'] = '确认收货完成';
            $refund_array['refund_state'] = '3';//状态:1为处理中,2为待管理员处理,3为已完成
            $refund_array['goods_state'] = 4;
            $refund_array['shipping_over']=1;
        }
        $refundReturnDao->db->doTransaction();
        $state = $refundReturnDao->editRefundReturn($whereRefund, $refund_array);
        if($state){ //退款记录成功

            //记录操作日志
            $sellerLogDAO = \DAO\SellerLogModel::getInstance();
            $sellerLogDAO->record('退货确认收货，退货编号：'.$refund['refund_sn'], array('seller_id'=>$sellerId, 'seller_name'=>$sellerName, 'store_id'=>$storeId));

            if($refund_array['goods_state'] == 4) { //同意
                // add by ky start
                //检测该店铺是否开启直接退款功能
                $storeDAO = \DAO\StoreModel::getInstance();
                $is_direct_refund = $storeDAO->getInfoById($storeId, 'is_direct_refund', 'is_direct_refund');
                if($is_direct_refund==1) {   //支持直接退款
                    //获取订单
                    $order_id = $refund['order_id'];
                    $order_info = $orderDao->find(array('order_id' => $order_id));

                    $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
                    //退款 检测该订单是否为线上支付
                    if ($refund['refund_amount'] > 0) {
                        $payment_type = $order_info['payment_type'];
                        if (!in_array($payment_type, array(0, 2))) {
                            $state = $refundReturnDao->storeRefund(array_merge($order_info, array('refund_order_no' => $refund['order_sn'], 'refund_amount' => $refund['refund_amount'])));
                            if (!$state) {
                                ErrorModel::throwException(CodeConfigModel::refundMoneyError);
                                //throw new Exception('更新订单信息失败');
                                $refundReturnDao->db->doRollback();
                                return false;
                            }
                        }
                    }
                    $refundUpdate = array('is_suc_refund' => 1, 'gmt_update' => TIMESTAMP, 'refund_state' => 3);
                    $res = $refundReturnDao->update(array('refund_id' => $refund['refund_id']), $refundUpdate);
                    if (!$res) {
                        ErrorModel::throwException(CodeConfigModel::refundWriteError);
                        $refundReturnDao->db->doRollback();
                        //                                showDialog('退款成功,退款表写入失败,请联系工作人员!',$reload,'error');
                        return false;
                    }
                    $result = $orderGoodsDao->update(array('rec_id' => $refund['order_goods_id']), array('refund_state_name'=>'退款成功', 'gmt_update' => TIMESTAMP));
                    if (!$result) {
                        $refundReturnDao->db->doRollback();
                        //                            showDialog('refund_state_name',$reload,'error');
                        return false;
                    }
                }
            }
            \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(),  array(&$refundReturnDao, 'getList'), array(), array($refund['store_id']));
            $refundReturnDao->deleteRefundCache($refund['buyer_id'], $refund['refund_id']);
            $orderDao->deleteOrderCache($refund['buyer_id'], $refund['order_id'], $refund['store_id']);
            $storeDAO->deleteStoreRefundCache($refund['store_id'],$refund['order_id']);
            $orderService=\Business\Order\OrderServiceModel::getInstance();
            $orderService->updateOrderGoodsStoregeByOrderIds($refund['order_id'],$refund['order_goods_id']);
            $refundReturnDao->db->doCommit();
            $push=\Our\Push::getInstance();
            $pushData=array('storeId'=>$storeId,
                'type'=>ApiConst::messageRefund,
                'waitReceiveCount'=>ApiConst::zero,
                'waitDeliveryCount'=>ApiConst::zero,
                'waitGetCount'=>ApiConst::zero,
                'orderCount'=>ApiConst::zero,
                'waitRefundProccessCount'=>ApiConst::zero,
                'waitRefundReceiveCount'=>ApiConst::reduceOne,
                'refundCount'=>ApiConst::reduceOne,
                'alertCount'=>ApiConst::zero,
                'params'=>array('c'=>'shopkeeper',
                    'm'=>'orderDetail',
                    'refundId'=>$refund['refund_id']));
            $push->addOneToClient($pushData);
            $push->sendTcpMessage();
            return true;
        }
        $refundReturnDao->db->doRollback();
        return false;

    }

    public function makeRefund($storeId,$refundId){
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
        $returnDetail=$refundReturnDao->findByRefundId($refundId,$refundReturnDao->refundDetailField);
        $storeDao=\DAO\StoreModel::getInstance(DbNameConst::masterDBConnectName);
        if($returnDetail['storeId']!=$storeId){
            ErrorModel::throwException(CodeConfigModel::notExistRefund);
        }$updateData=array();
        $updateData['is_suc_refund']=ApiConst::refundSuccess;
        $updateData['refund_type']=ApiConst::refundStateComplete;
        $res=$refundReturnDao->update(array('refund_id'=>$refundId), $updateData);
        \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(),  array(&$refundReturnDao, 'getList'), array(), array($refundId));
        $storeDao->deleteStoreCache($storeId,$refundId);
        $storeDao->deleteStoreRefundCache($storeId,$refundId);
        if($res!==false){
            return true;
        }
        return false;

    }
    /**
     * 退货审核页
     *
     */
    public function returnGoods($storeId,$refundId,$sellerState,$refundAmount,$sellerMessage,$isGiveUp=ApiConst::zero) {
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
        $orderDao=\DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $orderGoodsDao=\DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
        $condition = array();
        $condition['store_id'] = $storeId;
        $condition['refund_id'] = $refundId;
        $returnDetail=$refundReturnDao->findByRefundId($refundId);
        if($returnDetail['store_id']!=$storeId){
            ErrorModel::throwException(CodeConfigModel::notExistRefund);
        }
        $return = $returnDetail;
        try {
            $return_goods= $refundReturnDao->getRefundOperateState('return_goods',$return);
            if(!$return_goods) {
                ErrorModel::throwException(CodeConfigModel::wrongRefundState);
            }
            $orderDao->setDb(DbNameConst::masterDBConnectName);
            $orderDao->db->doTransaction();
            $order_info=$orderDao->findByOrderId($return['order_id']);
            $refund_array = array();
            $refund_array['seller_time'] = TIMESTAMP;
            $refund_array['seller_state'] =$sellerState;//卖家处理状态:1为待审核,2为同意,3为不同意
            $refund_array['seller_message'] =$sellerMessage;

            if($return['refund_type']==ApiConst::refundTypeGoods && !$isGiveUp && $sellerState==ApiConst::refundSellerAgree){
                $waitRefundReceiveCount=ApiConst::one;
                $refundCount=ApiConst::zero;
            }else{
                $waitRefundReceiveCount=ApiConst::zero;
                $refundCount=ApiConst::reduceOne;
            }
            //如果卖家不同意退款回写is_refund
            if ($sellerState != '2'){
                $orderGoodsUpdateData['is_refund']=ApiConst::zero;
                $orderGoodsUpdateData['refund_state_name']=DescribeConst::sellerRefuseReturn;
                $orderGoodsUpdateData['gmt_update']=TIMESTAMP;
                $orderGoodsWhere['rec_id']=$return['order_goods_id'];
                $result=$orderGoodsDao->update($orderGoodsWhere,$orderGoodsUpdateData);
                if(!$result){
                    $orderDao->db->doRollback();
                    ErrorModel::throwException(CodeConfigModel::updateIsRefundFail);
                }
                $push=\Our\Push::getInstance();
                $pushData=array('storeId'=>$order_info['store_id'],
                    'type'=>ApiConst::messageRefund,
                    'waitReceiveCount'=>ApiConst::zero,
                    'waitDeliveryCount'=>ApiConst::zero,
                    'waitGetCount'=>ApiConst::zero,
                    'orderCount'=>ApiConst::zero,
                    'waitRefundProccessCount'=>ApiConst::reduceOne,
                    'waitRefundReceiveCount'=>$waitRefundReceiveCount,
                    'refundCount'=>$refundCount,
                    'alertCount'=>ApiConst::zero,
                    'params'=>array('c'=>'shopkeeper',
                        'm'=>'orderDetail',
                        'refundId'=>$return['refund_id']));
                $push->addOneToClient($pushData);
                $push->sendTcpMessage();
            }

            if ($sellerState == ApiConst::refundSellerAgree){
                $orderGoodsUpdateData['refund_state_name']=DescribeConst::sellerAgreeReturn;
                $orderGoodsUpdateData['gmt_update']=TIMESTAMP;
                $orderGoodsWhere['rec_id']=$return['order_goods_id'];
                $result=$orderGoodsDao->update($orderGoodsWhere,$orderGoodsUpdateData);
                if(!$result){
                    $orderDao->db->doRollback();
                    ErrorModel::throwException(CodeConfigModel::updateRefundStateNameFail);
                }
            }

            if ($refund_array['seller_state'] == '2' && !$isGiveUp) {
                $refund_array['return_type'] = '2';//退货类型:1为不用退货,2为需要退货
                $refund_array['goods_state']=2;
                $refund_array['refund_state']=ApiConst::refundStateProccess;
            } elseif ($refund_array['seller_state'] == '3') {

                $refund_array['refund_state'] = ApiConst::refundStateComplete;//状态:1为处理中,2为待管理员处理,3为已完成
            } else {
                $refund_array['seller_state'] = '2';
                $refund_array['refund_state'] = ApiConst::refundStateComplete;
                $refund_array['return_type'] = '1';//选择弃货
                $storeDao=\DAO\StoreModel::getInstance();
                $is_direct_refund = $storeDao->getInfoById($storeId, 'is_direct_refund', 'is_direct_refund');
                if($is_direct_refund==ApiConst::one){
                    $payment_type = $order_info['payment_type'];
                    if(!in_array($payment_type,array(0,2))){
                        $state = $refundReturnDao->storeRefund(array_merge($order_info, array('refund_order_no'=>$order_info['order_sn'], 'refund_amount'=> $refundAmount)));
                        if (!$state) {
                            //throw new Exception('更新订单信息失败');
                            $orderDao->db->doRollback();
                            return false;
                        }
                        if($payment_type==1) {  //微信支付
                            $updateData = array('is_suc_refund'=>1,'gmt_update'=>TIMESTAMP,'seller_state'=>$refund_array['seller_state'],'refund_state'=>$refund_array['refund_state']);
                        } else {
                            $updateData = array('is_suc_refund'=>1,'gmt_update'=>TIMESTAMP);
                        }
                        $res=$refundReturnDao->update(array('refund_id'=>$returnDetail['refund_id']), $updateData);
                        if(!$res){
                            $refundReturnDao->db->doRollback();
//                                showDialog('退款成功,退款表写入失败,请联系工作人员!',$reload,'error');
                            return false;
                        }
                        $result= $orderGoodsDao->update(array('rec_id'=>$returnDetail['order_goods_id']), array('is_refund'=>1,'gmt_update'=>TIMESTAMP));
                        if(!$result){
                            $refundReturnDao->db->doRollback();
//                            showDialog('refund_state_name',$reload,'error');
                            return false;
                        }
                    }
                }
                if(in_array($payment_type,array(0,2))){
                    $refund_array['refund_state']=ApiConst::refundStateProccess;
                }
            }
            $refund_array['refund_amount']=$refundAmount;
            $state = $refundReturnDao->update($condition, $refund_array);
            if ($state) {
                $sellerLogDao=\DAO\SellerLogModel::getInstance(DbNameConst::masterDBConnectName);
                $sellerLogDao->record('退货处理，退货编号：'.$return['refund_sn']);
                $orderDao->db->doCommit();
                $push=\Our\Push::getInstance();
                $pushData=array('storeId'=>$order_info['store_id'],
                    'type'=>ApiConst::messageRefund,
                    'waitReceiveCount'=>ApiConst::zero,
                    'waitDeliveryCount'=>ApiConst::zero,
                    'waitGetCount'=>ApiConst::zero,
                    'orderCount'=>ApiConst::zero,
                    'waitRefundProccessCount'=>ApiConst::reduceOne,
                    'waitRefundReceiveCount'=>$waitRefundReceiveCount,
                    'refundCount'=>$refundCount,
                    'alertCount'=>ApiConst::zero,
                    'params'=>array('c'=>'shopkeeper',
                        'm'=>'orderDetail',
                        'refundId'=>$return['refund_id']));
                $push->addOneToClient($pushData);
                $push->sendTcpMessage();
                return true;
            } else {
                throw new Exception('系统错误');
            }
        }catch (Exception $e) {
            throw new \Exception($e->getMessage());
        }


//		Tpl::output('return',$return);
//		$info['buyer'] = array();
//	    if(!empty($return['pic_info'])) {
//	        $info = unserialize($return['pic_info']);
//	    }
//		Tpl::output('pic_list',$info['buyer']);
//		$model_member = Model('member');
//		$member = $model_member->getMemberInfoByID($return['buyer_id']);
//		Tpl::output('member',$member);
//		$condition = array();
//		$condition['order_id'] = $return['order_id'];
//		$model_refund->getRightOrderList($condition, $return['order_goods_id']);
//		$deliveryman_list  = Model('diliveryman')->getDiliverymanList(array('store_id'=>$_SESSION['store_id'],'is_del'=>0),'scores desc');
//		Tpl::output('deliveryman_list',$deliveryman_list);
//		Tpl::showpage('store_return_edit');
    }
    /**
     * 退货退款处理
     * @param $storeId 店铺id
     * @param $refundId 退款id
     * @param $refundAmount 退款金额
     * @param string $text 退款消息
     */
    public function refund($storeId, $sellerId, $sellerName, $refundId, $refundAmount = 0, $text = '', $seller_state = 2,$isGiveUp=ApiConst::zero)
    {
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $storeDao=\DAO\StoreModel::getInstance(DbNameConst::masterDBConnectName);
        $whereRefund  = array();
        $whereRefund['store_id']= $storeId;
        $whereRefund['refund_id']= $refundId;
        $refund = $refundReturnDao->find($whereRefund);
        if($refund['refund_type']==ApiConst::refundTypeGoods){
            if($this->returnGoods($storeId,$refundId,$seller_state,$refundAmount,$text,$isGiveUp)){
                $refundReturnDao->deleteRefundCache($refund['buyer_id'], $refund['refund_id']);
                $orderDao->deleteOrderCache($refund['buyer_id'],$refund['order_id'],$refund['store_id']);
                \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(),  array(&$refundReturnDao, 'getList'), array(), array($refund['store_id']));
                $storeDao->deleteStoreCache($refund['store_id'],$refund['order_id']);
                $storeDao->deleteStoreRefundCache($refund['store_id'],$refund['order_id']);
            }
            return true;
        }else{

            if(!$refund) {
                ErrorModel::throwException(CodeConfigModel::notExistRefund);
            }
            if($refund['seller_state']!=1) {
                ErrorModel::throwException(CodeConfigModel::alreadyExsitRefundGoods);
            }

            //获取订单
            $order_id = $refund['order_id'];
            $order_info = $orderDao->find( array('order_id'=>$order_id));

            $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
            $refund_array = array();
            $refund_array['seller_time'] = time();
            $refund_array['seller_state'] = $seller_state;//卖家处理状态:1为待审核,2为同意,3为不同意
            $refund_array['seller_message'] = $text;
            $refund_array['refund_amount'] = $refundAmount;
            $refundReturnDao->db->doTransaction();
            if($seller_state!=2){   //拒绝退款
                $result= $orderGoodsDao->update(array('rec_id'=>$refund['order_goods_id']), array('is_refund'=>0, 'refund_state_name'=>'卖家拒绝退货', 'gmt_update'=>TIMESTAMP));

                if(!$result){
                    $refundReturnDao->db->doRollback();
                    return false;
                }
                if($order_info['refund_state']== 2) {
                    $result = $orderDao->updateByOrderId(array('refund_state'=>1), $refund['order_id']);
                    if(!$result){
                        $refundReturnDao->db->doRollback();
                        return false;
                    }
                }

                $refund_array['refund_state'] = ApiConst::refundStateComplete;    //状态:1为处理中,2为待管理员处理,3为已完成
                $state = $refundReturnDao->editRefundReturn($whereRefund, $refund_array);
                if(!$state){
                    $refundReturnDao->db->doRollback();
                    return false;
                }
                //$this->recordSellerLog('退款处理，退款编号：'.$refund['refund_sn']);    //待确认
                //记录操作日志
                $sellerLogDAO = \DAO\SellerLogModel::getInstance();
                $sellerLogDAO->record('拒绝退款处理，退款编号：'.$refund['refund_sn'], array('seller_id'=>$sellerId, 'seller_name'=>$sellerName, 'store_id'=>$storeId));

                $refundReturnDao->deleteRefundCache($refund['buyer_id'], $refund['refund_id']);
                $orderDao->deleteOrderCache($refund['buyer_id'],$refund['order_id'],$refund['store_id']);
                \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(),  array(&$refundReturnDao, 'getList'), array(), array($refund['store_id']));
                $refundReturnDao->db->doCommit();
                $refundReturnDao->deleteRefundCache($refund['buyer_id'], $refund['refund_id']);
                $orderDao->deleteOrderCache($refund['buyer_id'],$refund['order_id'],$refund['store_id']);
                \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(),  array(&$refundReturnDao, 'getList'), array(), array($refund['store_id']));
                $storeDao->deleteStoreCache($storeId,$refund['order_id']);
                $storeDao->deleteStoreRefundCache($storeId,$refund['order_id']);
                $push=\Our\Push::getInstance();
                $pushData=array('storeId'=>$storeId,
                    'type'=>ApiConst::messageRefund,
                    'waitReceiveCount'=>ApiConst::zero,
                    'waitDeliveryCount'=>ApiConst::zero,
                    'waitGetCount'=>ApiConst::zero,
                    'orderCount'=>ApiConst::zero,
                    'waitRefundProccessCount'=>ApiConst::reduceOne,
                    'waitRefundReceiveCount'=>ApiConst::zero,
                    'refundCount'=>ApiConst::reduceOne,
                    'alertCount'=>ApiConst::zero,
                    'params'=>array('c'=>'shopkeeper',
                        'm'=>'orderDetail',
                        'refundId'=>$refund['refund_id']));
                $push->addOneToClient($pushData);
                $push->sendTcpMessage();
                return true;
            }

            if($refundAmount > $refund['buyer_refund_amount']){
                //showDialog('退款金额不可大于本订单支付金额','','error');
                $refundReturnDao->db->doRollback();
                return false;
            }

            //以下为同意退款流程
            if($order_info['order_state']==40){ //交易完成订单，退积分
                $res = $this->edit_points($refund, $order_info);
                if(!$res){
                    $refundReturnDao->db->doRollback();
                    ErrorModel::throwException(CodeConfigModel::refundAddPointsLogError);
                }
            }
            $refund_array['refund_state'] = ApiConst::refundStateProccess;    //状态:1为处理中,2为待管理员处理,3为已完成

            $state = $refundReturnDao->editRefundReturn($whereRefund, $refund_array);
            if($state){ //退款记录成功
                //记录操作日志
                $sellerLogDAO = \DAO\SellerLogModel::getInstance();
                $sellerLogDAO->record('同意退款处理，退款编号：'.$refund['refund_sn'], array('seller_id'=>$sellerId, 'seller_name'=>$sellerName, 'store_id'=>$storeId));

                // add by ky start
                //检测该店铺是否开启直接退款功能
                $storeDAO = \DAO\StoreModel::getInstance();
                //店铺积分
                $is_direct_refund = $storeDAO->getInfoById($storeId, 'is_direct_refund', 'is_direct_refund');
                $orderGoodsDao->update(array('rec_id'=>$refund['order_goods_id']), array('refund_state_name'=>'卖家同意退款'));
                if($is_direct_refund==1){   //支持直接退款
                    $refund_array['refund_state']=ApiConst::refundStateComplete;
                    //退款 检测该订单是否为线上支付
                    $updateData = array('is_suc_refund'=>1,'gmt_update'=>TIMESTAMP);
                    if($refund_array['refund_amount']>0){
                        $payment_type = $order_info['payment_type'];
                        if(!in_array($payment_type,array(0,2))){
                            $state = $refundReturnDao->storeRefund(array_merge($order_info, array('refund_order_no'=>$refund['order_sn'], 'refund_amount'=> $refund_array['refund_amount'])));
                            if (!$state) {
                                //throw new Exception('更新订单信息失败');
                                $refundReturnDao->db->doRollback();
                                return false;
                            }
                            if($payment_type==1) {  //微信支付
                                $updateData = array('is_suc_refund'=>1,'gmt_update'=>TIMESTAMP,'seller_state'=>$refund_array['seller_state'],'refund_state'=>$refund_array['refund_state']);
                            } else {
                                $updateData = array('is_suc_refund'=>1,'gmt_update'=>TIMESTAMP);
                            }
                        }
                    }else{
                        $updateData = array('is_suc_refund'=>ApiConst::zero,'gmt_update'=>TIMESTAMP,'seller_state'=>$refund_array['seller_state'],'refund_state'=>ApiConst::refundStateProccess);
                    }
                    $res=$refundReturnDao->update(array('refund_id'=>$refund['refund_id']), $updateData);
                    if(!$res){
                        $refundReturnDao->db->doRollback();
//                                showDialog('退款成功,退款表写入失败,请联系工作人员!',$reload,'error');
                        return false;
                    }
                    $result= $orderGoodsDao->update(array('rec_id'=>$refund['order_goods_id']), array('is_refund'=>1,'gmt_update'=>TIMESTAMP));
                    if(!$result){
                        $refundReturnDao->db->doRollback();
//                            showDialog('refund_state_name',$reload,'error');
                        return false;
                    }
                }
                $refundReturnDao->db->doCommit();
                $refundReturnDao->deleteRefundCache($refund['buyer_id'], $refund['refund_id']);
                $orderDao->deleteOrderCache($refund['buyer_id'],$refund['order_id'],$refund['store_id']);
                \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(),  array(&$refundReturnDao, 'getList'), array(), array($refund['store_id']));
                $storeDao->deleteStoreCache($storeId,$refund['order_id']);
                $storeDao->deleteStoreRefundCache($storeId,$refund['order_id']);
                $push=\Our\Push::getInstance();
                $pushData=array('storeId'=>$storeId,
                    'type'=>ApiConst::messageRefund,
                    'waitReceiveCount'=>ApiConst::zero,
                    'waitDeliveryCount'=>ApiConst::zero,
                    'waitGetCount'=>ApiConst::zero,
                    'orderCount'=>ApiConst::zero,
                    'waitRefundProccessCount'=>ApiConst::reduceOne,
                    'waitRefundReceiveCount'=>ApiConst::zero,
                    'refundCount'=>ApiConst::reduceOne,
                    'alertCount'=>ApiConst::zero,
                    'params'=>array('c'=>'shopkeeper',
                        'm'=>'orderDetail',
                        'refundId'=>$refund['refund_id']));
                $push->addOneToClient($pushData);
                $push->sendTcpMessage();
                return true;
            }
            $refundReturnDao->db->doRollback();
        }

        return false;
    }

    /**
     *  退货退款已完成订单积分扣除
     *
     * @param $refund
     * @param $order_info
     * @return bool
     */
    private function edit_points($refund,$order_info){
        return true;    //暂时不对积分做处理
        $settingDAO = \DAO\SettingModel::getInstance();
        $points_ratio = floatval($settingDAO->getListCache(array('points_ratio'))['points_ratio']);

        $order_id = $order_info['order_id'];
        $store_id = $refund['store_id'];
        $member_id = $refund['buyer_id'];
        $amount_money = $refund['refund_amount'];
        $pt_points = $points_ratio * $amount_money;
        //平台积分
        $pt_points_log_data=array(
            'pl_memberid'  => $member_id,
            'pl_membername'=> $refund['buyer_name'],
            'pl_points'    => -$pt_points,
            'pl_addtime'   => time(),
            'pl_desc'      => '退货退款扣除平台积分',
            'pl_stage'     => '退货退款扣除',
            'pl_type'      => 2,
            'pl_source_type'=> 2,
            'pl_order_id'  => $order_id
        );
        //更新积分记录
        $plDAO = \DAO\Member\PointsLogModel::getInstance(\Our\DbNameConst::masterDBConnectName);
        $ptRes = $plDAO->addlog($pt_points_log_data);
        if(!$ptRes){
            return false;
        }

        $qmmpDAO = \DAO\Member\QmMemberPointsModel::getInstance(\Our\DbNameConst::masterDBConnectName);
        //
        $ptMemberRes = $qmmpDAO->update('disabled_points=disabled_points-'.$pt_points, array('member_id'=>$member_id, 'points_type'=>2));
        if(!$ptMemberRes){
            return false;
        }
        $storeDAO = \DAO\StoreModel::getInstance();
        //店铺积分
        $ratio = $storeDAO->getInfoById($store_id, 'store_points_ratio', true);
        $store_points = $amount_money*$ratio;
        $store_points_log_data = array(
            'pl_memberid'  => $member_id,
            'pl_membername'=> $refund['buyer_name'],
            'pl_points'    => -$store_points,
            'pl_addtime'   => time(),
            'pl_desc'      => '退货退款扣除店铺积分',
            'pl_stage'     => '退货退款扣除',
            'pl_type'      => 1,
            'pl_store_id'  => $store_id,
            'pl_source_type'=> 2,
            'pl_order_id'  => $order_id
        );
        $storeRes = $plDAO->addlog($store_points_log_data);
        if(!$storeRes){
            return false;
        }
        $storeMemberRes = $qmmpDAO->update('disabled_points=disabled_points-'.$store_points, array('member_id'=>$member_id, 'store_id'=>$store_id));
        if(!$storeMemberRes){
            return false;
        }
        return true;
    }

    /**
     * 店铺退款列表
     * @param $storeId
     * @param int $type
     * @param int $pageIndex
     * @param int $pageSize
     * @return \stdClass
     */
    public function getStoreRefundList($storeId, $type=ApiConst::zero,$pageIndex = ApiConst::zero, $pageSize = ApiConst::pageSize,$refundId=false)
    {
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::salveDBConnectName);

        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);

        $orderDao=\DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsDao=\DAO\GoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $diliverymanDao=\DAO\Order\DiliverymanModel::getInstance();
        $qmDeliveryManLogDao=\DAO\Order\QmDeliverymanLogModel::getInstance();
        $addressDao = \DAO\Order\DAddressModel::getInstance(DbNameConst::salveDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance();

//        $where['store_id'] = $storeId;
//        $where['order_lock'] = 2;
        $order = array('add_time' => 'desc');
        if($refundId){
            $where['refund_id']=$refundId;
        }else{
            if($type==ApiConst::zero){
                $where['store_id'] = $storeId;
            }else{
                if($type==ApiConst::refundSellerVerify){
                    $where=$refundReturnDao->getProccessOrderBySeller($storeId);
                }
                if($type==ApiConst::refundSellerAgree){
                    $where=$refundReturnDao->getReturnWaitReceive($storeId);
                    $order= array('receive_time'=> 'asc');
                }
            }
        }


        //获得售后列表
        $refundReturns = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$refundReturnDao, 'getList'), array($where, $this->storeRefundReturnField, $pageIndex, $pageSize,$order), \Our\ApiConst::oneDaySecond, array($storeId));
        $orderGoodsId = array_column($refundReturns['list'], 'orderGoodsId');

        //获得售后商品列表getOrderGoodsByRecIds
        if (!empty($orderGoodsId)) {

            $orderGoods = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByRecIds'), array($orderGoodsId, $this->refundOrderGoodsField), \Our\ApiConst::oneDaySecond, array($storeId));
            $refundMerge = Common::intergrateOneToOne($refundReturns['list'], $orderGoods, 'orderGoodsId', 'recId');
            $orderIds= array_column($refundMerge, 'orderId');
            $refundIds=array_column($refundMerge,'refundId');
            $diliveryWhere['order_id']=array('in',$refundIds);
            $diliveryWhere['order_type']=ApiConst::orderTypeRefund;
            $orderWhere['order_id']=array('in',$orderIds);
            $orders = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$orderDao, 'getList'), array($orderWhere, $orderDao->getOrderDetailField(), ApiConst::zero, $pageSize), \Our\ApiConst::oneDaySecond, array($storeId));
            $qmDeliveryManLogWhere['order_id']=array('in',$refundIds);
            $qmDeliveryManLogWhere['order_type']= ApiConst::orderTypeRefund;
            $qmDeliveryManLogs=\Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$qmDeliveryManLogDao, 'getList'), array($qmDeliveryManLogWhere, $qmDeliveryManLogDao->fieldDetail,ApiConst::zero,$pageSize), \Our\ApiConst::oneDaySecond, array($storeId));
            $qmDeliveryManLogs=$qmDeliveryManLogDao->convertListByField($qmDeliveryManLogs['list'],'orderId');
            $orders=$orderDao->convertOrder($orders['list'],'orderId');
            $orderCommons = $orderCommonDao->getAllByOrderIds($orderIds, $orderCommonDao->orderCommonField);
            $orderCommons=$orderDao->convertOrder($orderCommons,'orderId');
            foreach ($refundMerge as &$value) {
                $value['sellerStateName']=$refundReturnDao->getSellerStateName($value['sellerState']);
                $value['stateName'] = $refundReturnDao->getRefundTextStatus($value,true);
                /*$value['blId'] = isset($value['blId']) ? (!is_null($value['blId']) ? $value['blId'] : ApiConst::zero) : ApiConst::zero;
                $value['canPlatformIn'] = $refundReturnDao->isPlatformIn($value) ? ApiConst::one : ApiConst::zero;
                $value['canSendShippingType'] = $refundReturnDao->checkIsAddReturnShipping($value) ? ApiConst::one : ApiConst::zero;*/
//                $value['couponAmount'] = ($value['goodsAmount'] + $value['shippingFee']) - $value['orderAmount'];//优惠券金额
//                $value['receiveAmount'] = $value['goodsAmount']+$value['shippingFee'] - $value['couponAmount'];
                // $value['orderAmount'] = $value['orderAmount'];
                $value['reciverInfo'] = unserialize($orderCommons[$value['orderId']]['reciverInfo']);
                $value['dlyoPickupCode'] = substr($value['orderSn'], ApiConst::positionPickupCodeBegin);
                $value['deliveryTimeEnd'] = $value['deliveryTime'] + ApiConst::arriveTimeRadius;
                $value['goodsImage'] = ImageUtil::getGoodsImgUrl($value['goodsImage'], ApiConst::goodsSmallSize);
                $value['goodsAttr']=$goodsDao->getFormatGoodsAttr($value['goodsSpec']);
                $extent=$orderDao->getClienOrderCommon($orders[$value['orderId']]);
                $value=array_merge($value,$extent);
                $goodGroup=unserialize($value['goodsGroup']);
                if ($value['diliverymanId']) {
                    $diliverymanDao = \DAO\Order\DiliverymanModel::getInstance();
                    $res = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$diliverymanDao, 'findById'), array($value['diliverymanId']), \Our\ApiConst::oneDaySecond, array($value['diliverymanId']));
                    $value['deliveryman'] = $diliverymanDao->convert($res);
                    $value['deliveryman']['distributionFee']=$qmDeliveryManLogs[$value['refundId']]['distributionFee'];
                }else{
                    $value['deliveryman']=new \stdClass();
                }
                if(!empty($goodGroup)){
                    $value['goodsGroup']=$goodGroup;
                    $value['goodsOriginPrice']=$goodsDao->getOriginPriceByGoodsGroup($value['goodsGroup']);
                }else{
                    $value['goodsGroup']=[];

                }

                if ($value['refundType'] == ApiConst::refundTypeGoods) {
                    if($value['refundShippingType']==ApiConst::bySeller){
                        $value['reciverInfo']=$orderCommonDao->getReciverInfo($value['reciverInfo']);
                    }
                } else {
                    $value['reciverInfo'] = new \stdClass();
                }
                $value['picInfo']=unserialize($value['picInfo']);
                if(!empty($value['picInfo'])){
                    $value['picInfo'] = $refundReturnDao->getRefundPics($value['picInfo']['buyer']);
                }
                if($value['goodsState']>ApiConst::goodsStateWaitRecieve){
                    $value['shippingOver']=ApiConst::shippingOver;
                }
                if($value['isSucRefund']==ApiConst::isNotSuccessRefund &&  ($value['sellerState']==ApiConst::refundSellerAgree || $value['platformState']==ApiConst::platAgree) ){
                    $value['markRefundButton']=ApiConst::one;
                }else{
                    $value['markRefundButton']=ApiConst::zero;;
                }
                unset($value['goodsSpec']);
                // unset($value['picInfo']);
            }
            $returnData['refundReturns'] = $refundMerge;
            $returnData['totalCount'] = $refundReturns['totalCount'];
            return $returnData;
        } else {
            return new \stdClass();
        }
    }
    public function getStoreRefundDetail($storeId,$returnId){
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance();
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance();
        $orderDao= \DAO\Order\OrderModel::getInstance();
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::salveDBConnectName);
        $storeDao = \DAO\StoreModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsDao = \DAO\GoodsModel::getInstance();
        $refundReturn = $refundReturnDao->findByRefundId($returnId, $this->refundReturnField);
        $diliveryManDao=\DAO\Order\DiliverymanModel::getInstance(DbNameConst::salveDBConnectName);
        if (empty($refundReturn)) {
            ErrorModel::throwException(CodeConfigModel::notExistRefund);
        }
        $res=$this->getStoreRefundList($storeId,ApiConst::zero,ApiConst::zero,ApiConst::pageSize, $returnId);
        if(!empty($res['refundReturns'][ApiConst::zero])) {
            return $res['refundReturns'][ApiConst::zero];
        }
        return new \stdClass();

    }
    /**
     * 退款列表
     *
     */
    public function getList($memberId, $pageIndex = ApiConst::zero, $pageSize = ApiConst::pageSize)
    {
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::salveDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsDao=\DAO\GoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $where['buyer_id'] = $memberId;
        //获得售后列表
        $refundReturns = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$refundReturnDao, 'getList'), array($where, $this->refundReturnField, $pageIndex, $pageSize, $order = array('add_time' => 'desc')), \Our\ApiConst::oneDaySecond, array($memberId));
        $orderGoodsId = array_column($refundReturns['list'], 'orderGoodsId');
        //获得售后商品列表getOrderGoodsByRecIds
        if (!empty($orderGoodsId)) {
            $orderGoods = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByRecIds'), array($orderGoodsId, $this->orderGoodsField), \Our\ApiConst::oneDaySecond, array($memberId));
            $refundMerge = Common::intergrateOneToOne($refundReturns['list'], $orderGoods, 'orderGoodsId', 'recId');
            foreach ($refundMerge as &$value) {
                $value['refundStateName'] = $refundReturnDao->getRefundTextStatus($value);
                $value['blId'] = isset($value['blId']) ? (!is_null($value['blId']) ? $value['blId'] : ApiConst::zero) : ApiConst::zero;
                $value['canPlatformIn'] = $refundReturnDao->isPlatformIn($value) ? ApiConst::one : ApiConst::zero;
                $value['canSendShippingType'] = $refundReturnDao->checkIsAddReturnShipping($value) ? ApiConst::one : ApiConst::zero;
                $value['goodsImage'] = ImageUtil::getGoodsImgUrl($value['goodsImage'], ApiConst::goodsSmallSize);
                $value['goodsAttr']=$goodsDao->getFormatGoodsAttr($value['goodsSpec']);
                $goodGroup=unserialize($value['goodsGroup']);
                $value['goodsGroup']=!empty($goodGroup)?$goodGroup:[];
                unset($value['goodsSpec']);
                unset($value['picInfo']);
            }
            $returnData['refundReturns'] = $refundMerge;
            $returnData['totalCount'] = $refundReturns['totalCount'];
            return $returnData;
        } else {
            return new \stdClass();
        }
    }

    public function getConvertOrder($order, $fields = array())
    {
        $convertResult = array();
        foreach ($fields as $key => $field) {
            $convertResult[$key] = $order[$field];
        }
        return $convertResult;
    }

    public function getFields()
    {
        return array(
            'orderId' => 'order_id',
            'orderSn' => 'order_sn',
            'storeId' => 'store_id',
            'storeName' => 'store_name',
            'addTime' => 'add_time',
            'goodsAmount' => 'goods_amount',
            'orderAmount' => 'order_amount',
            'shippingType' => 'shipping_type',
            'shippingFee' => 'shipping_fee',
            'paymentType' => 'payment_type',
            'orderState' => 'order_state',
            'refundState' => 'refund_state',
            'refundAmount' => 'refund_amount',
            'diliverymanId' => 'diliveryman_id',
            'deliveryDistance' => 'delivery_distance',
            'shippingArrivalTime' => 'shipping_arrival_time',
            'couponId' => 'coupon_id',
            'orderType' => 'order_type',
            'buyerId' => 'buyer_id',

        );
    }

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

    /**
     * 订单,获得订单详情
     *
     * @date 2018-5-15
     * @author ccw
     */
    public function getOrderDetail($orderId)
    {
        $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);
        $storeDao = \DAO\StoreModel::getInstance();
        //订单
        $order = $orderDao->findByOrderId($orderId);
        $fields = $this->getFields();
        $this->order = $this->getConvertOrder($order, $fields);
        //收货人地址
        //收货人信息
        $this->orderCommon = $orderCommonDao->findByOrderId($orderId, $this->orderCommonField);
        if ($this->orderCommon['daddressId'] > ApiConst::zero) {
            $this->address = $addressDao->getAddressByAddressId($this->orderCommon['daddressId'], $this->addressField);
            $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 = $orderGoodsDao->getOrderGoodsByOrderIds($orderId, $this->getGoodsDetailField());
        //商店相关信息
        $this->store = $storeDao->getInfoById($this->order['storeId'], $this->storeField);

        $returnData = $this->order;
        //配送员信息
        $this->diliveryman = $diliverymanDao->findById($returnData['diliverymanId']);
        //地址

        $returnData['shippingName'] = $orderDao->getShippingName($returnData['shippingType']);
        $returnData['shippingFeeName'] = $orderDao->getFreightFeeName($returnData['shippingType']);
        $returnData['paymentName'] = $orderDao->getPayTypeName($returnData['paymentType']);
        $returnData['blld'] = $returnData['blld'] ? $returnData['blld'] : ApiConst::zero;
        $returnData['couponId'] = $returnData['couponId'] ? $returnData['couponId'] : ApiConst::zero;
        if ($returnData['diliverymanId']) {
            $returnData['deliveryman'] = $diliverymanDao->convert($this->diliveryman, $this->getDeliveryManFields());
        } else {
            $returnData['diliverymanId'] = ApiConst::zero;
            $returnData['deliveryman'] = array();
        }
        $returnData['totalGoodsNum'] = $orderGoodsDao->getGoodsCount($this->orderGoodsList);
        $returnData['offinePayway'] = $this->store['offlinePayway'] ? $this->store['offlinePayway'] : '';
        $returnData['reciverInfo'] = $this->address;
        $returnData['orderGoods'] = $goodsDao->convert($this->orderGoodsList);
        return $returnData;
    }


    public function getOrderGoods($orderGoods)
    {
        return array(
            'goodsId' => $orderGoods['goodsId'],
            'goodsName' => $orderGoods['goodsName'],
            'goodsPrice' => $orderGoods['goodsPrice'],
            'goodsNum' => $orderGoods['goodsNum'],
            'goodsImage' => $orderGoods['goodsImage'],
            'goodsPayPrice' => $orderGoods['goodsPayPrice'],

        );
    }

    //获得退货退款订单详情
    public function getRefundOrder($memberId, $orderId, $goodsId)
    {
        //退款原因列表
        $refundReasonDao = \DAO\Order\RefundReasonModel::getInstance();
        $storeDao = \DAO\StoreModel::getInstance();

        $refundReasonList = \Our\RedisHelper::cachedFunction(\Redis\Db5\RefundReasonRedisModel::getInstance(), array(&$refundReasonDao, 'getAll'), array($this->refunReasonField), \Our\ApiConst::oneDaySecond);

        $refundTypes = array_values(ArrayConst::refundTypes);
        $cartDao = \DAO\Cart\CartModel::getInstance();

        //订单详情
        $orderDao = \DAO\Order\OrderModel::getInstance();
        $orderInfo = $orderDao->findByMemberIdAndOrderId($memberId, $orderId);
        if (empty($orderInfo)) {
            ErrorModel::throwException(CodeConfigModel::notExistRefund);
        }
        $shippingTypes=array();
        array_push($shippingTypes,ArrayConst::refundShippingType[$orderInfo['shippingType']]);
        // $shippingTypes = ArrayConst::refundShippingType[$orderInfo['shippingType']];
        //获得订单商品
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance();
        $orderGoodses = \Our\RedisHelper::cachedFunction(\Redis\Db5\RefundReasonRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByOrderIds'), array($orderInfo['orderId'], $this->orderGoodsField), \Our\ApiConst::oneDaySecond);
        $orderGoodses = $orderGoodsDao->convertOrderGoods($orderGoodses, 'goodsId');
        $goodsIds = $orderGoodsDao->getRefundOrderGoodsIds($orderGoodses);
//        $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($orderInfo['storeId'], $storeDao->detailField), \Our\ApiConst::sevenDaySecond,array($orderInfo['storeId']));
        if(!empty($orderGoodses[$goodsId])){
            $orderGoods = $orderGoodses[$goodsId];
        }
        if (!empty($orderGoods)) {
            array_push($goodsIds, $goodsId);
        }else{
            ErrorModel::throwException(CodeConfigModel::notExistOrderGoods);
        }
        $shippingFee = ApiConst::zero;
        if (count($orderGoods) == ApiConst::one) {
            $shippingFee = $storeDao->isFee($orderInfo['storeId'], $orderInfo['shippingType'], $orderInfo['order_state']) ? $orderInfo['shippingFee'] : ApiConst::zero;
        } else {
            $shippingFee == ApiConst::zero;
        }
        $orderGoodsConvert = $orderGoodsDao->getRefundOrderGoods($orderGoods);

        $returnData = array(
            'orderId' => (int)$orderId,
            'orderSn'=>$orderInfo['orderSn'],
            'needShippingFee' => $orderInfo['needShippingFee'],
            'shippingType' => $orderInfo['shippingType'],
            'shippingFee' => $shippingFee,
            'reasons' => $refundReasonList,
            'orderGoods' => $orderGoodsConvert,
            'refundTypes' => $refundTypes,
            'shippingTypes' => $shippingTypes,
            'storeName'=>$orderInfo['storeName'],
            'storeId'=>$orderInfo['storeId'],
            'refundSeletedId'=>$orderDao->selectedTypeId($orderInfo),
            'storeMemberId'=>$this->store['memberId']
        );
        $refundCondition = $orderInfo['refundCondition'] ? unserialize($orderInfo['refundCondition']) : array();
        $returnData['needShippingFee'] = $orderInfo['needShippingFee'];
       // if($orderInfo['shippingType']==ApiConst::bySelf){
            $returnData['needShippingFee']=ApiConst::zero;
       // }
        if ($orderInfo['paymentTime']) {
            $orderConfirmUtil = \Order\OrderConfirmUtil::getInstance();

            if ($orderInfo['couponId']) {
                if ($refundCondition) {
                    $refundCondition['storeCarts']['storeCarts'] = $cartDao->refundGoodsRemove($refundCondition['storeCarts']['storeCarts'], $goodsIds);
                    if (!empty($refundCondition['storeCarts']['storeCarts'])) {
                        $newTotalPrice = $orderConfirmUtil->reCalcOrderAmount($refundCondition['coupon'], $refundCondition['storeCarts']['storeCarts']);
                        $refundAmount = $orderInfo['orderAmount'] - $orderInfo['shippingFee'] - $newTotalPrice;
                    } else {
                        $refundAmount = $orderInfo['orderAmount'] - $orderInfo['shippingFee'] - ApiConst::zero;;
                    }
                }
            } else {

                $refundAmount = $orderGoods['goodsPrice']*$orderGoods['goodsNum'];
            }
            $returnData['refundAmount'] = $refundAmount - $orderInfo['refundAmount'] - $returnData['needShippingFee'] + $shippingFee;
            if((int)$returnData['refundAmount'] <ApiConst::zero){
                $returnData['refundAmount']=ApiConst::zero;
            }
//             if($orderGoods['goodsType']==ApiConst::goodsTypeFour){
//                 //已经退款过的金额
//                 $alreadyRefundMoney=$orderGoodsDao->getIsRefundMoney($orderGoodses,$orderGoods['promotionsId']);
//                 $res=$orderGoods['joinGoodsMoney']-$orderGoods['goodsPrice']-$alreadyRefundMoney-orderGoods['discountAmountLimit'];
//                 if($res<ApiConst::zero){
//                     $canRefundMoney=$orderGoods['goodsPayPrice']+$res;
//                     if($canRefundMoney<ApiConst::zero){
//                         $returnData['refundAmount']=ApiConst::zero;
//                     }else{
//                         $returnData['refundAmount']=$canRefundMoney;
//                     }
//                 }else{
//                     $returnData['refundAmount']=$orderGoods['goodsPayPrice'];
//                 }
//                 $returnData['refundAmount']=$returnData['refundAmount']-$returnData['needShippingFee']+$shippingFee;
//             }else{
//                 $returnData['refundAmount']=$orderGoods['goodsPayPrice']-$returnData['needShippingFee']+$shippingFee;
//             }
        } else {
            $returnData['refundAmount'] = ApiConst::zero;
        }

        return $returnData;
    }

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


    public function getUploadImagesPath($images)
    {
        $path = array();
        foreach ($images as $val) {
            $fileName = ImageUtil::getFileName();
            ImageUtil::uploadBase64Image($val, ImageConst::refund, $fileName);
            array_push($path, $fileName);
        }
        return $path;
    }

    /**
     * 添加订单商品部分退款
     *
     */
    public function addRefund($memberId, $refund)
    {
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
        $refundReasonDao = \DAO\Order\RefundReasonModel::getInstance(DbNameConst::masterDBConnectName);
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $orderInfo = $orderDao->findByMemberIdAndOrderId($memberId, $refund['orderId'], $this->orderField);
        $storeDao=\DAO\StoreModel::getInstance();
        if($refund['refundType']==ApiConst::refundTypeGoods){
            $refund['refundAmount']-=$orderInfo['needShippingFee'];
        }
        $whereRefund['goods_id']=$refund['goodsId'];
        $whereRefund['buyer_id']=$memberId;
        $whereRefund['order_id']=$orderInfo['orderId'];
        $refundOne=$refundReturnDao->find($whereRefund,$refundReturnDao->refundDetailField);
        if(!empty($refundOne)){
            ErrorModel::throwException(CodeConfigModel::alreadyExsitRefundGoods);
        }
        $refundReasonList = \Our\RedisHelper::cachedFunction(\Redis\Db5\RefundReasonRedisModel::getInstance(), array(&$refundReasonDao, 'getAll'), array($this->refunReasonField), \Our\ApiConst::oneDaySecond);
        $refundReasonList = $refundReasonDao->convertToKey($refundReasonList);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
        $orderLogDao = \DAO\Order\OrderLogModel::getInstance(DbNameConst::masterDBConnectName);
        $orderGoods = $orderGoodsDao->getOneByOrderIdAndGoodsId($refund['orderId'], $refund['goodsId'], $this->orderGoodsField);
        if(empty($orderGoods)){
            ErrorModel::throwException(CodeConfigModel::notExistOrderGoods);
        }
        if($orderGoods['refundId']>ApiConst::zero){
            ErrorModel::throwException(CodeConfigModel::alreadyExsitRefundGoods);
        }
        $refundAmount = $refund['refundAmount'];//退款金额
        if ($orderInfo['paymentTime']) {
            $maxRefundAmount=$orderGoods['goodsPayPrice']*$orderGoods['goodsNum'];
            if (($refundAmount < ApiConst::zero) || ($refundAmount > $maxRefundAmount)) {
                $refundAmount = $maxRefundAmount;
            }
        } else {
            $refundAmount = ApiConst::zero;
        }
        $refundArray = array();
        $goodsNum = $orderGoods['goodsNum'];//退货数量
        $reasonId = intval($refund['reasonId']);//退货退款原因

        $refundArray['reason_id'] = $reasonId;
        $refundArray['reason_info'] = '其他';
        $reasonList[ApiConst::zero] = $refundArray;
        if (!empty($refundReasonList[$reasonId])) {
            $refundArray['reason_id'] = $refundReasonList[$reasonId]['reasonId'];
            $refundArray['reason_info'] = $refundReasonList[$reasonId]['reasonInfo'];
        }
        $picArray = array();
        $picArray['buyer']=array();
        if (!empty($refund['images'])) {
            foreach($refund['images'] as $key=>$image){
                $ismuch= preg_match('/^(data:\s*image\/(\w+);base64,)/', $image, $result);
                if($ismuch){
                    $fileName=ImageUtil::uploadBase64Image($image,ImageConst::refund,ImageUtil::getFileName($memberId.$key));
                    $fileName=basename($fileName);
                }else{
                    $fileName=$image;
                }
                array_push($picArray['buyer'],$fileName);
            }
            //  $picArray['buyer'] = $refund['images'];
        } else {
            $picArray['buyer'] = array();
        }

        $info = serialize($picArray);
        $refundArray['pic_info'] = $info;
        $refundArray['order_lock'] = $orderDao->getOrderLock($orderInfo['orderState']);
        if ($refund['refundType'] == ApiConst::refundTypeGoods) {
            $refundReturnDao->isReturn($orderInfo);
        }
        $refundArray['return_type'] = $refundReturnDao->getRefundTypeByType($refund['refundType']);//退货类型:1为不用退货,2为需要退货
        $refundArray['seller_state'] = '1';//状态:1为待审核,2为同意,3为不同意
        $refundArray['refund_amount'] = \Our\Common::priceFormat($refundAmount);
        $refundArray['buyer_refund_amount'] = $refundArray['refund_amount'];
        $refundArray['goods_num'] = $goodsNum;
        $refundArray['buyer_message'] = $refund['buyerMessage'];
        $refundArray['add_time'] = TIMESTAMP;
        $refundArray['refund_type']=$refund['refundType'];
        $refundArray['refund_shipping_type']=isset($refund['refundShippingType'])?$refund['refundShippingType']:ApiConst::zero;
        $refundArrayUnLine=Common::convertUnderline($refundArray);
        $state = $refundReturnDao->addRefundReturn($refundArray,$orderInfo,$orderGoods);
        $orderDao->deleteOrderCache($memberId,$orderInfo['orderId'],$orderInfo['storeId'],true);
        $storeDao->deleteStoreCache($orderInfo['storeId'],$orderInfo['orderId']);
        $storeDao->deleteStoreRefundCache($orderInfo['storeId'],$orderInfo['orderId']);
        if ($state) {
            $refundStateName=$refundReturnDao->getRefundTextStatus($refundArrayUnLine);
            $orderGoodsDao->update(array('rec_id'=>$orderGoods['recId']),array('refund_state_name'=>$refundStateName,'refund_id'=>$state));
            $refundReturnDao->deleteRefundCache($memberId);
            $storeDao->deleteStoreRefundCache($refundOne['storeId']);
            $orderLogDao->addRefundOrderLog($orderInfo['orderId'],$refundArray['refund_type'],DescribeConst::buyer,$orderInfo['buyerName'],$orderInfo['orderState']);
            $push=\Our\Push::getInstance();
            $pushData=array('storeId'=>$orderInfo['storeId'],
                'type'=>ApiConst::messageRefund,
                'waitReceiveCount'=>ApiConst::zero,
                'waitDeliveryCount'=>ApiConst::zero,
                'waitGetCount'=>ApiConst::zero,
                'orderCount'=>ApiConst::zero,
                'waitRefundProccessCount'=>ApiConst::one,
                'waitRefundReceiveCount'=>ApiConst::zero,
                'refundCount'=>ApiConst::one,
                'alertCount'=>ApiConst::zero,
                'params'=>array('c'=>'shopkeeper',
                    'm'=>'orderDetail',
                    'orderId'=>$orderInfo['orderId']));
            $push->addOneToClient($pushData);
            $push->sendTcpMessage();

            //\Our\RedisHelper::rpush('client_push',array('storeId'=>$refund['storeId'],'type'=>ApiConst::messageRefundProccessing,'op'=>NameConst::reduce,'num'=>ApiConst::one,'params'=>array('c'=>'shopkeeper','m'=>'getRefundDetail','refundId'=>$refund['refundId'])));
            if ($orderInfo['orderState'] == ApiConst::orderStateWaitRecieve) {
                $orderDao->editOrderLock($orderInfo['orderId']);
            }
            return $state;
        } else {
            ErrorModel::throwException(CodeConfigModel::refundRefuseByStore);
        }
    }

    //获得退货退款详情
    public function getInfo($returnId)
    {
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance();
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance();
        $orderDao= \DAO\Order\OrderModel::getInstance();
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::salveDBConnectName);
        $storeDao = \DAO\StoreModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsDao = \DAO\GoodsModel::getInstance();
        $refundReturn = $refundReturnDao->findByRefundId($returnId, $this->refundReturnField);
        $diliveryManDao=\DAO\Order\DiliverymanModel::getInstance(DbNameConst::salveDBConnectName);
        if (empty($refundReturn)) {
            ErrorModel::throwException(CodeConfigModel::notExistRefund);
        }
        $orderGoods = \Our\RedisHelper::cachedFunction(\Redis\Db5\RefundReasonRedisModel::getInstance(), array(&$orderGoodsDao, 'findByRecId'), array($refundReturn['orderGoodsId'], $this->getGoodsDetailField()), \Our\ApiConst::oneDaySecond,array($refundReturn['orderId']));
        $this->orderCommon = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderCommonDao, 'findByOrderId'), array($refundReturn['orderId'], $orderCommonDao->orderCommonField), \Our\ApiConst::oneDaySecond,array($refundReturn['orderId']));
//        $this->store=$storeDao->get($refundReturn['storeId']);
//        $this->store=Common::convertUnderline($this->store[0]);
        $order = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'findByOrderId'), array($refundReturn['orderId'],$orderDao->getOrderDetailField()), \Our\ApiConst::oneDaySecond, array($refundReturn['orderId']));
        $this->store = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$storeDao, 'getInfoById'), array($refundReturn['storeId'],$storeDao->detailField), \Our\ApiConst::sevenDaySecond,array($refundReturn['storeId']));
        $refundReturn['goodsGroup'] = $goodsDao->getGoodsGroup($orderGoods['goodsGroup']);
        $refundReturn['goodsAttr'] = $goodsDao->getFormatGoodsAttr($orderGoods['goodsSpec']);
        $refundReturn['sellerStateName'] = ArrayConst::sellerState[$refundReturn['sellerState']];
        $refundReturn['refundTypeName'] = ArrayConst::refundType[$refundReturn['refundType']];
        $refundReturn['goodsPayPrice']=$orderGoods['goodsPayPrice'];
        $refundReturn['returnTypeName'] = ArrayConst::returnType[$refundReturn['returnType']];
        $refundReturn['picInfo'] =!empty($refundReturn['picInfo'])?unserialize($refundReturn['picInfo']):array();
        if(!empty($refundReturn['picInfo'])){
            $refundReturn['picInfo'] = $refundReturnDao->getRefundPics($refundReturn['picInfo']['buyer']);
        }
        $orderExtent=$orderDao->getClienOrderCommon($order);
        $refundReturn=array_merge($refundReturn,$orderExtent);
        // $value['orderAmount'] = $value['orderAmount'];
        $refundReturn['reciverInfo'] = unserialize($this->orderCommon['reciverInfo']);
        if ($refundReturn['refundType'] == ApiConst::refundTypeGoods) {
            if($refundReturn['refundShippingType']==ApiConst::bySeller || $refundReturn['refundShippingType']==ApiConst::bySelf){
                $refundReturn['reciverInfo']=$orderCommonDao->getReciverInfo($refundReturn['reciverInfo']);
            }
        } else {
            $refundReturn['reciverInfo'] = new \stdClass();
        }
        //平台操作类型
        $refundReturn['storeMemberId']=$this->store['memberId'];
        $refundReturn['platformStateName'] = ArrayConst::platformState[$refundReturn['platformState']];
        $refundReturn['refundShippingTypeName'] = ArrayConst::refundShippingType[$refundReturn['refundShippingType']]['name'];
        $refundReturn['refundText'] = $refundReturnDao->getRefundTextStatus($refundReturn);
        $refundReturn['stateName']=$refundReturn['refundText'];
        $refundReturn['goodsImage'] = ImageUtil::getGoodsImgUrl($refundReturn['goodsImage'], ApiConst::goodsSmallSize);
        $addressDao = \DAO\Order\DAddressModel::getInstance();
        $info = $refundReturn;
        if ($refundReturn['refundType'] == ApiConst::refundTypeGoods) {
            if ($refundReturn['addressId']) {
                $address = $addressDao->getAddressByAddressId($refundReturn['addressId'], $this->daddressField);
            } else {
                $address = $addressDao->getAddressByStoreId($refundReturn['storeId'], $this->daddressField);
            }
            if(!empty($address)){
                $address['isDefault'] = (int)$address['isDefault'];
                $address['company']=isset( $address['company'])? $address['company']:'';
                $info['dAddressInfo'] = $address;
            }else{
                $info['dAddressInfo'] =new \stdClass();
            }

        } else {
            $info['dAddressInfo'] = new \stdClass();
        }
        $info['canPlatformIn'] = $refundReturnDao->isPlatformIn($info) ? ApiConst::one : ApiConst::zero;
        $info['canSendShippingType'] = $refundReturnDao->checkIsAddReturnShipping($info) ? ApiConst::one : ApiConst::zero;
        if($info['refundShippingType']==ApiConst::bySeller){
            if($info['returnType']==ApiConst::returnTypeMustReturn){
                if(!$info['diliverymanId']){
                    $info['diliveryman']=new \stdClass();
                    //  $info['diliveryman']=ArrayConst::defaultDeliveryMan;
                }else{
                    $diliveryMan=$diliveryManDao->findById($info['diliverymanId']);
                    if(!empty($diliveryMan)){
                        $diliveryMan=array(
                            'id'=>$diliveryMan['id'],
                            'trueName'=>$diliveryMan['trueName'],
                            'mobile'=>$diliveryMan['mobile'],
                        );
                        $info['diliveryman']=$diliveryMan;
                    }else{
                        $info['diliveryman']=new \stdClass();
                    }
                }
            }else{
                $info['diliveryman']=new \stdClass();
            }
        }else{
            $info['diliveryman']=new \stdClass();
        }
        if($this->clientType==NameConst::pcClient){
            $orderCommon=$orderDao->getClienOrderCommon($order);
            $info=array_merge($info,$orderCommon);
        }
        if (!$refundReturn) {
            ErrorModel::throwException(CodeConfigModel::orderError);
        } else {
            return $info;
        }
    }

    //申请平台介入
    public function platformIn($buyerId, $refundId, $platFormMessage = DescribeConst::unagreeSellerProccess)
    {
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
        $orderDao=\DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $orderGoodsDao=\DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
        $where['buyer_id']=$buyerId;
        $where['refund_id']=$refundId;
        $res= $refundReturnDao->find($where,$refundReturnDao->refundDetailField);
        if(isset($res['isPlatformIn']) && !empty($res['isPlatformIn'])){
            ErrorModel::throwException(CodeConfigModel::platFormAreadyIn);
        }
        $re= $refundReturnDao->updateStatusByBuyerIdAndRefundId($buyerId, $refundId, $platFormMessage);
        if ($re) {
            $whereOrderGoods['rec_id']=$res['orderGoodsId'];
            $updateData['refund_state_name']=OrderConst::platFromProccess;
            $orderGoodsDao->update($whereOrderGoods,$updateData);
            $refundReturnDao->deleteRefundCache($buyerId,$refundId);
            $orderDao->deleteOrderCache($buyerId,$res['orderId'],$res['storeId']);
            return true;
        } else {
            return false;
        }
    }

    //买家添加退货物流信息
    public function addRefundShipping($memberId, $data)
    {
        $refundId = $data['refundId'];
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
        $retfundReturn = $refundReturnDao->findByMemberIdAndRefundId($memberId, $refundId, $this->refundReturnField);

        if (!empty($retfundReturn)) {
            if ($refundReturnDao->checkIsAddReturnShipping($retfundReturn) === TRUE) {
                $refundReturnDao->deleteRefundCache($memberId,$refundId);
                if (!$refundReturnDao->updateReturnShippingByRefundId($refundId, $data)) {
                    ErrorModel::throwException($refundReturnDao->errorCode);
                };
            } else {
                ErrorModel::throwException($refundReturnDao->errorCode);
            }
        } else {
            ErrorModel::throwException(CodeConfigModel::notExistRefund);
        }
    }

    //获得退货退款的快递公司
    public function getAllExpress()
    {
        $expressDao = \DAO\Order\ExpressModel::getInstance();
        return $expressDao->getExpressConst();
    }


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

        return self::$_instance;
    }
}
