<?php

require_once 'globals.php';

if (empty($_POST)) {
    exit;
}


LoginAuth::checkToken();
$db = Database::getInstance();
$db_prefix = DB_PREFIX;
$params = [
    'goods_id' => Input::postIntVar('goods_id', 0), // 商品id
    'sort_id' => Input::postStrVar('sort_id', -1), // 商品分类
    'title' => Input::postStrVar('title'), // 商品标题
    'type' => Input::postStrVar('type'), // 商品类型
    'is_sku' => Input::postStrVar('is_sku'), // 是否多规格
    'attr_id' => Input::postIntVar('attr_id', 0), // 商品规格id
    'skus' => Input::postStrArray('skus', []), // 商品规格信息
    'attach_user' => Input::postStrVar('attach_user', null), // 附加选项
    'content' => Input::postStrVar('content'), // 商品内容
    'pay_content' => Input::postStrVar('pay_content'), // 商品内容
    'cover' => Input::postStrVar('cover'), // 商品封面图
    'is_on_shelf' => Input::postIntVar('is_on_shelf', 0), // 上架
    'sales' => Input::postIntVar('sales'), // 销量
    'index_top' => Input::postIntVar('index_top', 0), // 首页置顶
    'sort_top' => Input::postIntVar('sort_top', 0), // 分类置顶
    'sort_num' => Input::postIntVar('sort_num'), // 排序
    'des' => Input::postStrVar('des'), // 简介
];




$cmd = empty($params['goods_id']) ? 'add' : 'edit';


$discount = Input::postStrArray('discount');
//d($discount);die;

$goods_id = $params['goods_id'];
$params['attach_user'] = empty($params['attach_user']) ? null : $params['attach_user'];
$params['post_params'] = empty($params['post_params']) ? '' : $params['post_params'];

if(empty($params['type'])){
    output::error('请选择商品类型');
}

if(empty($params['title'])){
    output::error('请输入商品名称');
}

//d($params['skus']);die;
if($params['is_sku'] == 'n'){
    foreach($params['skus'] as $key => $val){
        if(isEmpty($val)){
            output::error('请将商品价格信息设置完整');
        }
    }
}
if(!empty($params['skus']['member'])){
    foreach($params['skus']['member'] as $key => $val){
        if(isEmpty($val)){
            output::error('请将商品价格信息设置完整');
        }
    }
}

if($params['is_sku'] == 'y'){
    if(empty($params['attr_id'])){
        output::error('请设置规格信息');
    }
    if(empty($params['skus'])){
        output::error('请设置规格信息');
    }
    foreach($params['skus'] as $key => $val){
        foreach($val as $k => $v){
            if(isEmpty($v)){
                output::error('请将商品价格信息设置完整');
            }
        }

    }
}

$goodsModel = new Goods_Model();

$data = [
    'title' => $params['title'],
    'sort_id' => $params['sort_id'],
    'type' => $params['type'],
    'is_sku' => $params['is_sku'],
    'attr_id' => $params['attr_id'],
    'attach_user' => $params['attach_user'],
    'content' => $params['content'],
    'pay_content' => $params['pay_content'],
    'cover' => $params['cover'],
    'is_on_shelf' => $params['is_on_shelf'],
    'sales' => $params['sales'],
    'index_top' => $params['index_top'],
    'sort_top' => $params['sort_top'],
    'sort_num' => $params['sort_num'],
    'des' => $params['des']
];
if($cmd == 'add'){
    $old_skus = [];
}else{
    $old_skus = $db->fetch_all("select * from {$db_prefix}skus where goods_id={$goods_id}");
}

//d($old_skus);die;

