<?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 $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,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,seller_state as sellerState,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 $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 ';
    }

    /**
     * 退款列表
     *
     */
    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);
        $shippingTypes = array_values(ArrayConst::refundShippingType);
        $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);
        }
        //获得订单商品
        $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);
        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,
            '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),
        );
        $refundCondition = $orderInfo['refundCondition'] ? unserialize($orderInfo['refundCondition']) : array();
        $returnData['needShippingFee'] = $orderInfo['needShippingFee'];

        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'];
            }
            $returnData['refundAmount'] = $refundAmount - $orderInfo['refundAmount'] - $returnData['needShippingFee'] + $shippingFee;
//             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);
        $whereRefund['goods_id']=$refund['goodsId'];
        $whereRefund['buyer_id']=$memberId;
        $whereRefund['order_id']=$orderInfo['orderId'];
        $refundOne=$refundReturnDao->find($whereRefund);
        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']) {
            if (($refundAmount < ApiConst::zero) || ($refundAmount > $orderGoods['goodsPayPrice'])) {
                $refundAmount = $orderGoods['goodsPayPrice'];
            }
        } 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);
        $refundReturnDao->deleteRefundCache($memberId);
        if ($state) {
            $refundStateName=$refundReturnDao->getRefundTextStatus($refundArrayUnLine);
            $orderGoodsDao->update(array('rec_id'=>$orderGoods['recId']),array('refund_state_name'=>$refundStateName,'refund_id'=>$state));
            $orderLogDao->addRefundOrderLog($orderInfo['orderId'],$refundArray['refund_type'],DescribeConst::buyer,$orderInfo['buyerName'],$orderInfo['orderState']);
            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();
        $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);
        $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['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']);
        }
        //平台操作类型
        $refundReturn['platformStateName'] = ArrayConst::platformState[$refundReturn['platformState']];
       $refundReturn['refundShippingTypeName'] = ArrayConst::refundShippingType[$refundReturn['refundShippingType']]['name'];
        $refundReturn['refundText'] = $refundReturnDao->getRefundTextStatus($refundReturn);
        $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'];
                $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']=ArrayConst::defaultDeliveryMan;
                }else{
                    $diliveryMan=$diliveryManDao->findById($info['diliverymanId']);
                    if(!empty($diliveryMan)){
                        $diliveryMan=array(
                            'id'=>$diliveryMan['id'],
                            'trueName'=>$diliveryMan['true_name'],
                            'mobile'=>$diliveryMan['mobile'],
                        );
                        $info['diliveryman']=$diliveryMan;
                    }else{
                        $info['diliveryman']=new \stdClass();
                    }
                }
            }else{
                $info['diliveryman']=new \stdClass();
            }
        }else{
            $info['diliveryman']=new \stdClass();
        }
        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;
    }
}
