<?php
/**
 * Service: Api
 */

class Api {

    private static $resp = '';
    private static $post = [];

    private static $db = null;
    private static $db_prefix = null;

    private static $user_id = 0;
    private static $user = [];

    private static $timestamp = null;

    public static function init(){
        self::$db = Database::getInstance();
        self::$db_prefix = DB_PREFIX;
        self::$timestamp = time();
    }

    public static function api_init(){
        self::init();
        self::$resp = 'api';
    }

    public static function local_init(){
        self::init();
        self::$resp = 'local';
        self::$user_id = UID;
        $db_prefix = self::$db_prefix;
        if(self::$user_id > 0){
            $sql = "select * from {$db_prefix}user where uid=" . UID . " limit 1";
            self::$user = self::$db->once_fetch_array($sql);
        }

    }

    /**
     * 商品下单
     */
    public static function xiadan($post){
        $goods_id = $post['goods_id'];
        $sku_ids = empty($post['sku_ids']) ? '0' : $post['sku_ids'];
        $quantity = $post['quantity'];
        $payment_plugin = $post['payment_plugin'];
        $payment_title = $post['payment_title'];

        $attach = $post['attach'];
        $required = $post['required'];

        foreach($attach as $key => $val){
            if(empty($val)) Ret::error('请填写' . $key);
        }
        foreach($required as $key => $val){
            if(empty($val)) Ret::error('请填写' . $key);
        }



        if(empty($payment_plugin)){
            Ret::error('请选择支付方式');
        }
        if(self::$resp == 'local' && $payment_plugin == 'balance' && !ISLOGIN){
            Ret::error('未登录用户无法使用余额支付');
        }

        $stock = self::getStock([
            'goods_id' => $goods_id,
            'sku_ids' => $sku_ids
        ]);
        if($stock == -999){
            if(empty($sku_ids)){
                Ret::error('请选择商品规格');
            }else{
                Ret::error('请完整选择商品规格');
            }
        }
        if($quantity > $stock){
            if($stock == 0){
                Ret::error('该商品已售罄');
            }else{
                Ret::error('该商品库存不足，剩余库存：' . $stock);
            }

        }
        $amount = self::getGoodsPrice([
            'skus' => $sku_ids,
            'goods_id' => $goods_id,
            'quantity' => $quantity
        ]);
//        d($amount);die;
        // 验证通过后，开始写入订单

//        var_dump($sku_ids);die;
        if(empty($sku_ids)){
            $attr_spec = '';
        }else{
            $orderModel = new Order_Model();
            $specification_value_data = $orderModel->getSpecificationValue($sku_ids);
            $specification_value = array_column($specification_value_data, 'name');

            $specification_ids = array_column($specification_value_data, 'attr_id');
            $specification_data = $orderModel->getSpecification($specification_ids);
            $specification = array_column($specification_data, 'title');
            $attr_spec = '';
            foreach($specification as $k => $v){
                $attr_spec .= $v . '：' . $specification_value[$k] . '；';
            }
        }


        try {
            self::$db->beginTransaction();

            $insert_order = [
                'client_ip' => getClientIP(),
                'user_id' => self::$user_id,
                'out_trade_no' => date('YmdHis', self::$timestamp) . mt_rand(1000, 9999),
                'amount' => $amount['count_price'] * 100,
                'payment' => $payment_title,
                'pay_name' => $payment_title,
                'pay_plugin' => $payment_plugin,
                'expire_time' => self::$timestamp + 600,
                'create_time' => self::$timestamp
            ];
            self::$db->add('order', $insert_order);
            $order_id = self::$db->insert_id();

//            var_dump($attr_spec);die;

            $insert_child_order = [
                'order_id' => $order_id,
                'goods_id' => $goods_id,
                'sku' => empty($sku_ids) ? '' : $sku_ids,
                'attr_spec' => $attr_spec,
                'attach_user' => json_encode($attach, JSON_UNESCAPED_UNICODE),
                'quantity' => $quantity,
                'unit_price' => $amount['unit_price'] * 100,
                'price' => $amount['count_price'] * 100,
                'cost_price' => $amount['cost_price'] * 100
            ];
            self::$db->add('order_list', $insert_child_order);

            foreach($required as $key => $val){
                $insert_required = [
                    'order_id' => $order_id,
                    'name' => $key,
                    'content' => $val,
                    'type' => 'string'
                ];
                self::$db->add('order_required', $insert_required);
            }

            self::$db->commit();
        } catch (Exception $e) {
            self::$db->rollback();
            Ret::error($e->getMessage());
        }
        return self::success([
            'msg' => 'ok',
            'data' => [
                'out_trade_no' => $insert_order['out_trade_no']
            ],
            'code' => 200
        ]);
    }


