<?php

/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 16/9/28
 * Time: 上午12:09
 */
require_once (BASE_ROOT_PATH . '/helper/goods_helper.php');
require_once (BASE_ROOT_PATH . '/helper/account_helper.php');
require_once (BASE_ROOT_PATH . '/helper/goods/commonid_helper.php');


class refund_item
{
    const REFUND_MONEY = 1;
    const RETURN_GOODS = 2;

    static $seller_state = array(1 => "待审核",2 => "同意", 3 => "不同意");
    static $refund_state = array(1 => "处理中",2 => "待管理员处理", 3 => "已完成");
    static $refund_type  = array(1 => "退款",2 => "退货");
    static $return_type  = array(1 => "不用退货",2 => "需要退货");
    static $order_goods_type  = array(1 => "普通商品",2 => "团购商品",3 => "限时折扣商品",4 => "组合套装");
    static $goods_state  = array(1 => "待发货",2 => "待收货",3 => "未收到",4 => "已收货");
    static $payments  = array('bonus' => "红包支付","predeposit" => "红包支付","online" => "在线支付",
        "alipay" => "支付宝",'wxpay' => "微信支付",'cmbpay' => "一网通支付");

    public function __construct()
    {
    }

    static public function get_price($goods_info,$order_id,$goods_id,&$price,&$spec)
    {
        $price = 0.00;
        $spec = "";

        if($goods_id <= 0 || $order_id <= 0) {
            return false;
        }
        else
        {
            if(isset($goods_info[$order_id]))
            {
                $order_goods = $goods_info[$order_id];
                if(isset($order_goods[$goods_id])) {
                    $goods = $order_goods[$goods_id];
                    $price = doubleval($goods['goods_price']);
                    $spec = $goods['goods_spec'];
                    if(empty($spec)) $spec = "";
                }
            }
        }
    }

    static public function get_payment($order_infos,$order_id)
    {
        if($order_id <= 0) {
            return "";
        }
        else
        {
            if(isset($order_infos[$order_id]))
            {
                $order = $order_infos[$order_id];
                if(isset($order['payment_code'])) {
                    return self::$payments[$order['payment_code']];
                }
            }
        }

        return "";
    }

    static public function format($info,$goods_info,$order_infos)
    {
        $result['refund_id'] = intval($info['refund_id']);
        $result['order_id'] = intval($info['order_id']);
        $result['order_sn'] =  $info['order_sn'];
        $result['refund_sn'] =  $info['refund_sn'];
        $result['refund_amount'] = doubleval($info['refund_amount']);
        $result['refund_step'] = self::refund_step($info);
        $result['refund_type'] = intval($info['refund_type']);
        $result['refund_type_desc'] = self::$refund_type[intval($info['refund_type'])];
        $result['add_time'] = intval($info['add_time']);

        $result['goods_name'] =  empty($info['goods_name']) ? "" : $info['goods_name'];
        $image = empty($info['goods_image']) ? "" : $info['goods_image'];
        $result['goods_image'] = cthumb($image, 480, $info['store_id']);
        $result['goods_id'] = intval($info['goods_id']);
        $result['rec_id']   = intval($info['order_goods_id']);
        $result['goods_num'] = intval($info['goods_num']);
        $result['order_goods_type'] = self::$order_goods_type[intval($info['order_goods_type'])];
        $result['goods_state'] = self::$goods_state[intval($info['goods_state'])];

        self::get_price($goods_info,$result['order_id'],$result['goods_id'],$price,$spec);

        $result['goods_price'] = $price;
        $result['goods_spec'] = $spec;
        $result['payment_desc'] = self::get_payment($order_infos,$result['order_id']);

        $result['seller_state'] = self::$seller_state[intval($info['seller_state'])];
        $result['refund_state'] = self::$refund_state[intval($info['refund_state'])];
        $result['buyer_message'] =  empty($info['buyer_message']) ? "" : $info['buyer_message'];
        $result['seller_message'] =  empty($info['seller_message']) ? "" : $info['seller_message'];
        $result['admin_message'] =  empty($info['admin_message']) ? "" : $info['admin_message'];


        //$result['return_type'] = intval($info['return_type']); //'退货类型:1为不用退货,2为需要退货,默认为1'
        //$result['order_lock'] = intval($info['order_lock']);   //'订单锁定类型:1为不用锁定,2为需要锁定,默认为1',
        //$result['seller_time'] = intval($info['seller_time']);
        //$result['admin_time'] = intval($info['admin_time']);
        //$result['ship_time'] = intval($info['ship_time']);
        //$result['reason_id'] = intval($info['reason_id']);

        $result['shipping_code'] = empty($info['invoice_no']) ? "" : $info['invoice_no']; //物流编码
        $result['express_id'] = intval($info['express_id']);
        $result['delay_time'] = intval($info['delay_time']);
        $result['receive_time'] = intval($info['receive_time']);
        $result['receive_message'] = empty($info['receive_message']) ? "" : $info['receive_message'];
        $result['reason_info'] =  empty($info['reason_info']) ? "" : $info['reason_info'];

        return $result;
    }

