<?php

require_once 'globals.php';

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

/*try {
    $db->beginTransaction();

    $db->commit();
    echo "事务执行成功";
} catch (Exception $e) {
    $db->rollback();
    emMsg("出错啦：" . $e->getMessage());
}*/
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), // 上架
    'post_url' => Input::postStrVar('post_url'), // 自定义请求url
    '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'), // 简介
];



$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_url'] = empty($params['post_url']) ? '' : $params['post_url'];
$params['post_params'] = empty($params['post_params']) ? '' : $params['post_params'];


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['type'] == 'post'){
    if(empty($params['post_url'])){
        output::error('请输入要访问的URL');
    }
}
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();


// 1，保存商品主表
if ($params['goods_id'] > 0) {
    $update = [
        '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'],
    ];
//    d($update);die;
    $goodsModel->updateProduct($update, $params['goods_id']);
    $goods_id = $params['goods_id'];
} else {
    $insert = [
        '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'],
        'create_time' => time(),
        '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'],
    ];
//    d($insert);die;
    $goods_id = $goodsModel->addProduct($insert);
}

$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'){
    // 删除规格数据和会员价格
    $goodsModel->deleteProductSku($goods_id);
    foreach($params['skus'] as $key => $val){
        $insert = [
            'goods_id' => $goods_id,
            'sku' => $key,
            '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_url' => $params['post_url'],
            'post_params' => $params['post_params'],
        ];
        // 写入商品规格
        $skus_id = $goodsModel->insertProductSkus($goods_id, $insert);
        // 写入会员价格
        foreach($val as $k => $v){
            $temp = explode('_', $k);
            if($temp[0] == 'member'){
                $insert = [
                    'sku' => $key,
                    'goods_id' => $goods_id,
                    'member_level' => $temp[1],
                    'price' => $v * 100
                ];
                $goodsModel->insertMemberPrice($insert);
            }
        }
    }
}else{
//    1，在单规格中，如果我修改商品，那么就要删除skus。但是，新添加的skus还是用原来的uuid
//    2，在修改规格后，我需要对比新老skus。如果是同样的skus规格，则依旧用原来的uuid。如否，则重新生成，无法匹配的库存则转移到无效库存，（最为完善，需仔细思考）
//    3，最为简单应规格类型修改的方法，如存在库存时，则禁止修改规格，每次修改商品做新旧规格对比。（虚拟产品用此方法，应该没问题）
//    4，如果我只考虑库存表goods_id和sku关联呢。（这个应该最可行，仔细考虑这个）


    // 下面代码仍需修改，需考虑多规格转向单规格的修改
    $old_skus_id = $goodsModel->deleteProductSku($goods_id);
    $insert = [
        'goods_id' => $goods_id,
        'sku' => '0',
        '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_url' => $params['post_url'],
        'post_params' => $params['post_params'],
    ];
    $skus_id = $goodsModel->insertProductSkus($goods_id, $insert);

    // 保存会员价格
    $goodsModel->delMemberPrice($goods_id);
    foreach($params['skus']['member'] as $key => $val){
        $insert = [
            'goods_id' => $goods_id,
            'sku' => '0',
            'member_level' => $key,
            'price' => $val * 100
        ];
        $goodsModel->insertMemberPrice($insert);
    }

}

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