<?php
/**
 * 会员退款退货
 *
 *
 *
 * 全部退款，单个商品退货
 *
 */

//use Shopnc\Tpl;

defined('InShopNC') or exit('Access Invalid!');

require_once(BASE_ROOT_PATH . '/helper/order_helper.php');
require_once (BASE_ROOT_PATH . '/helper/fcode/operator.php');
require_once (BASE_ROOT_PATH . '/helper/fcode/send_manager.php');
require_once (BASE_ROOT_PATH . '/helper/user_session/fcode.php');

class member_refundControl extends mbMemberControl
{
    public function __construct()
    {
        parent::__construct();
    }

    public function listOp()
    {
        $helper = new refund_helper($_SESSION['member_id']);
        $refund_list = $helper->list_all($this->page_size(),$total_page);
        return self::outsuccess(array('refunds' => $refund_list,'mobile_page' => mobile_page($total_page)));
    }

    public function viewOp()
    {
        $refund_id = $_GET['refund_id'];
        if (!isset($refund_id)) {
            return self::outerr(errcode::ErrParamter);
        }
        $helper = new refund_helper($_SESSION['member_id']);
        $refund = $helper->view($refund_id,$err);
        if($refund == false) {
            return self::outerr($err['code'],$err['msg']);
        }
        else
        {
            $order = $this->get_order(array('order_id' => $refund['order_id'],'buyer_id' => $_SESSION['member_id']));

            if($order == false) {
                return self::outerr(errcode::ErrParamter,"查不到该订单");
            } else {
                global $config;
                return self::outsuccess(array('refund' => $refund,'order' => $order,'return_address' => $config['return_address']));
            }
        }
    }

    public function order_refundOp()
    {
        $order_sn = $_GET['order_sn'];
        if(!isset($order_sn) || empty($order_sn)) {
            return self::outerr(errcode::ErrParamter);
        }
        $helper = new refund_helper($_SESSION['member_id']);
        $refund_id = $helper->refund($order_sn,$err);
        if($refund_id == false) {
            return self::outerr($err['code'],$err['msg']);
        }
        else
        {
            $fcode = new user_session\fcode(true);
            $order = $this->get_order(array('order_sn' =>$order_sn,'buyer_id' => $_SESSION['member_id']));
            if($order == false) {
                return self::outerr(errcode::ErrParamter,"查不到该订单");
            } else {
                Logic('delivery')->cancel_oms($order_sn);
                return self::outsuccess(array('order' => $order));
            }
        }
    }

    public function return_infoOp()
    {
        $order_sn = $_GET['order_sn'];
        $rec_id = intval($_GET['rec_id']);
        if(empty($order_sn) || $rec_id <= 0) {
            return self::outerr(errcode::ErrParamter);
        }

        $helper = new refund_helper($_SESSION['member_id']);
        $ret = $helper->return_info($order_sn,$rec_id,$err);
        if($ret == false) {
            return self::outerr($err['code'],$err['msg']);
        }
        else
        {
            $reason_list = $ret['reason_list'];
            $goods_pay_price = doubleval($ret['goods']['goods_pay_price']);
            $order = $this->get_order(array('order_sn' =>$order_sn,'buyer_id' => $_SESSION['member_id']));
            if ($order != false)
            {
                $order_goods = &$order['order_goods'];
                foreach ($order_goods as &$item)
                {
                    if($item['rec_id'] == $rec_id) {
                        $item['goods_pay_price'] = $goods_pay_price;
                        break;
                    }
                }
                return self::outsuccess(array("reason_list" => $reason_list,'rec_id' => $rec_id,'order' => $order));
            }
            else
            {
                return self::outerr(errcode::ErrParamter,"查不到该订单");
            }
        }
    }

    public function goods_returnOp()
    {
        $order_sn = $_GET['order_sn'];
        $rec_id = intval($_GET['rec_id']);
        $buyer_msg = isset($_GET['buyer_message']) ? remove_tags(urldecode($_GET['buyer_message'])) : '';
        $goods_num = intval($_GET['goods_num']);
        $refund_amount = doubleval($_GET['refund_amount']);
        $reason_id = intval($_GET['reason_id']);//退货退款原因

        if(empty($order_sn) || $rec_id <= 0) {
            return self::outerr(errcode::ErrParamter);
        }
        $helper = new refund_helper($_SESSION['member_id']);
        $ret = $helper->return_goods($order_sn,$rec_id,$goods_num,$refund_amount,$reason_id,$buyer_msg,$err);

        if($ret == false) {
            return self::outerr($err['code'],$err['msg']);
        }
        else
        {
            $fcode = new user_session\fcode(true);
            $order = $this->get_order(array('order_sn' =>$order_sn,'buyer_id' => $_SESSION['member_id']));
            if($order == false) {
                return self::outerr(errcode::ErrParamter,"查不到该订单");
            } else {
                return self::outsuccess(array('order' => $order));
            }
        }
    }