    private static function refund_step($info)
    {
        $state = 1;
        $type = intval($info['refund_type']);
        $seller_time = intval($info['seller_time']);
        $admin_time = intval($info['admin_time']);
        $ship_time = intval($info['ship_time']);
        $return_type = intval($info['return_type']);

        if($type == self::REFUND_MONEY)
        {
            if($seller_time > 0) {
                $state = 2;
            }
            if($admin_time > 0) {
                $state = 3;
            }
        }
        else if($type == self::RETURN_GOODS)
        {
            if($seller_time > 0) {
                $state = 2;
            }
            if($ship_time > 0 || $return_type == 1) {
                $state = 3;
            }
            if($admin_time > 0) {
                $state = 4;
            }
        }
        else
        {

        }
        return $state;
    }
}

class refund_helper
{
    private $member_id;
    public function __construct($member_id)
    {
        $this->member_id = intval($member_id);
    }

    private function format($refund_list,$goods_info,$order_infos)
    {
        $result = [];
        foreach ($refund_list as $item) {
            $result[] = refund_item::format($item,$goods_info,$order_infos);
        }

        return $result;
    }

    private function goods_info($refund_list,&$order_infos)
    {
        $ids = [];
        foreach ($refund_list as $item) {
            $ids[] = intval($item['order_id']);
        }
        if(empty($ids)) return false;

        $model_order = Model('order');
        $order_list = $model_order->getNormalOrderList(array('order_id' => array('in',$ids)), $this->page_size, '*', 'order_id desc', '', array('order_goods'));

        $order_infos = [];
        $result = [];
        foreach ($order_list as $order)
        {
            $order_id = intval($order['order_id']);
            $order_goods = $order['extend_order_goods'];
            $ex_goods = [];
            foreach ($order_goods as $goods) {
                $goods_id = intval($goods['goods_id']);
                $ex_goods[$goods_id] = $goods;
            }
            $result[$order_id] = $ex_goods;
            $order_infos[$order_id]['payment_code'] = $order['payment_code'];
        }

        return $result;
    }

    public function list_all($page,&$total_page)
    {
        $model_refund = Model('refund_return');
        $condition = array();
        $condition['buyer_id'] = $this->member_id;
        $refund_list = $model_refund->getRefundReturnList($condition,$page);
        $total_page = $model_refund->gettotalpage();
        $goods_info = $this->goods_info($refund_list,$order_infos);

        return $this->format($refund_list,$goods_info,$order_infos);
    }

    public function view($refund_id,&$err)
    {
        $model_refund = Model('refund_return');
        $return_list = $model_refund->getRefundReturnList(array('buyer_id' => $this->member_id,'refund_id' => $refund_id));
        if(empty($return_list)) {
            $err = array('code' => errcode::ErrRefundNotExist,'msg' => '无此退款信息.');
            return false;
        }
        $goods_info = $this->goods_info($return_list,$order_infos);
        $refunds = $this->format($return_list,$goods_info,$order_infos);

        return $refunds[0];
    }

