<?php



$resp = 'local';

if (!defined('EM_ROOT')) {
    require_once '../init.php';
    $action = Input::getStrVar('action');
    Ret::error('不支持的请求');
    $_func = 'api_' . $action;
    $resp = 'api';
    return $_func();
}

$db = Database::getInstance();
$db_prefix = DB_PREFIX;


//var_dump($db_prefix); die;


function apiGetGoodsList($post = []){
    global $db, $db_prefix, $resp;

    d($GLOBALS);
    var_dump($db_prefix); die;

    if(empty($post)){
        $sort_id = Input::getStrVar('sort_id');
        $keyword = Input::getIntVar('keyword');
    }else{
        $sort_id = $post['sort_id'];
        $keyword = $post['keyword'];
    }
    $where = "";
    if(!empty($keyword)){
        $where .= " and g.title like '%{$keyword}%'";
    }

    if($sort_id != 0){
        $where .= " and g.sort_id={$sort_id}";
    }
    $sql = "SELECT 
            g.title, g.cover, g.des, g.type, g.id goods_id, g.des, g.sales, g.sort_id, g.id goods_id, 
            sku.guest_price, sku.user_price, g.stock stock_num, g.stock, 
            mp.member_level mp_level, mp.price mp_price
        FROM {$db_prefix}goods g
        LEFT JOIN {$db_prefix}skus sku ON sku.goods_id = g.id
        LEFT JOIN {$db_prefix}member_price mp ON mp.goods_id = g.id
        WHERE g.is_on_shelf = 1 AND g.delete_time IS NULL {$where}
        GROUP BY sku.sku, sku.goods_id, mp.member_level
        ORDER BY g.index_top DESC, g.sort_top DESC, g.sort_num DESC, g.id asc";

        echo $sql;die;

    $data = $db->fetch_all($sql);
    $goods = [];
    foreach($data as $val){

        if(isset($goods[$val['goods_id']])){
            $goods[$val['goods_id']]['mp'][$val['mp_level']] = $val['mp_price'];
        }else{
            $goods[$val['goods_id']] = $val;
            $goods[$val['goods_id']]['url'] = Url::goods($val['goods_id']);
            $goods[$val['goods_id']]['mp'][$val['mp_level']] = $val['mp_price'];
        }
    }
//        d($data);die;
    foreach($goods as $key => $val){
        if(LEVEL == -1){
            $goods[$key]['price'] = $val['guest_price'];
        }else if(LEVEL == 0){
            $goods[$key]['price'] = $val['user_price'];
        }else{
            if(!empty($val['mp'])){
                foreach($val['mp'] as $k => $v){
                    if($k == LEVEL){
                        $goods[$key]['price'] = $v;
                    }
                }
                if(!isset($goods[$key]['price'])){
                    $goods[$key]['price'] = $val['user_price'];
                }
            }else{
                $goods[$key]['price'] = $val['user_price'];
            }
        }
        $goods[$key]['price'] = number_format ($goods[$key]['price'] / 100, 2);
    }

    doMultiAction('home_goods_list', $goods, $goods);

        d($goods);die;
    return $goods;

}

/**
 * 获取订单的发货内容
 * @post.out_trade_no 订单编号
 * @post.limit 获取数量，为空时获取全部
 */
function api_get_order_serect($post = []){
    global $db, $db_prefix, $resp;
    if(empty($post)){
        $out_trade_no = Input::postStrVar('out_trade_no');
        $limit = Input::postIntVar('limit');
    }else{
        $out_trade_no = $post['out_trade_no'];
        $limit = $post['limit'];
    }
    $order = $db->once_fetch_array("select * from {$db_prefix}order where out_trade_no = '{$out_trade_no}'");
    $child_order = $db->once_fetch_array("select * from {$db_prefix}order_list where order_id = '{$order['id']}'");
    $goods = $db->once_fetch_array("select * from {$db_prefix}goods where id={$child_order['goods_id']}");
    $func = "plugin_goods_{$goods['type']}_get_order_serect";
    $res = $func($db, $db_prefix, $goods, $order, $child_order, $limit);
    if($resp == 'api'){
        Ret::success('success', $res);
    }else{
        return ['code' => 200, 'data' => $res];
    }
}

/**
 * 获取登录用户的订单列表
 */
function api_get_user_order($post = []){
    global $db, $db_prefix, $resp;
    if(empty($post)){

    }else{
        $user_id = $post['user_id'];
    }


    $sql = "SELECT DISTINCT o.id, ol.goods_id, g.type, 
o.out_trade_no, o.up_no, g.title, o.create_time, o.pay_time, o.status, o.amount, ol.quantity, ol.attr_spec, 
ol.attach_user, ol.unit_price, ol.cost_price, o.payment, g.cover 
FROM {$db_prefix}order o 
INNER JOIN {$db_prefix}order_list ol ON o.id = ol.order_id 
LEFT JOIN {$db_prefix}goods g on ol.goods_id = g.id 
where o.user_id = {$user_id} and o.delete_time is null
";

    $sql .= " order by o.id desc";
//    echo $sql;die;
    $res = $db->fetch_all($sql);

    foreach($res as $key => $val){
        $_text = empty($val['attach_user']) ? [] : json_decode($val['attach_user']);
        $res[$key]['attach_user_text'] = '';
        foreach($_text as $k => $v){
            $res[$key]['attach_user_text'] .= $k . "：" . $v . "；";
        }
        $res[$key]['amount'] = number_format($val['amount'] / 100, 2);
        $res[$key]['goods_url'] = Url::goods($val['goods_id']);
        $res[$key]['url'] = Url::goods($val['goods_id']);
//        $res[$key]['status_text'] =
        $res[$key]['pay_time_text'] = empty($val['pay_time']) ? '未付款' : date('Y-m-d H:i:s', $val['pay_time']);
        $res[$key]['status_text'] = orderStatusText($val['status']);
    }

    if($resp == 'api'){
        Ret::success('success', $res);
    }else{
        return ['code' => 200, 'data' => $res];
    }
}