    /**
     * 获取价格与库存
     */
    public static function getPriceStock($post){
        $sku = $post['skus'];
        $goods_id = $post['goods_id'];
        $quantity = $post['quantity'];
        $db_prefix = self::$db_prefix;
        $sql = "select * from {$db_prefix}skus where goods_id={$goods_id}";
        $sku = explode('-', $sku);
        foreach($sku as $val){
            $sql .= " and find_in_set('{$val}', REPLACE(sku, '-', ',')) > 0 ";
        }
        $sql .= " order by user_price asc";
        $skus = self::$db->fetch_all($sql);
        $select_sku = empty($skus) ? false : true;

        $goods = self::$db->once_fetch_array("select * from {$db_prefix}goods where id={$goods_id}");

        if($goods['is_sku'] == 'n'){
            $skus = self::$db->fetch_all("select * from {$db_prefix}skus where goods_id={$goods_id} and sku='0'");
        }

        $min_price = 0;
        $max_price = 0;
        $stock = 0;
        if(self::$user_id > 0){
            foreach($skus as $key => $val){
                $unit_price = $val['user_price'];
                $stock += $val['stock'];
                if(self::$user['level'] > 0){
                    $sql = "select * from {$db_prefix}member_price where goods_id={$goods_id} and sku='{$val['sku']}' order by member_level asc";
                    $_member = self::$db->fetch_all($sql);
                    foreach($_member as $v){
                        if($v['member_level'] > self::$user['level']){
                            break;
                        }
                        $unit_price = $v['price'];
                    }
                }
                if($key == 0){
                    $min_price = $unit_price;
                }
                $max_price = $unit_price;
            }

        }else{
            foreach($skus as $key => $val){
                $stock += $val['stock'];
                $unit_price = $val['guest_price'];
                if($key == 0){
                    $min_price = $unit_price;
                }
                $max_price = $unit_price;
            }
        }
        $is_full = count($skus) == 1 ? 'y' : 'n'; // 规格是否选择完整
        $is_select_sku = empty($skus) ? 'n' : 'y'; // 是否选择规格

        $sql = "select * from {$db_prefix}discount where goods_id={$goods_id} order by quantity desc";
        $discount = self::$db->fetch_all($sql);

        $dis = 0; // 优惠价格
        foreach($discount as $val){
            if($quantity >= $val['quantity']){
                $min_price = $min_price - $val['amount'];
                $max_price = $max_price - $val['amount'];
                $dis = $val['amount'];
                break;
            }
        }

//        d($skus);die;

        $sql = "select * from {$db_prefix}skus where goods_id={$goods_id}";
        $skus = self::$db->fetch_all($sql);


        return [
            'min_price' => $min_price * $quantity / 100,
            'max_price' => $max_price * $quantity / 100,
            'is_full' => $is_full,
            'is_select_sku' => $is_select_sku,
            'price' => $min_price * $quantity / 100,
            'discount' => $dis * $quantity  / 100,
            'stock' => empty($select_sku) ? $goods['stock'] : $stock,
            'skus' => $skus
        ];
    }