    public function ship($refund_id,$express_id,$invoice_no,&$err)
    {
        $model_refund = Model('refund_return');
        $condition = array();
        $condition['buyer_id'] = $this->member_id;
        $condition['refund_id'] = $refund_id;
        $return_list = $model_refund->getReturnList($condition);
        if(empty($return_list)) {
            $err = array('code' => errcode::ErrOrderRefundError,'msg' => "无此退款信息");
            return false;
        }
        $return = $return_list[0];
        if ($return['seller_state'] != '2' || $return['goods_state'] != '1') {
            $err = array('code' => errcode::ErrFrequentlyRequest,'msg' => "该申请已发货");
            return false;
        }

        $refund_array = array();
        $refund_array['ship_time'] = time();
        $refund_array['delay_time'] = time();
        $refund_array['express_id'] = $express_id;
        $refund_array['invoice_no'] = $invoice_no;
        $refund_array['goods_state'] = '2';
        $state = $model_refund->editRefundReturn($condition, $refund_array);
        if ($state) {
            return true;
        } else {
            $err = array('code' => errcode::ErrOrderRefundError,'msg' => "发货失败");
            return false;
        }
    }

    public function refund($order_sn,&$err)
    {
        $order_info = Model('order')->getOrderInfo(array('order_sn' => $order_sn));
        if (empty($order_info)) {
            $err = array("code" => errcode::ErrOrderNotExist,'msg' => errcode::msg(errcode::ErrOrderNotExist));
            return false;
        }

        $model_refund = Model('refund_return');
        $order_id = intval($order_info['order_id']);
        $order = $model_refund->getRightOrderList(array('buyer_id' => $this->member_id, 'order_id' => $order_id));

        $order_amount = $order['order_amount'];//订单金额
        $pd_amount = $order['pd_amount'];
        $order_amount -= $pd_amount;

        $condition = array();
        {
            $condition['buyer_id'] = $order['buyer_id'];
            $condition['order_id'] = $order['order_id'];
            $condition['goods_id'] = '0';
            $condition['seller_state'] = array('lt', '3'); //状态:1为待审核,2为同意,3为不同意
        }

        $refund_list = $model_refund->getRefundReturnList($condition);
        $refund = array();
        if (!empty($refund_list) && is_array($refund_list)) {
            $refund = $refund_list[0];
        }
        $model_trade = Model('trade');
        $order_paid = $model_trade->getOrderState('order_paid');
        $payment_code = $order['payment_code'];
        if ($refund['refund_id'] > 0 || $order['order_state'] != $order_paid || $payment_code == 'offline') {
            $err = array("code" => errcode::ErrOrderNotExist,'msg' => "只有付完款尚未发货的时才能退款。");
            return false;
        }

        $refund_array = array();
        $refund_array['refund_type'] = '1'; //类型:1为退款,2为退货
        $refund_array['seller_state'] = '1';//状态:1为待审核,2为同意,3为不同意
        $refund_array['order_lock'] = '2';  //锁定类型:1为不用锁定,2为需要锁定
        $refund_array['goods_id'] = '0';
        $refund_array['order_goods_id'] = '0';
        $refund_array['reason_id'] = '0';
        $refund_array['reason_info'] = '取消订单，全部退款';
        $refund_array['goods_name'] = '订单商品全部退款';
        $refund_array['refund_amount'] = ncPriceFormat($order_amount);
        $refund_array['buyer_message'] = remove_tags(urldecode($_POST['buyer_message']));
        $refund_array['add_time'] = time();

        $pic_array = array();
        $pic_array['buyer'] = array();
        $refund_array['pic_info'] = serialize($pic_array);
        $refund_id = $model_refund->addRefundReturn($refund_array, $order);

        if ($refund_id) {
            QueueClient::push("reset_fcode",['pay_sn' => $order_info['pay_sn']]);
            $model_refund->editOrderLock($order_id);
            return $refund_id;
        } else {
            $err = array("code" => errcode::ErrOrderRefundError, 'msg' => "退款失败.");
            return false;
        }
    }