/**
 * 获取游客订单列表
 */
function api_get_visitors_order($search = []){
    global $db, $db_prefix, $resp;
    if(empty($search)){
        $out_trade_no = Input::postStrVar('out_trade_no');
        $required = Input::postStrArray('required');
        $attach = Input::postStrVar('attach');
    }else{
        $out_trade_no = $search['out_trade_no'];
        $required = $search['required'];
        $attach = $search['attach'];
    }

    if(empty($out_trade_no)){
        if($resp == 'api'){
            Ret::error('请输入查询内容');
        }else{
            return ['code' => 400, 'msg' => '请输入查询内容'];
        }
    }

    $where = "where o.delete_time is null and (";
    if(!empty($out_trade_no)){
        $where .= " (o.out_trade_no = '{$out_trade_no}' or o.up_no = '{$out_trade_no}') or";
        $where .= " ol.attach_user like '%:\"{$out_trade_no}\"%' or";
        $where .= " orq.content = '{$out_trade_no}' or";
    }
    $where = trim($where, "or");
    $where .= ")";

    $sql = "SELECT DISTINCT o.id, ol.goods_id, g.type, 
o.out_trade_no, o.up_no, g.title, o.create_time, o.pay_time, o.status, o.amount, ol.quantity, ol.attr_spec, 
ol.attach_user, ol.unit_price, ol.cost_price, o.payment, g.cover 
FROM {$db_prefix}order o 
INNER JOIN {$db_prefix}order_list ol ON o.id = ol.order_id 
LEFT JOIN {$db_prefix}goods g on ol.goods_id = g.id ";
        $sql .= " left JOIN {$db_prefix}order_required orq ON o.id = orq.order_id {$where}";

    $sql .= " order by o.id desc ";
//    echo $sql;die;
    $res = $db->fetch_all($sql);

//    var_dump($orq_num);die;
//    d($res);die;

    foreach($res as $key => $val){
        $_text = empty($val['attach_user']) ? [] : json_decode($val['attach_user']);
        $res[$key]['attach_user_text'] = '';
        foreach($_text as $k => $v){
            $res[$key]['attach_user_text'] .= $k . "：" . $v . "；";
        }
        $res[$key]['amount'] = number_format($val['amount'] / 100, 2);
        $res[$key]['goods_url'] = Url::goods($val['goods_id']);
        $res[$key]['url'] = Url::goods($val['goods_id']);
//        $res[$key]['status_text'] =
        $res[$key]['pay_time_text'] = empty($val['pay_time']) ? '未付款' : date('Y-m-d H:i:s', $val['pay_time']);
        $res[$key]['status_text'] = orderStatusText($val['status']);
    }

    if($resp == 'api'){
        Ret::success('查询完成', $res);
    }else{
//        d($res);die;
        return ['code' => 200, 'data' => $res];
    }
}

/**
 * 游客查询订单结果数量
 */
function api_visitors_search_order_count(){
    global $db, $db_prefix, $resp;
    $out_trade_no = Input::postStrVar('out_trade_no');
    $required = Input::postStrArray('required');
    $attach = Input::postStrVar('attach');

    $_search = [
        'out_trade_no' => $out_trade_no,
        'required' => $required,
        'attach' => $attach
    ];

    $where = "where o.delete_time is null and (";
    if(!empty($out_trade_no)){
        $where .= " (o.out_trade_no = '{$out_trade_no}' or o.up_no = '{$out_trade_no}') or";
        $where .= " ol.attach_user like '%:\"{$out_trade_no}\"%' or";
        $where .= " orq.content = '{$out_trade_no}' or";
    }
    $where = trim($where, "or");
    $where .= ")";
    if(empty($out_trade_no)){
        if($resp == 'api'){
            Ret::error('请输入查询内容');
        }else{
            return ['code' => 400, 'msg' => '请输入查询内容'];
        }
    }

//echo $where;die;
    $sql = "SELECT count(DISTINCT o.id) order_count
FROM {$db_prefix}order o
INNER JOIN {$db_prefix}order_list ol ON o.id = ol.order_id";
        $sql .= " left JOIN {$db_prefix}order_required orq ON o.id = orq.order_id ";
    $sql .= "{$where}";

    $res = $db->once_fetch_array($sql);
    $order_count = empty($res) ? 0 : $res['order_count'];
    if($resp == 'api'){
        Ret::success('查询完成', [
            'order_count' => $order_count,
            '_search' => $_search
        ]);
    }else{
        return ['code' => 200, 'data' => [
            'order_count' => $order_count,
            '_search' => $_search
        ]];
    }

}