    /**
     * 获取商品价格
     */
    public static function getGoodsPrice($post){
        $sku = $post['skus'];
        $goods_id = $post['goods_id'];
        $quantity = $post['quantity'];
        $db_prefix = self::$db_prefix;
        $sql = "select * from {$db_prefix}skus where goods_id={$goods_id} and sku='{$sku}' limit 1";
        $skus = self::$db->once_fetch_array($sql);

        if(self::$user_id > 0){
            $unit_price = $skus['user_price'] / 100;
            if(self::$user['level'] > 0){
                $sql = "select * from {$db_prefix}member_price where goods_id={$goods_id} and sku='{$sku}' order by member_level asc";
                $_member = self::$db->fetch_all($sql);
                foreach($_member as $val){
                    if($val['member_level'] > self::$user['level']){
                        break;
                    }
                    $unit_price = $val['price'] / 100;
                }
            }
        }else{
            $unit_price = $skus['guest_price'] / 100;
        }


        $data = [
            'count_price' => $unit_price * $quantity,
            'unit_price' => $unit_price,
            'cost_price' => $skus['cost_price'] / 100
        ];

        return self::success($data);

    }

    /**
     * 获取商品库存
     */
    public static function getStock($post){
        $db_prefix = self::$db_prefix;
        $goods_id = $post['goods_id'];
        $sku = $post['sku_ids'];
        $sql = "select * from {$db_prefix}skus where goods_id={$goods_id} and sku='{$sku}' limit 1";
        $skus = self::$db->once_fetch_array($sql);
        if(empty($skus)){
            return self::success(-999);
        }else{
            return self::success($skus['stock']);
        }
    }

    /**
     * 获取商品批量优惠信息
     */
    public static function getGoodsDiscount($post){
        $db_prefix = self::$db_prefix;
        $goods_id = $post['goods_id'];
        $sql = "select * from {$db_prefix}discount where goods_id={$goods_id} order by quantity asc";
        $list = self::$db->fetch_all($sql);
        foreach($list as &$val){
            $val['amount'] /= 100;
        }
        return self::success($list);


    }

    /**
     * 获取商品分类
     */
    public static function getSortAll() {

        $db_prefix = self::$db_prefix;

        $sql = "select s.sid, s.sortname, COUNT(g.id) AS goods_count, s.sortimg
from {$db_prefix}sort s
LEFT JOIN 
    {$db_prefix}goods g ON s.sid = g.sort_id and g.delete_time is null and g.is_on_shelf = 1 
where s.type='goods' GROUP BY  s.sid order by s.taxis desc, sid asc";




        $list = self::$db->fetch_all($sql);



        foreach($list as &$val){
            $val['sort_url'] = Url::sort($val['sid']);
        }

//        d($list);die;

        return self::success($list);
    }