    private function reason_list($model_refund)
    {
        $condition = array();
        $reason_data = $model_refund->getReasonList($condition, '', '', 'reason_id,reason_info');

        $reason_list = [];
        foreach ($reason_data as $data) {
            $reason_list[] = $data;
        }
        $reason_list[] = array('reason_id' => 0, 'reason_info' => '其他');

        return $reason_list;
    }

    private function reason_info($model_refund,$reason_id)
    {
        $reason_list = $this->reason_list($model_refund);

        $reasons = [];
        foreach ($reason_list as $data) {
            $reason_id   = intval($data['reason_id']);
            $reason_info = $data['reason_info'];
            $reasons[$reason_id] = $reason_info;
        }

        if (isset($reasons[$reason_id])) {
            return $reasons[$reason_id];
        } else {
            return '其他';
        }
    }

    public function return_info($order_sn,$rec_id,&$err)
    {
        $order_info = Model('order')->getOrderInfo(array('order_sn' => $order_sn));
        if (empty($order_info)) {
            $err = array("code" => errcode::ErrOrderNotExist,'msg' => errcode::msg(errcode::ErrOrderNotExist));
            return false;
        }

        $order_id = intval($order_info['order_id']);
        if ($order_id < 1 || $rec_id < 1) {
            $err = array("code" => errcode::ErrParamter,'msg' => errcode::msg(errcode::ErrParamter));
            return false;
        }

        $model_refund = Model('refund_return');
        $reason_list = $this->reason_list($model_refund);

        $condition = array();
        $condition['buyer_id'] = $this->member_id;
        $condition['order_id'] = $order_id;
        $order = $model_refund->getRightOrderList($condition, $rec_id);

        $order_amount = $order['order_amount'];//订单金额
        $order_refund_amount = $order['refund_amount'];//订单退款金额
        $goods_list = $order['goods_list'];
        $goods = $goods_list[0];
        $goods_pay_price = $goods['goods_pay_price'];//商品实际成交价
        if ($order_amount < ($goods_pay_price + $order_refund_amount)) {
            $goods_pay_price = $order_amount - $order_refund_amount;
            $goods['goods_pay_price'] = $goods_pay_price;
        }

        $condition = array();
        $condition['buyer_id'] = $order['buyer_id'];
        $condition['order_id'] = $order['order_id'];
        $condition['order_goods_id'] = $rec_id;
        $condition['seller_state'] = array('lt', '3');
        $refund_list = $model_refund->getRefundReturnList($condition);
        $refund = array();
        if (!empty($refund_list) && is_array($refund_list)) {
            $refund = $refund_list[0];
        }

        $refund_state = $model_refund->getRefundState($order);//根据订单状态判断是否可以退款退货 '申请状态:1为处理中,2为待管理员处理,3为已完成,默认为1',
        if ($refund['refund_id'] > 0) {
            $err = array("code" => errcode::ErrOrderRefundError,'msg' => "不能重复退货");
            return false;
        }

        if ($refund_state != 1) {
            $err = array("code" => errcode::ErrOrderState,'msg' => '请确认订单状态，在已经付款后才能退款，已经发货后才能退货.');
            return false;
        }

        return array('reason_list' => (array)$reason_list, 'goods' => $goods);
    }