    public function shipOp()
    {
        $refund_id = intval($_GET['refund_id']);
        $ship_code = remove_tags(urldecode($_GET['shipping_code']));
        $express_id = intval($_GET['express_id']);
        if($refund_id <= 0 || empty($ship_code)) {
            return self::outerr(errcode::ErrParamter);
        }

        $helper = new refund_helper($_SESSION['member_id']);
        $ret = $helper->ship($refund_id,$express_id,$ship_code,$err);
        if($ret == true) {
            return self::outsuccess(NULL);
        } else {
            return self::outerr($err['code'],$err['msg']);
        }
    }

    private function get_order($condition)
    {
        $model_order = Model('order');
        $order_list = $model_order->getNormalOrderList($condition, $this->page_size, '*', 'order_id desc', '', array('order_common','order_address', 'order_goods'));
        $order_helper = new order_helper($order_list);
        $orders = $order_helper->format();
        $model_order->cls();
        if(!empty($orders)) {
            return $orders[0];
        } else {
            return false;
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 向商家添加全部退款请求,即付完款后取消订单
     */
    public function add_refund_allOp()
    {
        $order_info = Model('order')->getOrderInfo(array('order_sn' => $_GET['order_sn']));
        if (empty($order_info)) {
            return self::outerr(errcode::ErrOrderNotExist);
        }

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

        $order_amount = $order['order_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');//订单状态20:已付款
        $payment_code = $order['payment_code'];//支付方式
        if ($refund['refund_id'] > 0 || $order['order_state'] != $order_paid || $payment_code == 'offline') {//检查订单状态,防止页面刷新不及时造成数据错误
            return self::outerr(errcode::ErrOrderState, "只有付完款尚未发货的时才能退款。");
        }

        $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) {
            $model_refund->editOrderLock($order_id);
            return self::outsuccess(array("ret" => 1, "refund_id" => $refund_id, "order_sn" => $_GET['order_sn']));
        } else {
            return self::outerr(errcode::ErrOrderRefundError, "退款失败.");
        }
    }

    //该函数用来返回退款具体信息。已经付款，未发货时退款，退货。
    public function refund_one_infoOp()
    {
        $order_info = Model('order')->getOrderInfo(array('order_sn' => $_GET['order_sn']));
        if (empty($order_info)) {
            return self::outerr(errcode::ErrOrderNotExist);
        }
        $order_id = intval($order_info['order_id']);
        $order_goods_id = intval($_GET['order_goods_id']);//订单商品表编号
        if ($order_id < 1 || $order_goods_id < 1) {       //参数验证
            return self::outerr(errcode::ErrParamter, "商品参数错误.");
        }

        $model_refund = Model('refund_return');
        $condition = array();
        $reason_data = $model_refund->getReasonList($condition, '', '', 'reason_id,reason_info');//退款退货原因
        foreach ($reason_data as $data) {
            $reason_list[] = $data;
        }
        array_push($reason_list, array('reason_id' => 0, 'reason_info' => '其他'));

        $condition = array();
        $condition['buyer_id'] = $_SESSION['member_id'];
        $condition['order_id'] = $order_id;
        $order = $model_refund->getRightOrderList($condition, $order_goods_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) {
            return self::outerr(errcode::ErrOrderRefundError, "不能重复退货.");
        }
        if ($refund_state != 1) {
            return self::outerr(errcode::ErrOrderState, '请确认订单状态，在已经付款后才能退款，已经发货后才能退货.');
        }

        $goods['goods_image'] = cthumb($goods['goods_image'], 360, $order_info['store_id']);
        $goods['order_goods_id'] = $order_goods_id;

        return self::outsuccess(array('ret' => 1, 'reason_list' => (array)$reason_list, 'goods' => $goods));
    }

    //已经付款，未发货时退款。只能单品退款
    public function add_refund_oneOp()
    {
        // if(!isset($_GET['refund_type']) || empty($_GET['refund_type'])
        //     || !in_array($_GET['refund_type'],self::$refund_type))
        // {
        //    return self::outerr(errcode::ErrParamter,"请使用正确的退款类型，1：退款，2:退货.");
        //}
        //$refund_type = $_GET['refund_type'];

        $order_info = Model('order')->getOrderInfo(array('order_sn' => $_GET['order_sn']));
        if (empty($order_info)) {
            return self::outerr(errcode::ErrOrderNotExist);
        }
        $order_id = $order_info['order_id'];
        $order_goods_id = intval($_GET['order_goods_id']);//订单商品表编号
        if ($order_id < 1 || $order_goods_id < 1) {       //参数验证
            return self::outerr(errcode::ErrParamter, "商品参数错误.");
        }
        $buyer_msg = isset($_GET['buyer_message']) ? remove_tags(urldecode($_GET['buyer_message'])) : '';

        $model_refund = Model('refund_return');

        $reason_list = $model_refund->getReasonList();//退款退货原因
        $reason_id = intval($_POST['reason_id']);//退货退款原因
        $reson_info = '其他';
        if (!empty($reason_list[$reason_id])) {
            $reason_array = $reason_list[$reason_id];
            $reson_info = $reason_array['reason_info'];
        }
        $goods_num = intval($_POST['goods_num']);//退货数量
        $refund_amount = doubleval($_POST['refund_amount']);//退款金额

        ////////////////////////////////////////////////////////////////
        $condition = array();
        $condition['buyer_id'] = $_SESSION['member_id'];
        $condition['order_id'] = $order_id;
        $order = $model_refund->getRightOrderList($condition, $order_goods_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) {//检查订单状态,防止页面刷新不及时造成数据错误
            return self::outerr(errcode::ErrOrderState);
        }

        $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);
            }
            return self::outsuccess(array('ret' => 1, "refund_id" => $refund_id, "order_sn" => $_GET['order_sn'], "order_goods_id" => $_GET['order_goods_id']));
        } else {
            return self::outerr(errcode::ErrOrderRefundError, "退货失败.");
        }
    }

    /**
     * 退款或退货退款记录详情
     */
    public function refund_viewOp()
    {
        if (!isset($_GET['refund_id']) || empty($_GET['refund_id'])) {
            return self::outerr(errcode::ErrParamter, "记录参数有误");
        }
        $model_refund = Model('refund_return');
        $condition = array();
        $condition['buyer_id'] = $_SESSION['member_id'];
        $condition['refund_id'] = intval($_GET['refund_id']);
        $condition['seller_state'] = array('lt', '3'); //状态:1为待审核,2为同意,3为不同意
        $refund_fields = 'refund_id,order_id,order_sn,order_goods_id,add_time,refund_type,return_type,seller_time,ship_time,admin_time';
        $refund_list = $model_refund->getRefundReturnList($condition, '', $refund_fields);

        if (empty($refund_list)) {
            return self::outerr(errcode::ErrOrderState);
        }

        $refund = $refund_list[0];
        $refund['refund_state'] = $model_refund->getRefundStatueApp($refund);

        unset($refund['seller_time']);
        unset($refund['ship_time']);
        unset($refund['admin_time']);
        $model_order = Model('order');
        $condition = array();
        $condition['order_id'] = $refund['order_id'];
        $condition['rec_id'] = $refund['order_goods_id'];
        $good_fields = 'goods_id,goods_name,goods_price,goods_num,goods_image,goods_pay_price,goods_type,commis_rate,gc_id,goods_spec';
        $refund['good_list'] = $model_order->getOrderGoodsList($condition, $good_fields);
        return self::outsuccess(array('refund' => $refund));
    }

    /**
     * 用户发货
     */
    public function refund_shipOp()
    {
        $model_refund = Model('refund_return');
        $condition = array();
        $condition['buyer_id'] = $_SESSION['member_id'];
        $condition['refund_id'] = intval($_GET['refund_id']);
        $return_list = $model_refund->getReturnList($condition);
        $return = $return_list[0];
        if ($return['seller_state'] != '2' || $return['goods_state'] != '1') {//检查状态,防止页面刷新不及时造成数据错误
            return self::outerr(errcode::ErrFrequentlyRequest, "该申请已发货");
        }
        $refund_array = array();
        $refund_array['ship_time'] = time();
        $refund_array['delay_time'] = time();
      //  $refund_array['express_id'] = $_POST['express_id'];
        $refund_array['invoice_no'] = remove_tags(urldecode($_POST['invoice_no']));
        $refund_array['goods_state'] = '2';
        $state = $model_refund->editRefundReturn($condition, $refund_array);
        if ($state) {
            return self::outsuccess(array('ret' => 1));
        } else {
            return self::outerr(errcode::ErrOrderRefundError, "发货失败.");
        }
    }
}
