<?php
/**
 * 我的订单
 *
 *
 *
 *

 */

//use Shopnc\Tpl;

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

require_once(BASE_ROOT_PATH . '/helper/kdn_helper.php');
require_once(BASE_ROOT_PATH . '/helper/order_helper.php');
require_once(BASE_ROOT_PATH . '/helper/pay_helper.php');

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

    public function listOp()
    {
        $model_order = Model('order');
        $condition = array();
        $condition['buyer_id'] = $_SESSION['member_id'];
        $order_state = intval(trim($_GET['state']));
        if ($order_state >= 10) {
            $condition['order_state'] = $order_state;
        }

        if ($_GET['state_type'] != '') {
            $condition['order_state'] = str_replace(
                array('state_new','state_pay','state_send','state_success','state_noeval'),
                array(ORDER_STATE_NEW,ORDER_STATE_PAY,ORDER_STATE_SEND,ORDER_STATE_SUCCESS), $_GET['state_type']);
        } else {
            $condition['order_state'] = array("in",array(ORDER_STATE_NEW,ORDER_STATE_PAY,ORDER_STATE_SEND,ORDER_STATE_SUCCESS,ORDER_STATE_CANCEL));
        }

        $order_list_array = $model_order->getNormalOrderList($condition, $this->page_size, '*', 'order_id desc', '', array('order_common','order_address', 'order_goods'));
        $page_count = $model_order->gettotalpage();

        $order_helper = new order_helper($order_list_array);
        $result = $order_helper->format();

        return self::outsuccess(array('orders' => $result,'mobile_page' =>mobile_page($page_count)));
    }
    public function infoOp()
    {
        $pay_sn = $_POST['pay_sn'];
        if(empty($pay_sn)) {
            return self::outerr(errcode::ErrParamter);
        }
        $order = $this->get_order(array("buyer_id" => $_SESSION['member_id'],'pay_sn' => $pay_sn));
        if($order == false) {
            return self::outerr(errcode::ErrOrder);
        } else {
            return self::outsuccess(array('order' => $order));
        }
    }

    public function pay_infoOp()
    {
        $pay_sn = $_POST['pay_sn'];
        if(empty($pay_sn)) {
            return self::outerr(errcode::ErrParamter);
        }
        $order = $this->get_order(array("buyer_id" => $_SESSION['member_id'],'pay_sn' => $pay_sn));
        $pay_ments = pay_helper::pay_types();
        if($order == false) {
            return self::outerr(errcode::ErrOrder);
        } else {
            return self::outsuccess(array('order' => $order,"paytype" => $pay_ments));
        }
    }

    public function change_stateOp()
    {
        $act_type = $_GET['act_type'];
        $order_id = intval($_POST['order_id']);

        $state_type = $this->state_type($act_type);
        if($state_type == false || $order_id <= 0) {
            return self::outerr(errcode::ErrParamter);
        }

        $action = new order_action();
        $fOk = $action->change_state($state_type,$order_id);

        if($fOk == true)
        {
            $order = $this->get_order(array("buyer_id" => $_SESSION['member_id'],'order_id' => $order_id));
            if($order == false) {
                $order = null;
            }

            return self::outsuccess(array("act_type" => $act_type,"order_id" => $order_id, "order" => $order));
        }
        else {
            return self::outerr(errcode::ErrOrder);
        }
    }

    private function state_type($act_type)
    {
        if($act_type == "if_cancel") return "order_cancel";
        if($act_type == "if_delete") return "order_delete";
        if($act_type == "if_receive") return "order_receive";
        return false;
    }

    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 payOp()
    {
        $pay_sn = $_GET['pay_sn'];
        $payment = $_GET['payment'];
        if(empty($pay_sn) || empty($payment)) {
            return self::outerr(errcode::ErrParamter,"支付号或者支付类型错误");
        }

        $out_put = pay_helper::pay($pay_sn,$payment,false,$err);
        if($out_put == false) {
            return self::outerr($err['code'],$err['msg']);
        } else {
            $out_put['payment'] = $payment;
            $out_put['pay_sn']  = $pay_sn;
            return self::outsuccess($out_put);
        }
    }

    ///////////////////////////////////////////////////////////////////下面是老接口///////////////////////////////////////////////////////////////////////////
    public function order_listOp()
    {
        $this->page_size = 1000;
        $model_order = Model('order');
        $condition = array();
        $condition['buyer_id'] = $_SESSION['member_id'];
        $order_state = intval(trim($_GET['state']));
        if ($order_state >= 10) {
            $condition['order_state'] = $order_state;
        }

        $order_list_array = $model_order->getNormalOrderList($condition, $this->page_size, '*', 'order_id desc', '', array('order_address', 'order_goods'));
        $order_group_list = array();
        $order_pay_sn_array = array();

        $model_refund = Model('refund_return');

        foreach ($order_list_array as $value) 
        {
            //显示取消订单
            $value['if_cancel'] = $model_order->getOrderOperateState('buyer_cancel', $value);
            //显示收货
            $value['if_receive'] = $model_order->getOrderOperateState('receive', $value);
            //显示锁定中
            $value['if_lock'] = $model_order->getOrderOperateState('lock', $value);
            //显示物流跟踪
            $value['if_deliver'] = $model_order->getOrderOperateState('deliver', $value);
            //订单是否能退货
            $value['if_refund_return'] = $model_refund->getRefundState($value);

            //商品图
            foreach ($value['extend_order_goods'] as $k => $goods_info) {
                $value['extend_order_goods'][$k]['goods_image_url'] = cthumb($goods_info['goods_image'], 240, $value['store_id']);
                $value['extend_order_goods'][$k]['refund_id']       = (string)$model_refund->getRefundIdForGood($goods_info,$value['extend_order_goods'][$k]['refund_state']);
            }

            $value['refund_id'] = (string)$model_refund->getRefundId($value,$value['refund_state']);
            $order_group_list[$value['pay_sn']]['order_list'][] = $value;

            //如果有在线支付且未付款的订单则显示合并付款链接
            if ($value['order_state'] == ORDER_STATE_NEW) {
                $order_group_list[$value['pay_sn']]['pay_amount'] += $value['order_amount'] - $value['rcb_amount'] - $value['pd_amount'];
            }
            $order_group_list[$value['pay_sn']]['add_time'] = $value['add_time'];

            //记录一下pay_sn，后面需要查询支付单表
            $order_pay_sn_array[] = $value['pay_sn'];
        }

        $new_order_group_list = array();
        foreach ($order_group_list as $key => $value) {
            $value['pay_sn'] = strval($key);
            $new_order_group_list[] = $value;
        }

        $page_count = $model_order->gettotalpage();
        $model_order->cls();

        $array_data = array('order_group_list' => $new_order_group_list);
        if (isset($_GET['getpayment']) && $_GET['getpayment'] == "true") 
        {
            $model_mb_payment = Model('mb_payment');
            $payment_list = $model_mb_payment->getMbPaymentOpenList();
            $payment_array = array();
            if (!empty($payment_list)) 
            {
                foreach ($payment_list as $value) {
                    $payment_array[] = array('payment_code' => $value['payment_code'], 'payment_name' => $value['payment_name']);
                }
            }
            $array_data['payment_list'] = $payment_array;
        }

        $array_data['mobile_page'] = mobile_page($page_count);
        self::outsuccess($array_data);
    }

    public function order_infoOp()
    {
        $model_order = Model('order');
        $condition = array();
        $condition['buyer_id'] = $_SESSION['member_id'];
        $condition['pay_sn'] = $_POST['pay_sn'];
        $order_list_array = $model_order->getNormalOrderList($condition, $this->page_size, '*', 'order_id desc', '', array('order_address', 'order_goods'));

        $model_refund = Model('refund_return');
        $array_data = array();
        foreach ($order_list_array as $value)
        {
            //显示取消订单
            $value['if_cancel'] = $model_order->getOrderOperateState('buyer_cancel', $value);
            //显示收货
            $value['if_receive'] = $model_order->getOrderOperateState('receive', $value);
            //显示锁定中
            $value['if_lock'] = $model_order->getOrderOperateState('lock', $value);
            //显示物流跟踪
            $value['if_deliver'] = $model_order->getOrderOperateState('deliver', $value);

            foreach ($value['extend_order_goods'] as $k => $goods_info) {
                $value['extend_order_goods'][$k]['goods_image_url'] = cthumb($goods_info['goods_image'], 240, $value['store_id']);
                $value['extend_order_goods'][$k]['refund_id']       = (string)$model_refund->getRefundIdForGood($goods_info,$value['extend_order_goods'][$k]['refund_state']);
            }
            $value['refund_id'] = (string)$model_refund->getRefundId($value,$value['refund_state']);
            $array_data[] = $value;
        }

        self::outsuccess(array("order_list" => $array_data));
    }

    /**
     * 取消订单
     */
    public function order_cancelOp()
    {
        $condition = array();
        if (!empty($_POST['order_id'])) {
            $order_id = intval($_POST['order_id']);
            $condition['order_id'] = $order_id;
        } else if (!empty($_POST['order_sn'])) {
            $condition['order_sn'] = trim($_POST['order_sn']);
        } else {
            return self::outerr(errcode::ErrParamter, "请传入order_sn.");
        }

        $model_order = Model('order');
        $logic_order = Logic('order');

        $condition['buyer_id'] = $_SESSION['member_id'];
        Log::record("buyer_id = {$condition['buyer_id']}", Log::DEBUG);

        $order_info = $model_order->getOrderInfo($condition);
        if ($order_info['order_state'] != ORDER_STATE_NEW) {
            Log::record("order_state = {$order_info['order_state']}.", Log::ERR);
            return self::outerr(errcode::ErrOrder, "已支付和已发货订单不能取消.");
        }

        if ($order_info['order_state'] == ORDER_STATE_CANCEL) {
            return self::outsuccess(array('result' => '1'));
        }

        $result = $logic_order->changeOrderStateCancel($order_info, 'buyer', $_SESSION['member_name'], '其它原因');
        if (!$result['state']) {
            return self::outerr(errcode::ErrOrder, $result['msg']);
        } else {
            return self::outsuccess(array('result' => '1'));
        }
    }

    /**
     * 订单确认收货
     */
    public function order_receiveOp()
    {
        $model_order = Model('order');
        $order_id = intval($_POST['order_id']);

        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['buyer_id'] = $_SESSION['member_id'];
        $order_info = $model_order->getOrderInfo($condition);
        $if_allow = $model_order->getOrderOperateState('receive', $order_info);
        if (!$if_allow) {
            return self::outerr(errcode::ErrOrder, '无权操作');
        }

        $logic_order = Logic('order');
        $result = $logic_order->changeOrderStateReceive($order_info, 'buyer', $_SESSION['member_name']);
        if (!$result['state']) {
            return self::outerr(errcode::ErrOrder, $result['msg']);
        } else {
            return self::outsuccess(array('result' => '1'));
        }
    }

    /**
     * 物流跟踪
     */
    public function search_deliverOp()
    {
        $order_id = intval($_POST['order_id']);
        if ($order_id <= 0) {
            return self::outsuccess(NULL,'express/error','wap');
        }

        $model_order = Model('order');
        $condition['order_id'] = $order_id;
        $condition['buyer_id'] = $_SESSION['member_id'];
        $order_info = $model_order->getOrderInfo($condition, array('order_common', 'order_goods'));

        if (empty($order_info) || !in_array($order_info['order_state'], array(ORDER_STATE_SEND, ORDER_STATE_SUCCESS))) {
            return self::outsuccess(NULL,'express/error','wap');
        }

        $express = rkcache('express', true);
        $e_code = $express[$order_info['extend_order_common']['shipping_express_id']]['e_kdn_code'];
        $e_name = $express[$order_info['extend_order_common']['shipping_express_id']]['e_name'];

        $key = "express_{$e_code}_" . $order_info['shipping_code'];
        $deliver_info = rkcache($key);
        if (empty($deliver_info))
        {
            $deliver_info = kdn_helper::query($e_code, $order_info['shipping_code']);
            if ($deliver_info === false || empty($deliver_info)) {
                return self::outsuccess(NULL,'express/error','wap');
            }
            $deliver_info = json_decode(urldecode($deliver_info), true);
            wkcache($key, $deliver_info, 3600);
        }

        $routes = $deliver_info['Traces'];
        krsort($routes);
        switch ($deliver_info['State'])
        {
            case '2':
                $msg = '在途中';
                break;
            case '3':
                $msg = '已签收';
                break;
            case '4':
                $msg = '问题件';
                break;
            default: {
                return self::outsuccess(NULL,'express/error','wap');
            }
        }
        $outdatas = array('query_status' => true,
            'msg_statu' => $msg,'LogisticCode' => $deliver_info['LogisticCode'],'shipper_namer' => $e_name,
            'routes' => $routes);
        return self::outsuccess($outdatas,'express/info','wap');
    }

    /**
     * 获取不同状态下订单数量
     */
    public function orderCountStateOp()
    {
        $result = Model()->table('order')->field('order_state, count(*) as count')->where(array('buyer_id' => $_SESSION['member_id'],'delete_state' => 0))->group('order_state')->select();
        $ret_count = Model('refund_return')->getRefundReturn(array('buyer_id' => $_SESSION['member_id']));
        $result[] = array('order_state' => 'refund_return','count' => strval($ret_count));
        self::outsuccess(array('order_count' => $result));
    }
}