    public function return_goods($order_sn,$rec_id,$goods_num,$refund_amount,$reason_id,$buyer_msg,&$err)
    {
        $order_info = Model('order')->getOrderInfo(array('order_sn' => $order_sn));
        if (empty($order_info) || intval($order_info['order_id'] < 1)) {
            $err = array("code" => errcode::ErrOrderNotExist,'msg' => errcode::msg(errcode::ErrOrderNotExist));
            return false;
        }
        $order_id = intval($order_info['order_id']);

        $model_refund = Model('refund_return');
        $reson_info = $this->reason_info($model_refund,$reason_id);
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        $condition = array();
        $condition['buyer_id'] = $this->member_id;
        $condition['order_id'] = $order_id;
        $order = $model_refund->getRightOrderList($condition, $rec_id);

        $order_id = $order['order_id'];
        $order_amount = $order['order_amount'];//订单金额
        $order_refund_amount = $order['refund_amount'];//订单退款金额
        $goods_list = $order['goods_list'];
        $goods = $goods_list[0];
        $goods_pay_price = $goods['goods_pay_price'];//商品实际成交价
        if ($order_amount < ($goods_pay_price + $order_refund_amount)) {
            $goods_pay_price = $order_amount - $order_refund_amount;
            $goods['goods_pay_price'] = $goods_pay_price;
        }

        $goods_id = $goods['rec_id'];
        $condition = array();
        $condition['buyer_id'] = $order['buyer_id'];
        $condition['order_id'] = $order['order_id'];
        $condition['order_goods_id'] = $goods_id;
        $condition['seller_state'] = array('lt', '3');
        $refund_list = $model_refund->getRefundReturnList($condition);
        $refund = array();
        if (!empty($refund_list) && is_array($refund_list)) {
            $refund = $refund_list[0];
        }
        $refund_state = $model_refund->getRefundState($order);
        if ($refund['refund_id'] > 0 || $refund_state != 1) {
            $err = array("code" => errcode::ErrOrderState,'msg' => errcode::msg(errcode::ErrOrderState));
            return false;
        }

        $refund_array = array();
        if (($refund_amount < 0) || ($refund_amount > $goods_pay_price)) {
            $refund_amount = $goods_pay_price;
        }
        if (($goods_num < 0) || ($goods_num > $goods['goods_num'])) {
            $goods_num = 1;
        }

        $refund_array['reason_info'] = $reson_info;
        $refund_array['reason_id'] = $reason_id;
        $refund_array['pic_info'] = serialize(array('buyer' => array()));

        $model_trade = Model('trade');
        $order_shipped = $model_trade->getOrderState('order_shipped');//订单状态30:已发货
        if ($order['order_state'] == $order_shipped) {
            $refund_array['order_lock'] = '2';//锁定类型:1为不用锁定,2为需要锁定
        }
        $refund_array['refund_type'] =  2;//类型:1为退款,2为退货
        $refund_array['return_type'] = '2';//退货类型:1为不用退货,2为需要退货
        if ($refund_array['refund_type'] != '2') {
            $refund_array['refund_type'] = '1';
            $refund_array['return_type'] = '1';
        }
        $refund_array['seller_state'] = '1';//状态:1为待审核,2为同意,3为不同意
        $refund_array['refund_amount'] = ncPriceFormat($refund_amount);
        $refund_array['goods_num'] = $goods_num;
        $refund_array['buyer_message'] = $buyer_msg;
        $refund_array['add_time'] = time();
        $refund_id = $model_refund->addRefundReturn($refund_array, $order, $goods);

        if ($refund_id)
        {
            if ($order['order_state'] == $order_shipped) {
                $model_refund->editOrderLock($order_id);
            }
            QueueClient::push("reset_fcode",['pay_sn' => $order_info['pay_sn']]);
            return true;
        }
        else {
            $err = array("code" => errcode::ErrOrderRefundError,'msg' => "退货失败");
            return false;
        }
    }
}

class order_action
{
    public function change_state($state_type,$order_id)
    {
        $model_order = Model('order');

        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['buyer_id'] = $_SESSION['member_id'];
        $order_info	= $model_order->getOrderInfo($condition);

        if($state_type == 'order_cancel') {
            $result = $this->order_cancel($order_info);
        } else if ($state_type == 'order_receive') {
            $result = $this->order_receive($order_info);
        } else if (in_array($state_type,array('order_delete','order_drop','order_restore'))){
            $result = $this->order_recycle($order_info, $state_type);
        } else {
            return false;
        }

        return $result['state'];
    }