    /**
     * 获取商品信息
     * @post.goods_id 商品ID
     */
    public static function getGoodsInfo($post){
        $db_prefix = DB_PREFIX;
        $db = Database::getInstance();

        $goods_id = $post['goods_id'];

        $sql = "select * from {$db_prefix}goods where id={$goods_id} limit 1";
        $goods = $db->once_fetch_array($sql);

        if($goods['is_on_shelf'] == 0){
            self::error('该商品已下架！');
        }

        $sql = "select * from {$db_prefix}skus where goods_id={$goods_id}";
        $skus = $db->fetch_all($sql);
        $sql ="select * from {$db_prefix}member_price where goods_id={$goods_id}";
        $member_price = $db->fetch_all($sql);


        $goods['attach_user'] = json_decode($goods['attach_user'], true);

        if($goods['is_sku'] == 'y'){
            $sku_value_ids = [];
            $sku_attr_ids = [];
            $goods['have_stock_skus'] = [];
            $goods['sku_all'] = [];
            foreach($skus as $key => $val){

                $ids = explode('-', $val['sku']);
                $sku_value_ids = array_merge($sku_value_ids, $ids);

                $price = -1;

                if(LEVEL == -1){
                    $price= $val['guest_price'] / 100;
                }else{
                    foreach($member_price as $v){
                        if($v['member_level'] == LEVEL && $val['sku'] == $v['sku']){
                            $price = $v['price'] / 100;
                        }
                    }
                    $price = $price == -1 ? $val['user_price'] / 100 : $price;
                }
                $val['price'] = $price;

                $goods['sku_all'][$val['sku']] = $val;
                $goods['sku_all'][$val['sku']]['stock'] = $val['stock'];
                if($val['stock'] > 0){
                    $goods['have_stock_skus'][$val['sku']] = $val;
                }

                if(!isset($goods['price']) && $price != -1){
                    $goods['price'] = $price;
                }
                if(!isset($goods['market_price'])){
                    $goods['market_price'] = $val['market_price'] / 100;
                }
            }


            $sku_value_ids = array_unique($sku_value_ids);
            $sql = "SELECT * FROM {$db_prefix}sku_value WHERE id IN (" . implode(',', $sku_value_ids) . ")";
            $sku_values = $db->fetch_all($sql);
            foreach($sku_values as $val){
                $sku_attr_ids[] = $val['attr_id'];
            }
            $sku_attr_ids = array_unique($sku_attr_ids);
            $sql = "SELECT * FROM {$db_prefix}sku_attr WHERE id IN (" . implode(',', $sku_attr_ids) . ")";
            $sku_attr = $db->fetch_all($sql);

            $goods['spec'] = [];
            $goods['spec_attr'] = [];
            foreach($sku_attr as $key => $val){
                $goods['spec'][$key] = [
                    'sku_attr_id' => $val['id'],
                    'title' => $val['title'],
                    'sku_values' => []
                ];


                foreach($sku_values as $v){
                    if($val['id'] == $v['attr_id']){
                        $goods['spec'][$key]['sku_values'][] = [
                            'id' => $v['id'],
                            'name' => $v['name']
                        ];
                        $goods['spec_attr'][$key][] = $v['id'];
                    }

                }
            }

        }else{
            foreach($skus as $val){
                $price = -1;
                if(LEVEL == -1){
                    $price= $val['guest_price'] / 100;
                }else{
                    foreach($member_price as $v){
                        if($v['member_level'] == LEVEL && $val['sku'] == $v['sku']){
                            $price = $v['price'] / 100;
                        }
                    }
                    $price = $price == -1 ? $val['user_price'] / 100 : $price;
                }

                if(!isset($goods['price']) && $price != -1){
                    $goods['price'] = $price;
                }
                if(!isset($goods['market_price'])){
                    $goods['market_price'] = $val['market_price'] / 100;
                }

            }
            $goods['spec'] = [];

            $goods['spec_attr_json'] = json_encode([]);

            $goods['have_stock_skus'][] = array_merge($val, ['price' => $price, 'stock' => $goods['stock']]);

            $goods['have_stock_skus_json'] = json_encode($goods['have_stock_skus']);
            $goods['skus_all_json'] = json_encode([]);
        }


        return self::success($goods);
    }

    /**
     * 获取商品列表
     * @post.sort_id 分类id，为空时获取全部商品
     * @post.keyword 商品搜索
     */
    public static function getGoodsList($post) {
        $db = Database::getInstance();
        $db_prefix = DB_PREFIX;
        $sort_id = $post['sort_id'];
        $keyword = $post['keyword'];
        $where = "";
        if(!empty($keyword)){
            $where .= " and g.title like '%{$keyword}%'";
        }


        if(!empty($sort_id) && $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.market_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";

        $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($goods);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'] = $goods[$key]['price'] / 100;
            $goods[$key]['market_price'] = $goods[$key]['market_price'] / 100;
        }

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


        return self::success($goods);
    }

    /**
     * 返回数据
     */
    private static function success($data){
        if(self::$resp == 'api'){
            Ret::success('success', $data);
        }else{
            return $data;
        }
    }
    private static function error($msg){
        if(self::$resp == 'api'){
            Ret::error($msg);
        }else{
            emMsg($msg);
        }
    }
}