<?php

$resp = 'local';

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


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

/**
 * 获取卡密
 */
function api_get_order_serect($post = []){
    global $db, $db_prefix, $resp;
    if(empty($search)){
        $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);


//    d($res);die;


    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}
";

    $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'];
    }
    $where = "where";
    if(!empty($out_trade_no)){
        $where .= " (o.out_trade_no = '{$out_trade_no}' or o.up_no = '{$out_trade_no}') and";
    }
    $req_where = "";
    $orq_num = 0;
    if(!empty($required)){
        foreach($required as $key => $val){
            if(!empty($val)){
                $orq_num++;
                if(empty($req_where)){
                    $req_where .= " and ((orq.name = '{$key}' and orq.content = '{$val}') or";
                }else{
                    $req_where .= " (orq.name = '{$key}' and orq.content = '{$val}') or";
                }
            }
        }
        $req_where = trim($req_where, 'or');
        if($orq_num > 0){
            $req_where .= ")";
        }
    }
    if(!empty($attach)){
        $where .= " ol.attach_user like '%:\"{$attach}\"%' and";
    }
    $where = trim($where, "and");
    if($where == 'where' && empty($req_where)){
        if($resp == 'api'){
            Ret::error('您必须输入一个查询条件');
        }else{
            return ['code' => 400, 'msg' => '您必须输入一个查询条件'];
        }

    }
    $where = $where == 'where' ? '' : $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 ";
    if($orq_num > 0){
        $sql .= " INNER JOIN {$db_prefix}order_required orq ON o.id = orq.order_id ";
    }
    $sql .= "
{$where} {$req_where}";
    if($orq_num > 0){
        $sql .= " GROUP BY o.id HAVING COUNT(DISTINCT orq.name) = {$orq_num}";
    }
    $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";
    if(!empty($out_trade_no)){
        $where .= " (o.out_trade_no = '{$out_trade_no}' or o.up_no = '{$out_trade_no}') and";
    }
    $req_where = "";
    $orq_num = 0;
    if(!empty($required)){
        foreach($required as $key => $val){
            if(!empty($val)){
                $orq_num++;
                if(empty($req_where)){
                    $req_where .= " and ((orq.name = '{$key}' and orq.content = '{$val}') or";
                }else{
                    $req_where .= " (orq.name = '{$key}' and orq.content = '{$val}') or";
                }
            }
        }
        $req_where = trim($req_where, 'or');
        if($orq_num > 0){
            $req_where .= ")";
        }
    }
    if(!empty($attach)){
        $where .= " ol.attach_user like '%:\"{$attach}\"%' and";
    }
    $where = trim($where, "and");
    if($where == 'where' && empty($req_where)){
        if($resp == 'api'){
            Ret::error('您必须输入一个查询条件');
        }else{
            return ['code' => 400, 'msg' => '您必须输入一个查询条件'];
        }

    }
    $where = $where == 'where' ? '' : $where;
    $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";
    if($orq_num > 0){
        $sql .= " INNER JOIN {$db_prefix}order_required orq ON o.id = orq.order_id ";
    }
    $sql .= "
{$where} {$req_where}";
    if($orq_num > 0){
        $sql .= " HAVING COUNT(DISTINCT orq.name) = {$orq_num}";
    }
    $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
        ]];
    }

}