    private function order_cancel($order_info)
    {
        $model_order = Model('order');
        $logic_order = Logic('order');
        $if_allow = $model_order->getOrderOperateState('buyer_cancel',$order_info);
        if (!$if_allow) {
            return callback(false,'无权操作');
        }
        $ret = $logic_order->changeOrderStateCancel($order_info,'buyer', $_SESSION['member_name']);
        if($ret['state']) {
            QueueClient::push('onPredeposit',
                array('change_type' => 'order_cancel','buyer_id'=>$order_info['buyer_id'],'order_sn'=>$order_info['order_sn']));
        } else {
            Log::record('用户取消订单失败SN:' . $order_info['order_sn'],Log::ERR);
        }
        return $ret;
    }
    private function order_receive($order_info)
    {
        $model_order = Model('order');
        $logic_order = Logic('order');
        $if_allow = $model_order->getOrderOperateState('receive',$order_info);
        if (!$if_allow) {
            return callback(false,'无权操作');
        }

        return $logic_order->changeOrderStateReceive($order_info,'buyer',$_SESSION['member_name']);
    }
    private function order_recycle($order_info, $state_type) {
        $model_order = Model('order');
        $logic_order = Logic('order');
        $state_type = str_replace(array('order_delete','order_drop','order_restore'), array('delete','drop','restore'), $state_type);
        $if_allow = $model_order->getOrderOperateState($state_type,$order_info);
        if (!$if_allow) {
            return callback(false,'无权操作');
        }
        return $logic_order->changeOrderStateRecycle($order_info,'buyer',$state_type);
    }
}

class order_helper
{
    private $mOrders;
    private $mod_refund;
    private $mod_order;

    public function __construct($order_list)
    {
        $this->mod_order = Model('order');
        $this->mod_refund = Model('refund_return');
        $this->mOrders = $this->mod_refund->getGoodsRefundList($order_list);
    }

    private function action_title($key)
    {
        static $actions = array("if_cancel" => "取消订单",
                                "if_refund_cancel" => "退款",
                                "if_payment" => "立即支付",
                                "if_receive" => "确认收货",
                                "if_deliver" => "查看物流",
                                "if_evaluation" => "评价赚红包",
                                "if_delete" => "删除订单",
                                "if_lock" => "退款退货中");
        return $actions[$key];
    }

    private function actions($order)
    {
        $state['if_payment'] = $this->mod_order->getOrderOperateState('payment',$order);
        //显示取消订单
        $state['if_cancel'] = $this->mod_order->getOrderOperateState('buyer_cancel', $order);
        //显示退款取消订单
        $state['if_refund_cancel'] = $this->mod_order->getOrderOperateState('refund_cancel', $order);
        //显示收货
        $state['if_receive'] = $this->mod_order->getOrderOperateState('receive', $order);
        //显示物流跟踪
        $state['if_deliver'] = $this->mod_order->getOrderOperateState('deliver', $order);
        //显示评价
        $state['if_evaluation'] = $this->mod_order->getOrderOperateState('evaluation', $order);
        //显示删除
        $state['if_delete'] = $this->mod_order->getOrderOperateState('delete', $order);

        $state['if_lock'] = $this->mod_order->getOrderOperateState('lock', $order);

        $actions = [];
        foreach ($state as $key => $value) {
            if ($value == true) {
                $item['action'] = $key;
                $item['title']  = $this->action_title($key);
                $actions[] = $item;
            }
        }

        return $actions;
    }

    private function payment_desc($payment_code)
    {
        static $payments  = array('bonus' => "红包支付","predeposit" => "红包支付","online" => "在线支付",
            "alipay" => "支付宝",'wxpay' => "微信支付",'cmbpay' => "一网通银行卡支付");
        if(isset($payments[$payment_code])) {
            return $payments[$payment_code];
        } else {
            return "";
        }
    }