try {
    $db->beginTransaction();

    // 1，保存商品主表
    if ($params['goods_id'] > 0) {
        $goodsModel->updateProduct($data, $params['goods_id']);
        $goods_id = $params['goods_id'];
    } else {
        $data['create_time'] = time();
        $goods_id = $goodsModel->addProduct($data);
    }

    $sql = "DELETE FROM `{$db_prefix}discount` WHERE `goods_id` = {$goods_id}";
    $db->query($sql);
    foreach($discount['number'] as $key => $val){
        if(!empty($val) && !empty($discount['amount'][$key])){
            $amount = $discount['amount'][$key] * 100;
            $sql = "INSERT INTO `{$db_prefix}discount` (`goods_id`, `quantity`, `amount`) VALUES ({$goods_id}, {$val}, {$amount})";
            $db->query($sql);
        }
    }

    // 2，保存规格主表
    if($params['is_sku'] == 'y'){
        // 删除会员价格
        $db->query("DELETE FROM {$db_prefix}member_price where goods_id={$goods_id}");
        // 删除商品规格
        $db->query("delete from {$db_prefix}skus where goods_id={$goods_id}");
        $goods_stock = 0;
        foreach($params['skus'] as $key => $val){
            // 写入会员价格
            foreach($val as $k => $v){
                $temp = explode('_', $k);
                $price = $v * 100;
                if($temp[0] == 'member'){
                    $db->query("INSERT INTO {$db_prefix}member_price (goods_id, sku, member_level, price) VALUES ({$goods_id}, '{$key}', {$temp[1]}, {$price})");
                }
            }
            // 写入商品规格
            $old_stock = 0;
            $old_sales = 0;
            foreach($old_skus as $os){
                if($key == $os['sku']){
                    $old_stock = $os['stock'];
                    $old_sales = $os['sales'];
                }
            }
            $goods_stock+= $old_stock;
            $guest_price = empty($val['guest_price']) || $val['guest_price'] < 0 ? 0 : $val['guest_price'] * 100;
            $user_price = empty($val['user_price']) || $val['user_price'] < 0 ? 0 : $val['user_price'] * 100;
            $market_price = empty($val['market_price']) ? 0 : $val['market_price'] * 100;
            $cost_price = empty($val['cost_price']) ? 0 : $val['cost_price'] * 100;
            $post_params = $params['post_params'];
            $db->query("INSERT INTO " . DB_PREFIX . "skus 
            (goods_id, sku, guest_price, user_price, market_price, cost_price, stock, sales) 
            VALUES 
            ({$goods_id}, '{$key}', {$guest_price}, {$user_price}, {$market_price}, {$cost_price}, {$old_stock}, {$old_sales})");
        }
    }
    if($params['is_sku'] == 'n'){
        // 删除会员价格
        $db->query("DELETE FROM {$db_prefix}member_price where goods_id={$goods_id}");
        // 删除商品规格
        $db->query("delete from {$db_prefix}skus where goods_id={$goods_id}");
        $goods_stock = 0;
        // 写入会员价格
        if(!empty($params['skus']['member'])){
            foreach($params['skus']['member'] as $key => $val){
                $price = $val * 100;
                $db->query("INSERT INTO {$db_prefix}member_price (goods_id, sku, member_level, price) VALUES ({$goods_id}, '0', {$key}, {$price})");
            }
        }
//        d($old_skus);die;
        // 写入商品规格
        $old_stock = 0;
        $old_sales = 0;
        foreach($old_skus as $os){
            if('0' == $os['sku']){
                $old_stock = $os['stock'];
                $old_sales = $os['sales'];
            }
        }
        $goods_stock+= $old_stock;
        $guest_price = $params['skus']['guest_price'] * 100;
        $user_price = $params['skus']['user_price'] * 100;
        $market_price = $params['skus']['market_price'] * 100;
        $cost_price = empty($params['skus']['cost_price']) ? 0 : $params['skus']['cost_price'] * 100;
        $post_params = $params['post_params'];
        $db->query("INSERT INTO " . DB_PREFIX . "skus 
            (goods_id, sku, guest_price, user_price, market_price, cost_price, stock, sales) 
            VALUES 
            ({$goods_id}, '0', {$guest_price}, {$user_price}, {$market_price}, {$cost_price}, {$old_stock}, {$old_sales})");
    }
//    var_dump($goods_stock);die;
    // 3. 更新商品库存
    $db->query("update {$db_prefix}goods set stock = {$goods_stock} where id = {$goods_id}");


    doAction('save_goods_after');



    $db->commit();
} catch (Exception $e) {
    $db->rollback();
    output::error($e->getMessage());
}

if(empty($params['goods_id'])){
    die(json_encode(['msg' => '商品已添加', 'type' => 'add']));
}else{
    die(json_encode(['msg' => '', 'type' => 'edit']));
}