    private function order_info($order)
    {
        $result["order_id"] = intval($order["order_id"]);
        $result["order_sn"] = $order["order_sn"];
        $result["pay_sn"] = $order["pay_sn"];
        $result["add_time"] = intval($order["add_time"]);
        $result["payment_code"] = $order["payment_code"];
        $result["payment_desc"] = $this->payment_desc($order["payment_code"]);
        $result['buyer_id'] = intval($order['buyer_id']);

        $result["payment_time"] = intval($order["payment_time"]);
        $result["finnshed_time"] = intval($order["finnshed_time"]);
        $result["goods_amount"] = $this->goods_amount($order);//doubleval($order["goods_amount"]);
        $result["order_amount"] = doubleval($order["order_amount"]);
        $result["rcb_amount"] = doubleval($order["rcb_amount"]);
        $result["pd_amount"] = doubleval($order["pd_amount"]);
        $result['bonus_rates'] = $this->formate_rates(unserialize($order["bonus_rate"]),doubleval($order["pd_amount"]));
        $result["shipping_fee"] = doubleval($order["shipping_fee"]);
        $result["evaluation_state"] = intval($order["evaluation_state"]);
        $result["order_state"] = intval($order["order_state"]);
        $result["refund_state"] = intval($order["refund_state"]);
        $result["refund_amount"] = doubleval($order["refund_amount"]);
        $result["delay_time"] = intval($order["delay_time"]);
        $result["shipping_code"] = empty($order["shipping_code"]) ? "" : $order["shipping_code"];
        $result["trade_no"] = $order["trade_no"];
        $result["state_desc"] = $order["state_desc"];
        $result['pay_cash'] = $result["order_amount"] - $result["pd_amount"];
        $result['full_discount'] = $result["goods_amount"] - $order["goods_amount"];
        $result['full_desc'] = $this->full_desc($order);

        if ($result['order_state'] == ORDER_STATE_NEW) {
            $result['cancel_time'] = $result['add_time'] + ORDER_AUTO_CANCEL_DAY * 24 * 3600;
        } else {
            $result['cancel_time'] = 0;
        }

        $refund_state = 0;
        $order['refund_id'] = intval($this->mod_refund->getRefundId($order,$refund_state));
        $result["refund_state"] = intval($refund_state);

        return $result;
    }

    private function formate_rates($rates,$pd_amount)
    {
        $result = [];
        if(empty($rates))
        {
            if(intval($pd_amount * 100 + 0.5) > 0) {
                $item['rate'] = 30;
                $item['total'] = $pd_amount;
                $result[] = $item;
            } else {
                return null;
            }
        }
        else
        {
            foreach ($rates as $rate => $val) {
                $item['rate'] = $rate;
                $item['total'] = $val;
                $result[] = $item;
            }
        }
        
        return $result;
    }

    private function full_desc($order)
    {
        $order_info = $order['extend_order_common'];

        $info = '';
        if(isset($order_info['promotion_info']))
        {
            $info = $order_info['promotion_info'];
            $ret = preg_match('#(.*?)<a.*?title=("|\')(.*?)\2.*?>.*?</a>#s',$info,$matches);
            if($ret != false && count($matches) == 4) {
                $info = $matches[1] . $matches[3];
            }
        }

        return (is_null($info) || empty($info)) ? "" : $info;
    }

    private function goods_amount($order)
    {
        $goods_amount = doubleval($order['goods_amount']);
        $goods_list = $order['extend_order_goods'];
        if(empty($goods_list) || !is_array($goods_list)) {
            return $goods_amount;
        } else {
            $goods_amount = 0.00;
        }
        foreach ($goods_list as $goods) {
            $goods_amount += doubleval($goods['goods_price']) * intval($goods['goods_num']);
        }

        return $goods_amount;
    }

    private function order_goods($order)
    {
        $result = [];
        $order_goods = $order['extend_order_goods'];
        if(empty($order_goods)) return $result;

        foreach ($order_goods as $val)
        {
            $goods["rec_id"] = intval($val["rec_id"]);
            $goods["order_id"] = intval($val["order_id"]);
            $goods["goods_id"] = intval($val["goods_id"]);
            $commonid = commonid_helper::instance()->common_id($goods["goods_id"]);
            if($commonid == false) {
                continue;
            }
            $goods["goods_commonid"] = $commonid;
            $goods["goods_name"] = $this->goods_name($val["goods_name"]);
            $goods["goods_price"] = doubleval($val["goods_price"]);
            $goods["goods_num"] = intval($val["goods_num"]);
            $goods["goods_image"] = cthumb($val['goods_image'], 480, $val['store_id']);
            $goods["goods_pay_price"] = doubleval($val["goods_pay_price"]);
            $goods["store_id"] = intval($val["store_id"]);
            $goods["buyer_id"] = intval($val["buyer_id"]);
            $goods["goods_type"] = intval($val["goods_type"]);
            $goods["type_desc"] = $this->type_desc($goods["goods_type"]);

            $goods["promotions_id"] = intval($val["promotions_id"]);
            $goods["gc_id"] = intval($val["gc_id"]);
            $goods["goods_spec"] = $this->goods_spec($val["goods_spec"],$val["goods_name"]);
            $goods["refund"] = isset($val["refund"]) ? intval($val["refund"]) : 0;

            $refund_state = 0;
            $goods['refund_id'] = intval($this->mod_refund->getRefundIdForGood($val,$refund_state));
            $goods['refund_state'] = intval($refund_state);
            $result[] = $goods;
        }

        return $result;
    }

    private function goods_name($goods_name)
    {
        return $goods_name;
//        if(empty($goods_spec))
//        {
//            $goods_name = trim($goods_name);
//            $data = explode(' ',$goods_name);
//            $count = count($data);
//            if($count > 1) {
//                $goods_spec = $data[$count -1];
//            } else {
//                $goods_spec = '';
//            }
//        }
//
//        return $goods_spec;
    }

    private function goods_spec($goods_spec,$goods_name)
    {
        if(empty($goods_spec))
        {
            $goods_name = trim($goods_name);
            $data = explode(' ',$goods_name);
            $count = count($data);
            if($count > 1) {
                $goods_spec = $data[$count -1];
            } else {
                $goods_spec = '';
            }
        }

        return $goods_spec;
    }

    private function type_desc($goods_type)
    {
        $descs = array(1 => "普通商品",2 => "抢购", 3 => "限购", 4 => "套装", 5 => "赠品");
        if($goods_type > 0 && $goods_type <= count($descs)) {
            return $descs[$goods_type];
        } else {
            return "";
        }
    }

    private function reciver_info($order)
    {
        $info = $order['reciver_info'];
        $info['reciver_name'] = $order['reciver_name'];

        return $info;
    }
    private function invoice_info($order)
    {
        $result = [];
        $result['inv_content'] = "";
        $result['inv_title'] = "";
        $result['inv_id'] = 0;

        if(isset($order['extend_order_common']))
        {
            $order_common = $order['extend_order_common'];
            if(isset($order_common['invoice_info']))
            {
                $invoice_info = $order_common['invoice_info'];
                foreach ($invoice_info as $key => $value)
                {
                    if($key == '内容') {
                        $result['inv_content'] = $value;
                    }
                    elseif($key == '抬头') {
                        $item['inv_title'] = $value;
                    }
                }
            }
        }

        return $result;
    }

    public function format()
    {
        $result = [];
        foreach ($this->mOrders as $order) {
            $item['order_info'] = $this->order_info($order);
            $actions = $this->actions($order);
            $item['actions'] = $actions;
            $order_goods = $this->order_goods($order);
            if($order_goods == false) {
                continue;
            }
            $item['order_goods'] = $order_goods;
            $item['reciver_info'] = $this->reciver_info($order);
            $item['invoice_info'] = $this->invoice_info($order);

            $result[] = $item;
        }

        return $result;
    }
}
