<?php

/**
 * ECSHOP 虚拟卡商品管理程序
 * ============================================================================
 * 版权所有 (C) 2005-2006 北京亿商互动科技发展有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com
 * ----------------------------------------------------------------------------
 * 这是一个免费开源的软件；这意味着您可以在不用于商业目的的前提下对程序代码
 * 进行修改、使用和再发布。
 * ============================================================================
 * @author:     wj <wjzhangq@126.com>
 * @version:    v2.1
 * ---------------------------------------------
 * $Author: wj $
 * $Date: 2007-05-08 15:42:37 +0800 (星期二, 08 五月 2007) $
 * $Id: virtual_card.php 8508 2007-05-08 07:42:37Z wj $
 */

if (isset($set_modules) && $set_modules == true)
{
    $i = (isset($modules)) ? count($modules) : 0;
    $file = basename(__FILE__);

    $modules['02_cat_and_goods']['50_virtual_card_list']   = $file . '?act=list';   // 商品列表
    $modules['02_cat_and_goods']['51_virtual_card_add']    = $file . '?act=add';    // 添加商品
    $modules['02_cat_and_goods']['52_virtual_card_change'] = $file . '?act=change'; // 修改加密串

    return;
}

define('IN_ECS', true);

/* 包含文件 */
require_once('includes/init.php');
require_once('includes/lib_goods.php');
require_once('../includes/lib_code.php');
require_once('../includes/cls_image.php');
$image = new cls_image();

/* 包含语言文件 */
require_once('../plugins/virtual_card/languages/virtual_card_'.$_CFG['lang'].'.php');
require_once('../languages/'.$_CFG['lang'].'/admin/goods.php');
$smarty->assign('lang', $_LANG);

/* 插件模板路径 */
$template_dir = '../../plugins/virtual_card/templates/';

/*------------------------------------------------------ */
//-- 商品列表，商品回收站
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'list')
{
    $cat_id = empty($_REQUEST['cat_id']) ? 0 : intval($cat_id);

    /* 模板赋值 */
    $ur_here = $_LANG['virtual_card_list'];
    $action_link = array('href' => 'virtual_card.php?act=add', 'text' => $_LANG['virtual_card_add']);

    $smarty->assign('ur_here',     $ur_here);
    $smarty->assign('full_page',   1);
    $smarty->assign('action_link', $action_link);
    $smarty->assign('cat_list',    cat_list(0, $cat_id));
    $smarty->assign('intro_list',  get_intro_list());

    $goods_list = goods_list($_REQUEST['act'] == 'list' ? 0 : 1, 0);
    $smarty->assign('goods_list',   $goods_list['goods']);
    $smarty->assign('filter',       $goods_list['filter']);
    $smarty->assign('record_count', $goods_list['record_count']);
    $smarty->assign('page_count',   $goods_list['page_count']);
    $smarty->assign('full_page',    1);

    /* 排序标记 */
    $sort_flag = sort_flag($goods_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    assign_query_info();
    $smarty->display($template_dir.'virtual_card_list.htm');
}

/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    $is_delete = empty($_REQUEST['is_delete']) ? 0 : intval($_REQUEST['is_delete']);
    $goods_list = goods_list($is_delete, 0);

    $smarty->assign('goods_list',   $goods_list['goods']);
    $smarty->assign('filter',       $goods_list['filter']);
    $smarty->assign('record_count', $goods_list['record_count']);
    $smarty->assign('page_count',   $goods_list['page_count']);
    $smarty->assign('list_type',    $is_delete ? 'trash' : 'goods');
    $smarty->assign('use_storage',  empty($_CFG['use_storage']) ? 0 : 1);

    /* 排序标记 */
    $sort_flag = sort_flag($goods_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch($template_dir.'virtual_card_list.htm'), '', array('filter' => $goods_list['filter'], 'page_count' => $goods_list['page_count']));
}

/*------------------------------------------------------ */
//-- 添加新商品 编辑商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit' || $_REQUEST['act'] == 'copy')
{
    /* 检查权限 */
    admin_priv('goods_manage');

    /* 包含 html editor 类文件 */
    include_once('../includes/fckeditor/fckeditor.php');

    /* 添加还是编辑的标识 */
    $is_add = $_REQUEST['act'] == 'add';

    /* 取得商品信息 */
    if ($is_add)
    {
        /* 默认值 */
        $goods = array(
            'goods_id'      => 0,
            'goods_desc'    => '',
            'cat_id'        => 0,
            'is_on_sale'    => '1',
            'is_alone_sale' => '1',
            'can_handsel'   => '1',
            'other_cat'     => array(), // 扩展分类
            'goods_type'    => 0,       // 商品类型
            'shop_price'    => 0,
            'promote_price' => 0,
            'market_price'  => 0,
            'integral'      => 0,
            'goods_number'  => 0,
            'warn_number'   => 1,
            'promote_end'   => date('Y-m-d', strtotime('+1 month')),
        );

        /* 关联商品 */
        $link_goods_list = array();
        $sql = "DELETE FROM " . $ecs->table('link_goods') . " WHERE goods_id = 0 OR link_goods_id = 0";
        $db->query($sql);

        /* 关联文章 */
        $goods_article_list = array();
        $sql = "DELETE FROM " . $ecs->table('goods_article') . " WHERE goods_id = 0";
        $db->query($sql);
    }
    else
    {
        /* 如果是编辑商品，同步一下库存 */
        if ($_REQUEST['act'] == 'edit')
        {
            $sql = "SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('virtual_card')." WHERE goods_id = '$_REQUEST[goods_id]' AND is_saled = 0 ";
            $num = $GLOBALS['db']->GetOne($sql);
            $db->query('UPDATE ' . $GLOBALS['ecs']->table('goods'). " SET goods_number = '$num' WHERE goods_id = '$_REQUEST[goods_id]'");
        }

        /* 商品信息 */
        $sql = "SELECT * FROM " . $ecs->table('goods') . " WHERE goods_id = '$_REQUEST[goods_id]'";
        $goods = $db->getRow($sql);

        /* 如果不是促销，处理促销日期 */
        if ($goods['is_promote'] == '0')
        {
            unset($goods['promote_start']);
            unset($goods['promote_end']);
        }

        /* 如果是复制商品，处理 */
        if ($_REQUEST['act'] == 'copy')
        {
            // 商品信息
            $goods['goods_id'] = 0;
            $goods['goods_sn'] = '';
            $goods['goods_name'] = '';

            // 扩展分类不变

            // 关联商品
            $sql = "DELETE FROM " . $ecs->table('link_goods') . " WHERE goods_id = 0 OR link_goods_id = 0";
            $db->query($sql);

            $sql = "SELECT '0' AS goods_id, link_goods_id, is_double " .
                   "FROM " . $ecs->table('link_goods') .
                   " WHERE goods_id = '$_REQUEST[goods_id]' ";
            $res = $db->query($sql);
            while ($row = $db->fetchRow($res))
            {
                $db->autoExecute($ecs->table('link_goods'), $row, 'INSERT');
            }

            $sql = "SELECT goods_id, '0' AS link_goods_id, is_double " .
                    "FROM " . $ecs->table('link_goods') .
                    " WHERE link_goods_id = '$_REQUEST[goods_id]' ";
            $res = $db->query($sql);
            while ($row = $db->fetchRow($res))
            {
                $db->autoExecute($ecs->table('link_goods'), $row, 'INSERT');
            }

            // 关联文章
            $sql = "DELETE FROM " . $ecs->table('goods_article') . " WHERE goods_id = 0";
            $db->query($sql);

            $sql = "SELECT 0 AS goods_id, article_id " .
                    "FROM " . $ecs->table('goods_article') .
                    " WHERE goods_id = '$_REQUEST[goods_id]' ";
            $res = $db->query($sql);
            while ($row = $db->fetchRow($res))
            {
                $db->autoExecute($ecs->table('goods_article'), $row, 'INSERT');
            }

            // 图片不变

            // 商品属性
            $sql = "DELETE FROM " . $ecs->table('goods_attr') . " WHERE goods_id = 0";
            $db->query($sql);

            $sql = "SELECT 0 AS goods_id, attr_id, attr_value, attr_price " .
                   "FROM " . $ecs->table('goods_attr') .
                   " WHERE goods_id = '$_REQUEST[goods_id]' ";
            $res = $db->query($sql);
            while ($row = $db->fetchRow($res))
            {
                $db->autoExecute($ecs->table('goods_attr'), $row, 'INSERT');
            }
        }

        // 扩展分类
        $other_cat_list = array();
        $sql = "SELECT cat_id FROM " . $ecs->table('goods_cat') . " WHERE goods_id = '$_REQUEST[goods_id]'";
        $goods['other_cat'] = $db->getCol($sql);
        foreach ($goods['other_cat'] as $cat_id)
        {
            $other_cat_list[$cat_id] = cat_list(0, $cat_id);
        }
        $smarty->assign('other_cat_list', $other_cat_list);

        /* 关联商品 */
        $link_goods_list = get_linked_goods($goods['goods_id']);

        /* 关联文章 */
        $goods_article_list = get_goods_articles($goods['goods_id']);

    }

    /* 创建 html editor */
    create_html_editor('goods_desc', $goods['goods_desc']);

    /* 模板赋值 */
    $smarty->assign('ur_here', $is_add ? $_LANG['virtual_card_add'] : ($_REQUEST['act'] == 'edit' ? $_LANG['edit_goods'] : $_LANG['copy_goods']));
    $smarty->assign('action_link', array('href' => 'virtual_card.php?act=list', 'text' => $_LANG['virtual_card_list']));
    $smarty->assign('goods', $goods);
    $smarty->assign('cat_list', cat_list(0, $goods['cat_id']));
    $smarty->assign('user_rank_list', get_user_rank_list());
    $smarty->assign('cfg', $_CFG);
    $smarty->assign('form_act', $is_add ? 'insert' : ($_REQUEST['act'] == 'edit' ? 'update' : 'insert'));
    if (!$is_add)
    {
        $smarty->assign('member_price_list', get_member_price_list($_REQUEST['goods_id']));
    }
    $smarty->assign('link_goods_list', $link_goods_list);
    $smarty->assign('goods_article_list', $goods_article_list);
    $smarty->assign('goods_type_list', goods_type_list($goods['goods_type']));
    $smarty->assign('gd', gd_version());
    $smarty->assign('thumb_width', $_CFG['thumb_width']);
    $smarty->assign('thumb_height', $_CFG['thumb_height']);
    $smarty->assign('goods_attr_html', build_attr_html($goods['goods_type'], $goods['goods_id']));

    /* 显示商品信息页面 */
    assign_query_info();
    $smarty->display($template_dir.'virtual_card_info.htm');
}

/*------------------------------------------------------ */
//-- 插入商品 更新商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')
{
    /* 检查权限 */
    admin_priv('goods_manage');

    /* 检查货号是否重复 */
    if ($_POST['goods_sn'])
    {
        $sql = "SELECT COUNT(*) FROM " . $ecs->table('goods') .
               " WHERE goods_sn = '$_POST[goods_sn]' AND goods_id <> '$_POST[goods_id]'";
        if ($db->getOne($sql) > 0)
        {
            sys_msg($_LANG['goods_sn_exists']);
        }
    }

    /* 检查图片格式 */
    if ($_FILES['goods_img']['tmp_name'] != '' && $_FILES['goods_img']['tmp_name'] != 'none' && !$image->check_img_type($_FILES['goods_img']['type']))
    {
        sys_msg($_LANG['invalid_goods_img']);
    }

    /* 插入还是更新的标识 */
    $is_insert = $_REQUEST['act'] == 'insert';

    /* 处理商品图片 */
    $goods_img    = ''; // 初始化商品图片
    $goods_thumb  = ''; // 初始化商品缩略图
    $original_img = ''; // 初始化原始图片

    // 如果上传了商品图片，相应处理
    if (isset($_FILES['goods_img']) && $_FILES['goods_img']['tmp_name'] != '' && $_FILES['goods_img']['tmp_name'] != 'none')
    {
        /* 删除原来的图片文件 */
        if (!empty($_REQUEST['goods_id']))
        {
            $sql = "SELECT goods_thumb, goods_img, original_img " .
                    " FROM " . $ecs->table('goods') .
                    " WHERE goods_id = '$_REQUEST[goods_id]'";
            $row = $db->getRow($sql);
            if ($row)
            {
                if ($row['goods_thumb'] != '' && is_file('../' . $row['goods_thumb']))
                {
                    unlink('../' . $row['goods_thumb']);
                }
                if ($row['goods_img'] != '' && is_file('../' . $row['goods_img']))
                {
                    unlink('../' . $row['goods_img']);
                }
                if ($row['original_img'] != '' && is_file('../' . $row['original_img']))
                {
                    unlink('../' . $row['original_img']);
                }
            }
        }

        $original_img = $image->upload_image($_FILES['goods_img']); // 原始图片
        $goods_img    = $original_img; // 商品图片
        $img          = $original_img; // 相册图片

        // 如果系统支持GD，缩放商品图片，且给商品图片和相册图片加水印

        // 如果系统支持GD，缩放商品图片，且给商品图片和相册图片加水印
        if ($image->gd_version() > 0 && $image->check_img_function($_FILES['goods_img']['type']))
        {
            // 如果设置大小不为0，缩放图片
            if ($_CFG['image_width'] * $_CFG['image_height'] > 0)
            {
                $goods_img = $image->make_thumb('../'. $goods_img , $GLOBALS['_CFG']['image_width'], $GLOBALS['_CFG']['image_height']);
            }

            // 加水印
            if (intval($_CFG['watermark_place']) > 0)
            {
                $image->add_watermark('../'.$goods_img,'',$GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']);
            }
        }
    }

    // 是否上传商品所略图
    if (isset($_FILES['goods_thumb']) && $_FILES['goods_thumb']['tmp_name'] != '' && $_FILES['goods_thumb']['tmp_name'] != 'none')
    {
        // 上传了，直接使用，原始大小
        $goods_thumb = $image->upload_image($_FILES['goods_thumb']);
    }
    else
    {
        // 如果设置缩略图大小不为0，生成缩略图
        if (!empty($original_img) && $_CFG['thumb_width'] * $_CFG['thumb_height'] > 0)
        {
            $goods_thumb = $image->make_thumb('../' . $original_img, $GLOBALS['_CFG']['thumb_width'], $GLOBALS['_CFG']['thumb_height']);
        }
        else
        {
            $goods_thumb = $original_img;
        }

        // 检查创建缩略图是否成功
        if (is_int($goods_thumb))
        {
            switch ($image->error_no)
            {
                case ERR_IMAGE_NOT_EXISTS:
                    $msg = $_LANG['img_not_exists'];
                    break;
                case ERR_NO_GD:
                    $msg = $_LANG['no_gd'];
                    break;
                case ERR_INVALID_IMAGE:
                    $msg = $_LANG['img_invalid'];
                    break;
                case ERR_DIRECTORY_READONLY:
                    $msg = $_LANG['create_dir_failed'];
                    break;
            }
        }
    }

    /* 如果没有输入商品货号则自动生成一个商品货号 */
    if (empty($_POST['goods_sn']))
    {
        $max_id   = $is_insert ? $db->getOne("SELECT MAX(goods_id) + 1 FROM ".$ecs->table('goods')) : $_REQUEST['goods_id'];
        $goods_sn = generate_goods_sn($max_id);
    }
    else
    {
        $goods_sn = $_POST['goods_sn'];
    }

    /* 处理商品数据 */
    $is_promote = isset($_POST['is_promote']) ? 1 : 0;
    $shop_price = !empty($_POST['shop_price']) ? $_POST['shop_price'] : 0;
    $market_price = !empty($_POST['market_price']) ? $_POST['market_price'] : 0;
    $promote_price = !empty($_POST['promote_price']) ? floatval($_POST['promote_price'] ) : 0;
    $promote_start_year = !empty($_POST['promote_start_Year']) ? $_POST['promote_start_Year'] : 0;
    $promote_start_month = !empty($_POST['promote_start_Month']) ? $_POST['promote_start_Month'] : 0;
    $promote_start_day = !empty($_POST['promote_start_Day']) ? $_POST['promote_start_Day'] : 0;
    $promote_start = date("$promote_start_year-$promote_start_month-$promote_start_day");

    $promote_end_year = !empty($_POST['promote_end_Year']) ? $_POST['promote_end_Year'] : 0;
    $promote_end_month = !empty($_POST['promote_end_Month']) ? $_POST['promote_end_Month'] : 0;
    $promote_end_day = !empty($_POST['promote_end_Day']) ? $_POST['promote_end_Day'] : 0;
    $promote_end = date($promote_end_year . '-' . $promote_end_month . '-' . $promote_end_day);

    $is_best = isset($_POST['is_best']) ? 1 : 0;
    $is_new = isset($_POST['is_new']) ? 1 : 0;
    $is_hot = isset($_POST['is_hot']) ? 1 : 0;
    $is_on_sale = isset($_POST['is_on_sale']) ? 1 : 0;
    $is_alone_sale = isset($_POST['is_alone_sale']) ? 1 : 0;
    $can_handsel = isset($_POST['can_handsel']) ? 1 : 0;
    $goods_number = isset($_POST['goods_number']) ? $_POST['goods_number'] : 0;
    $warn_number = isset($_POST['warn_number']) ? $_POST['warn_number'] : 0;
    /* 入库 */
    if ($is_insert)
    {
        $sql = "INSERT INTO " . $ecs->table('goods') . " (goods_name, goods_sn, cat_id, " .
                "shop_price, market_price, is_promote, promote_price, " .
                "promote_start, promote_end, goods_img, goods_thumb, original_img, is_real, keywords, " .
                "goods_brief, goods_number, warn_number, integral, extension_code, " .
                "is_on_sale, is_alone_sale, can_handsel, is_best, is_new, is_hot, ".
                "goods_desc, add_time, last_update, goods_type)" .
                "VALUES ('$_POST[goods_name]', '$goods_sn', '$_POST[cat_id]', " .
                "'$shop_price', '$market_price', '$is_promote','$promote_price', ".
                "'$promote_start', '$promote_end', '$goods_img', '$goods_thumb', '$original_img', '0', '$_POST[keywords]', ".
                "'$_POST[goods_brief]', '$goods_number', '$warn_number', '$_POST[integral]', 'virtual_card', ".
                "'$is_on_sale', '$is_alone_sale', '$can_handsel', '$is_best', '$is_new', '$is_hot', ".
                "'$_POST[goods_desc]', '" . time() . "', '". time() ."', '$_POST[goods_type]')";
    }
    else
    {
        $sql = "UPDATE " . $ecs->table('goods') . " SET " .
                "goods_name = '$_POST[goods_name]', " .
                "goods_sn = '$goods_sn', " .
                "cat_id = '$_POST[cat_id]', " .
                "shop_price = '$shop_price', " .
                "market_price = '$market_price', " .
                "is_promote = '$is_promote', " .
                "promote_price = '$promote_price', " .
                "promote_start = '$promote_start', " .
                "promote_end = '$promote_end', ";
        if ($goods_img)
        {
            $sql .= "goods_img = '$goods_img', original_img = '$original_img', ";
        }
        if ($goods_thumb)
        {
            $sql .= "goods_thumb = '$goods_thumb', ";
        }

        $sql .= "keywords = '$_POST[keywords]', " .
                "goods_brief = '$_POST[goods_brief]', " .
                "warn_number = '$warn_number', " .
                "integral = '$_POST[integral]', " .
                "is_best = '$is_best', " .
                "is_new = '$is_new', " .
                "is_hot = '$is_hot', " .
                "is_on_sale = '$is_on_sale', " .
                "is_alone_sale = '$is_alone_sale', " .
                "can_handsel = '$can_handsel', " .
                "goods_desc = '$_POST[goods_desc]'," .
                "last_update = '". time() ."', ".
                "goods_type = '$_POST[goods_type]' " .
                "WHERE goods_id = '$_REQUEST[goods_id]' LIMIT 1";
    }
    $db->query($sql);

    /* 商品编号 */
    $goods_id = $is_insert ? $db->insert_id() : $_REQUEST['goods_id'];

    /* 记录日志 */
    if ($is_insert)
    {
        admin_log($_POST['goods_name'], 'add', 'goods');
    }
    else
    {
        admin_log($_POST['goods_name'], 'edit', 'goods');
    }

    /* 处理属性 */
    if (isset($_POST['attr_id_list']) && isset($_POST['attr_value_list']))
    {
        $db->query("DELETE FROM " .$ecs->table('goods_attr'). " WHERE goods_id='$goods_id'");

        foreach ($_POST['attr_id_list'] AS $key=>$val)
        {
            if (!empty($_POST['attr_value_list'][$key]))
            {
                $sql = "INSERT INTO " .$ecs->table('goods_attr'). " (attr_id, goods_id, attr_value, attr_price)".
                        "VALUES ('" .$_POST['attr_id_list'][$key]. "', '$goods_id', ".
                                "'" .$_POST['attr_value_list'][$key]. "', '" .$_POST['attr_price_list'][$key]. "')";
                $db->query($sql);
            }
        }
    }

    /* 处理会员价格 */
    if (isset($_POST['user_rank']) && isset($_POST['user_price']))
    {
        handle_member_price($goods_id, $_POST['user_rank'], $_POST['user_price']);
    }

    /* 处理扩展分类 */
    if (isset($_POST['other_cat']))
    {
        handle_other_cat($goods_id, array_unique($_POST['other_cat']));
    }

    if ($is_insert)
    {
        /* 处理关联商品 */
        handle_link_goods($goods_id);

        /* 处理关联文章 */
        handle_goods_article($goods_id);

        /* 更新 is_basic */
        change_is_basic($goods_id);
    }

    /* 清空缓存 */
    clear_cache_files();

    /* 提示页面 */
    if ($is_insert)
    {
        $link[] = array('text' => $_LANG['continue_add_goods'], 'href' => 'virtual_card.php?act=add');
    }
    $link[] = array('text' => $_LANG['back_goods_list'], 'href' => 'virtual_card.php?act=list');
    sys_msg($is_insert ? $_LANG['add_goods_ok'] : $_LANG['edit_goods_ok'], 0, $link);
}

/*------------------------------------------------------ */
//-- 批量操作
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'batch')
{
    /* 取得要操作的商品编号 */
    $goods_id = isset($_POST['checkboxes']) ? join(',', $_POST['checkboxes']) : 0;

    /* 放入回收站 */
    if ($_POST['type'] == 'trash')
    {
        /* 检查权限 */
        admin_priv('remove_back');

        update_goods($goods_id, 'is_delete', '1') or sys_msg($db->error(), '1');

        /* 记录日志 */
        admin_log('', 'batch_trash', 'goods');
    }

    /* 上架 */
    elseif ($_POST['type'] == 'on_sale')
    {
        /* 检查权限 */
        admin_priv('goods_manage');
        update_goods($goods_id, 'is_on_sale', '1') or sys_msg($db->error(), '1');
    }

    /* 下架 */
    elseif ($_POST['type'] == 'not_on_sale')
    {
        /* 检查权限 */
        admin_priv('goods_manage');
        update_goods($goods_id, 'is_on_sale', '0') or sys_msg($db->error(), '1');
    }

    /* 设为精品 */
    elseif ($_POST['type'] == 'best')
    {
        /* 检查权限 */
        admin_priv('goods_manage');
        update_goods($goods_id, 'is_best', '1') or sys_msg($db->error(), '1');
    }

    /* 取消精品 */
    elseif ($_POST['type'] == 'not_best')
    {
        /* 检查权限 */
        admin_priv('goods_manage');
        update_goods($goods_id, 'is_best', '0') or sys_msg($db->error(), '1');
    }

    /* 设为新品 */
    elseif ($_POST['type'] == 'new')
    {
        /* 检查权限 */
        admin_priv('goods_manage');
        update_goods($goods_id, 'is_new', '1') or sys_msg($db->error(), '1');
    }

    /* 取消新品 */
    elseif ($_POST['type'] == 'not_new')
    {
        /* 检查权限 */
        admin_priv('goods_manage');
        update_goods($goods_id, 'is_new', '0') or sys_msg($db->error(), '1');
    }

    /* 设为热销 */
    elseif ($_POST['type'] == 'hot')
    {
        /* 检查权限 */
        admin_priv('goods_manage');
        update_goods($goods_id, 'is_hot', '1') or sys_msg($db->error(), '1');
    }

    /* 取消热销 */
    elseif ($_POST['type'] == 'not_hot')
    {
        /* 检查权限 */
        admin_priv('goods_manage');
        update_goods($goods_id, 'is_hot', '0') or sys_msg($db->error(), '1');
    }

    /* 转移到分类 */
    elseif ($_POST['type'] == 'move_to')
    {
        /* 检查权限 */
        admin_priv('goods_manage');
        update_goods($goods_id, 'cat_id', $_POST['target_cat']) or sys_msg($db->error(), '1');
    }

    /* 清除缓存 */
    clear_cache_files();

    $link[] = array('href' => 'virtual_card.php?act=list', 'text' => $_LANG['virtual_card_list']);
    sys_msg($_LANG['batch_handle_ok'], 0, $link);
}

/*------------------------------------------------------ */
//-- 补货处理
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'replenish')
{
    assign_query_info();

    /* 检查权限 */
    admin_priv('goods_manage');
    /* 验证goods_id是否合法 */
    if (empty($_REQUEST['goods_id']))
    {
        $link[] = array('text'=>$_LANG['go_back'],'href'=>'virtual_card.php?act=list');
        sys_msg($_LANG['replenish_no_goods_id'], 1, $link);
    }
    else
    {
        $goods_name = $db->GetOne("SELECT goods_name From ".$ecs->table('goods')." WHERE goods_id='".$_REQUEST['goods_id']."' AND is_real = 0 AND extension_code='virtual_card' ");
        if (empty($goods_name))
        {
            $link[] = array('text'=>$_LANG['go_back'],'href'=>'virtual_card.php?act=list');
            sys_msg($_LANG['replenish_no_get_goods_name'],1, $link);
        }
    }

    $card = array('goods_id'=>$_REQUEST['goods_id'],'goods_name'=>$goods_name, 'end_date'=>date('Y-m-d', strtotime('+1 year')));
    $smarty->assign('card', $card);

    $smarty->assign('ur_here', $_LANG['replenish']);
    $smarty->assign('action_link', array('text'=>$_LANG['go_list'], 'href'=>'virtual_card.php?act=card&goods_id='.$card['goods_id']));
    $smarty->display($template_dir.'replenish_info.htm');
}

/*------------------------------------------------------ */
//-- 编辑捕获信息
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_replenish')
{
    /* 检查权限 */
    admin_priv('goods_manage');
    /* 获取卡片信息 */
    $sql = "SELECT T1.card_id, T1.goods_id, T2.goods_name,T1.card_sn, T1.card_password, T1.end_date, T1.crc32 FROM ".
            $ecs->table('virtual_card')." AS T1, ".$ecs->table('goods')." AS T2 ".
            "WHERE T1.goods_id = T2.goods_id AND T1.card_id = '$_REQUEST[card_id]'";
    $card = $db->GetRow($sql);
    if ($card['crc32'] == 0 || $card['crc32'] == crc32(AUTH_KEY))
    {
        $card['card_sn']       = decrypt($card['card_sn']);
        $card['card_password'] = decrypt($card['card_password']);
    }
    elseif ($card['crc32'] == crc32(OLD_AUTH_KEY))
    {
        $card['card_sn']       = decrypt($card['card_sn'], OLD_AUTH_KEY);
        $card['card_password'] = decrypt($card['card_password'], OLD_AUTH_KEY);
    }
    else
    {
        $card['card_sn']       = '***';
        $card['card_password'] = '***';
    }

    $smarty->assign('ur_here',     $_LANG['replenish']);
    $smarty->assign('action_link', array('text'=>$_LANG['go_list'], 'href'=>'virtual_card.php?act=card&goods_id='.$card['goods_id']));
    $smarty->assign('card',        $card);
    $smarty->display($template_dir.'replenish_info.htm');
}

elseif ($_REQUEST['act'] == 'action')
{
    /* 检查权限 */
    admin_priv('goods_manage');

    $_POST['card_sn'] = trim($_POST['card_sn']);

    /* 加密后的 */
    $coded_card_sn       = encrypt($_POST['card_sn']);
    $coded_old_card_sn   = encrypt($_POST['old_card_sn']);
    $coded_card_password = encrypt($_POST['card_password']);

    /* 在前后两次card_sn不一致时，检查是否有重复记录,一致时直接更新数据 */
    if ($_POST['card_sn'] != $_POST['old_card_sn'])
    {
        $sql = "SELECT count(*) FROM ".$ecs->table('virtual_card')." WHERE goods_id='".$_POST['goods_id']."' AND card_sn='$coded_card_sn'";

        if ($db->GetOne($sql) > 0)
        {
             $link[] = array('text'=>$_LANG['go_back'], 'href'=>'virtual_card.php?act=replenish&goods_id='.$_POST['goods_id']);
             sys_msg(sprintf($_LANG['card_sn_exist'],$_POST['card_sn']),1,$link);
        }
    }

    /* 如果old_card_sn不存在则新加一条记录 */
    if (empty($_POST['old_card_sn']))
    {
        /* 插入一条新记录 */
        $end_date = strtotime($_POST['end_dateYear'] . "-" . $_POST['end_dateMonth'] . "-" . $_POST['end_dateDay']);
        $add_date = time();
        $sql = "INSERT INTO ".$ecs->table('virtual_card')." (goods_id, card_sn, card_password, end_date, add_date, crc32) ".
               "VALUES ('$_POST[goods_id]', '$coded_card_sn', '$coded_card_password', '$end_date', '$add_date', '" . crc32(AUTH_KEY) . "')";
        $db->query($sql);

        /* 如果添加成功且原卡号为空时商品库存加1 */
        if (empty($_POST['old_card_sn']))
        {
            $sql = "UPDATE ".$ecs->table('goods')." SET goods_number= goods_number+1 WHERE goods_id='$_POST[goods_id]'";
            $db->query($sql);
        }

        $link[] = array('text'=>$_LANG['go_list'], 'href'=>'virtual_card.php?act=card&goods_id='.$_POST['goods_id']);
        $link[] = array('text'=>$_LANG['continue_add'], 'href'=>'virtual_card.php?act=replenish&goods_id='.$_POST['goods_id']);
        sys_msg($_LANG['action_success'], 0, $link);
    }
    else
    {
        /* 更新数据 */
        $end_date = strtotime($_POST['end_dateYear'] . "-" . $_POST['end_dateMonth'] . "-" . $_POST['end_dateDay']);
        $sql = "UPDATE ".$ecs->table('virtual_card')." SET card_sn='$coded_card_sn', card_password='$coded_card_password', end_date='$end_date' ".
               "WHERE card_id='$_POST[card_id]'";
        $db->query($sql);

        $link[] = array('text'=>$_LANG['go_list'], 'href'=>'virtual_card.php?act=card&goods_id='.$_POST['goods_id']);
        $link[] = array('text'=>$_LANG['continue_add'], 'href'=>'virtual_card.php?act=replenish&goods_id='.$_POST['goods_id']);
        sys_msg($_LANG['action_success'], 0, $link);
    }

}
/*------------------------------------------------------ */
//-- 补货列表
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'card')
{
    /* 检查权限 */
    admin_priv('goods_manage');

    /* 验证goods_id是否合法 */
    if (empty($_REQUEST['goods_id']))
    {
        $link[] = array('text'=>$_LANG['go_back'],'href'=>'virtual_card.php?act=list');
        sys_msg($_LANG['replenish_no_goods_id'], 1, $link);
    }
    else
    {
        $goods_name = $db->GetOne("SELECT goods_name From ".$ecs->table('goods')." WHERE goods_id='".$_REQUEST['goods_id']."' AND is_real = 0 AND extension_code='virtual_card' ");
        if (empty($goods_name))
        {
            $link[] = array('text'=>$_LANG['go_back'],'href'=>'virtual_card.php?act=list');
            sys_msg($_LANG['replenish_no_get_goods_name'],1, $link);
        }
    }

    if (empty($_REQUEST['order_sn']))
    {
        $_REQUEST['order_sn'] = '';
    }

    $smarty->assign('full_page',    1);
    $smarty->assign('lang',         $_LANG);
    $smarty->assign('ur_here',      $goods_name);
    $smarty->assign('action_link',  array('text'    => $_LANG['replenish'],
                                            'href'  => 'virtual_card.php?act=replenish&goods_id='.$_REQUEST['goods_id']));

    $list = get_replenish_list();

    $smarty->assign('card_list',    $list['item']);
    $smarty->assign('filter',       $list['filter']);
    $smarty->assign('record_count', $list['record_count']);
    $smarty->assign('page_count',   $list['page_count']);

    $sort_flag = sort_flag($list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    assign_query_info();
    $smarty->display($template_dir.'replenish_list.htm');
}

/*------------------------------------------------------ */
//-- 虚拟卡列表，用于排序、翻页
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'query_card')
{
    $list = get_replenish_list();

    $smarty->assign('card_list',    $list['item']);
    $smarty->assign('filter',       $list['filter']);
    $smarty->assign('record_count', $list['record_count']);
    $smarty->assign('page_count',   $list['page_count']);

    $sort_flag = sort_flag($list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch($template_dir.'replenish_list.htm'), '',
        array('filter'=>$list['filter'], 'page_count'=>$list['page_count']));
}

/* 批量删除card */
elseif ($_REQUEST['act'] == 'batch_drop_card')
{
    /* 检查权限 */
    admin_priv('goods_manage');

    $num = count($_POST['checkboxes']);
    $sql = "DELETE FROM ".$ecs->table('virtual_card')." WHERE card_id ".db_create_in(implode(',',$_POST['checkboxes']));
    if ($db->query($sql))
    {
        /* 商品数量减$num */
        $db->query("UPDATE ".$ecs->table('goods')." SET goods_number= goods_number - '$num' WHERE goods_id = '$_REQUEST[goods_id]'");
        $link[] = array('text'=>$_LANG['go_list'], 'href'=>'virtual_card.php?act=card&goods_id='.$_REQUEST['goods_id']);
        sys_msg($_LANG['action_success'], 0, $link);
    }
}

/* 批量上传页面 */

elseif ($_REQUEST['act'] == 'batch_card_add')
{
    /* 检查权限 */
    admin_priv('goods_manage');

    $smarty->assign('ur_here',          $_LANG['batch_card_add']);
    $smarty->assign('action_link',      array('text'=>$_LANG['virtual_card_list'], 'href'=>'virtual_card.php?act=list'));
    $smarty->assign('goods_id',           $_REQUEST['goods_id']);
    $smarty->display($template_dir.'batch_card_info.htm');
}

elseif ($_REQUEST['act'] == 'batch_confirm')
{
    /* 检查上传是否成功 */
    if ($_FILES['uploadfile']['tmp_name'] == '' || $_FILES['uploadfile']['tmp_name'] == 'none')
    {
        sys_msg($_LANG['uploadfile_fail'], 1);
    }

    $data = file($_FILES['uploadfile']['tmp_name']);
    $rec = array(); //数据数组
    $i = 0;
    $separator = trim($_POST['separator']);
    foreach ($data as $line)
    {
        $row = explode($separator, $line);
        switch(count($row))
        {
            case '3':
                $rec[$i]['end_date'] = $row[2];
            case '2':
                $rec[$i]['card_password'] = $row[1];
            case '1':
                $rec[$i]['card_sn']  = $row[0];
                break;
            default:
                $rec[$i]['card_sn']  = $row[0];
                $rec[$i]['card_password'] = $row[1];
                $rec[$i]['end_date'] = $row[2];
                break;
        }
        $i++;
    }

    $smarty->assign('ur_here',          $_LANG['batch_card_add']);
    $smarty->assign('action_link',      array('text'=>$_LANG['batch_card_add'], 'href'=>'virtual_card.php?act=batch_card_add&goods_id='.$_REQUEST['goods_id']));
    $smarty->assign('list',               $rec);
    $smarty->display($template_dir.'batch_card_confirm.htm');

}
/* 批量上传处理 */
elseif ($_REQUEST['act'] == 'batch_insert')
{
    /* 检查权限 */
    admin_priv('goods_manage');

    $add_time = time();
    $i = 0;
    foreach ($_POST['checked'] as $key)
    {
        $rec['card_sn']  = encrypt($_POST['card_sn'][$key]);
        $rec['card_password'] = encrypt($_POST['card_password'][$key]);
        $rec['crc32']    = crc32(AUTH_KEY);
        $rec['end_date'] = empty($_POST['end_date'][$key])?0:strtotime($_POST['end_date'][$key]);
        $rec['goods_id'] = $_POST['goods_id'];
        $rec['add_date'] = $add_time;
        $db->AutoExecute($ecs->table('virtual_card'), $rec, 'INSERT');
        $i++;
    }

    /* 更新商品库存 */
    $db->query('UPDATE '.$ecs->table('goods')." SET goods_number = goods_number + '$i' WHERE goods_id = '$_REQUEST[goods_id]'");
    $link[] = array('text' => $_LANG['card'] , 'href' => 'virtual_card.php?act=card&goods_id='.$_POST['goods_id']);
    sys_msg(sprintf($_LANG['batch_card_add_ok'], $i) , 0, $link);
}

/*------------------------------------------------------ */
//-- 更改加密串
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'change')
{
    /* 检查权限 */
    admin_priv('goods_manage');

    $smarty->assign('ur_here', $_LANG['virtual_card_change']);

    assign_query_info();
    $smarty->display($template_dir . 'virtual_card_change.htm');
}

/*------------------------------------------------------ */
//-- 提交更改
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'submit_change')
{
    /* 检查权限 */
    admin_priv('goods_manage');

    if (isset($_POST['old_string']) && isset($_POST['new_string']))
    {
        // 检查原加密串是否正确
        if ($_POST['old_string'] != OLD_AUTH_KEY)
        {
            sys_msg($_LANG['invalid_old_string'], 1);
        }

        // 检查新加密串是否正确
        if ($_POST['new_string'] != AUTH_KEY)
        {
            sys_msg($_LANG['invalid_new_string'], 1);
        }

        // 检查原加密串和新加密串是否相同
        if ($_POST['old_string'] == $_POST['new_string'] || crc32($_POST['old_string']) == crc32($_POST['new_string']))
        {
            sys_msg($_LANG['same_string'], 1);
        }

        // 重新加密卡号和密码
        $old_crc32 = crc32($_POST['old_string']);
        $new_crc32 = crc32($_POST['new_string']);
        $sql = "SELECT card_id, card_sn, card_password FROM " . $ecs->table('virtual_card') . " WHERE crc32 = '$old_crc32'";
        $res = $db->query($sql);
        while ($row = $db->fetchRow($res))
        {
            $row['card_sn'] = encrypt(decrypt($row['card_sn'], $_POST['old_string']), $_POST['new_string']);
            $row['card_password'] = encrypt(decrypt($row['card_password'], $_POST['old_string']), $_POST['new_string']);
            $row['crc32'] = $new_crc32;
            $db->autoExecute($ecs->table('virtual_card'), $row, 'UPDATE', 'card_id = ' . $row['card_id']);
        }

        // 记录日志
        //admin_log();

        // 返回
        sys_msg($_LANG['change_key_ok'], 0, array(array('href' => 'virtual_card.php?act=list', 'text' => $_LANG['virtual_card_list'])));
    }
}

/*------------------------------------------------------ */
//-- 搜索商品，仅返回名称及ID
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'get_goods_list')
{
    include_once('../includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);

    $arr = get_goods_list($filters);
    $opt = array();

    foreach ($arr AS $key=>$val)
    {
        $opt[] = array('value'  => $val['goods_id'],
                        'text'  => $val['goods_name'],
                        'data'  => $val['shop_price']);
    }

    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 把商品加入关联
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add_link_goods')
{
    include_once('../includes/cls_json.php');
    $json = new JSON;

    check_authz_json('goods_manage');

    $linked_array   = $json->decode($_GET['add_ids']);
    $linked_goods   = $json->decode($_GET['JSON']);
    $goods_id       = $linked_goods[0];
    $is_double      = $linked_goods[1] == 'true' ? 0 : 1;

    foreach ($linked_array AS $val)
    {
        if ($is_double)
        {
            /* 双向关联 */
            $sql = "INSERT INTO " . $ecs->table('link_goods') . " (goods_id, link_goods_id, is_double) " .
                    "VALUES ('$val', '$goods_id', '$is_double')";
            $db->query($sql, 'SILENT');
        }

        $sql = "INSERT INTO " . $ecs->table('link_goods') . " (goods_id, link_goods_id, is_double) " .
                "VALUES ('$goods_id', '$val', '$is_double')";
        $db->query($sql, 'SILENT');
    }

    $linked_goods   = get_linked_goods($goods_id);
    $options        = array();

    foreach ($linked_goods AS $val)
    {
        $options[] = array('value'  => $val['goods_id'],
                        'text'      => $val['goods_name'],
                        'data'      => '');
    }

    make_json_result($options);
}

/*------------------------------------------------------ */
//-- 删除关联商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_link_goods')
{
    include_once('../includes/cls_json.php');
    $json = new JSON;

    check_authz_json('goods_manage');

    $drop_goods     = $json->decode($_GET['drop_ids']);
    $drop_goods_ids = db_create_in($drop_goods);
    $linked_goods   = $json->decode($_GET['JSON']);
    $goods_id       = $linked_goods[0];
    $is_signle      = $linked_goods[1];

    if (!$is_signle)
    {
        $sql = "DELETE FROM " .$ecs->table('link_goods') .
                " WHERE link_goods_id='$goods_id' AND goods_id " . $drop_goods_ids;
    }
    else
    {
        $sql = "UPDATE " .$ecs->table('link_goods') . " SET is_double = 0 ".
                " WHERE link_goods_id='$goods_id' AND goods_id " . $drop_goods_ids;
    }
    $db->query($sql);

    $sql = "DELETE FROM " .$ecs->table('link_goods') .
            " WHERE goods_id='$goods_id' AND link_goods_id " . $drop_goods_ids;
    $db->query($sql);

    $linked_goods   = get_linked_goods($goods_id);
    $options        = array();

    foreach ($linked_goods AS $val)
    {
        $options[] = array('value'  => $val['goods_id'],
                        'text'      => $val['goods_name'],
                        'data'      => '');
    }

    make_json_result($options);
}

/*------------------------------------------------------ */
//-- 搜索文章
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'get_article_list')
{
    include_once('../includes/cls_json.php');
    $json = new JSON;

    $filters    = $json->decode($_GET['JSON']);
    $keyword    = trim($filters['title']);

    $sql        = "SELECT article_id, title FROM " .$ecs->table('article').
                    " WHERE cat_id > 0 AND title LIKE '%" . mysql_like_quote($keyword) . "%' ORDER BY article_id DESC LIMIT 50";
    $res        = $db->query($sql);
    $arr        = array();

    while ($row = $db->fetchRow($res))
    {
        $arr[]  = array('value' => $row['article_id'], 'text'=>$row['title'], 'data'=>'');
    }

    make_json_result($arr);
}

/*------------------------------------------------------ */
//-- 添加关联文章
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add_goods_article')
{
    include_once('../includes/cls_json.php');
    $json = new JSON;

    check_authz_json('goods_manage');

    $articles   = $json->decode($_GET['add_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $goods_id   = $arguments[0];

    foreach ($articles AS $val)
    {
        $sql = "INSERT INTO " . $ecs->table('goods_article') . " (goods_id, article_id) " .
                "VALUES ('$goods_id', '$val')";
        $db->query($sql, 'SILENT');
    }

    $arr = get_goods_articles($goods_id);
    $opt = array();

    foreach ($arr AS $val)
    {
        $opt[] = array('value'      => $val['article_id'],
                        'text'      => $val['title'],
                        'data'      => '');
    }

    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 删除关联文章
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_goods_article')
{
    include_once('../includes/cls_json.php');
    $json = new JSON;

    check_authz_json('goods_manage');

    $articles   = $json->decode($_GET['drop_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $goods_id   = $arguments[0];

    $sql = "DELETE FROM " .$ecs->table('goods_article') . " WHERE " . db_create_in($articles, "article_id");
    $db->query($sql);

    $arr = get_goods_articles($goods_id);
    $opt = array();

    foreach ($arr AS $val)
    {
        $opt[] = array('value'      => $val['article_id'],
                        'text'      => $val['title'],
                        'data'      => '');
    }

    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 修改商品名称
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_goods_name')
{
    check_authz_json('goods_manage');

    $goods_id   = intval($_POST['id']);
    $goods_name = trim($_POST['val']);

    $sql = "UPDATE " .$ecs->table('goods'). " SET goods_name='$goods_name' WHERE goods_id='$goods_id'";

    if ($db->query($sql))
    {
        make_json_result(stripslashes($_POST['val']));
    }
    else
    {
        make_json_error($_LANG['cannot_found_goods']);
    }
}

/*------------------------------------------------------ */
//-- 修改商品货号
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_goods_sn')
{
    check_authz_json('goods_manage');

    $goods_id = intval($_POST['id']);
    $goods_sn = trim($_POST['val']);

    /* 检查是否重复 */
    $sql = "SELECT COUNT(*) FROM " . $ecs->table('goods') . " WHERE goods_sn = '$goods_sn' AND goods_id <> '$goods_id'";

    if ($db->getOne($sql) > 0)
    {
        make_json_error($_LANG['goods_sn_exists']);
    }
    else
    {
        if (update_goods($goods_id, 'goods_sn', $goods_sn))
        {
            make_json_result(stripslashes($goods_sn));
        }
        else
        {
            make_json_error($db->error());
        }
    }
}

/*------------------------------------------------------ */
//-- 修改商品价格
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_goods_price')
{
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $goods_price    = floatval($_POST['val']);

    if (update_goods($goods_id, 'shop_price', $goods_price))
    {
        make_json_result(number_format($goods_price, 2));
    }
    else
    {
        make_json_error($GLOBALS['db']->errorMsg());
    }
}

/*------------------------------------------------------ */
//-- 修改商品库存数量
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_goods_number')
{
    check_authz_json('goods_manage');

    $goods_id   = intval($_POST['id']);
    $goods_num  = intval($_POST['val']);

    if (update_goods($goods_id, 'goods_number', $goods_num))
    {
        make_json_result($goods_num);
    }
    else
    {
        make_json_error($db->error());
    }
}

/*------------------------------------------------------ */
//-- 修改上架状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_on_sale')
{
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $on_sale        = intval($_POST['val']);

    if (update_goods($goods_id, 'is_on_sale', $on_sale))
    {
        make_json_result($on_sale);
    }
    else
    {
        make_json_error($GLOBALS['db']->errorMsg());
    }
}

/*------------------------------------------------------ */
//-- 修改精品推荐状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_best')
{
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $is_best        = intval($_POST['val']);

    if (update_goods($goods_id, 'is_best', $is_best))
    {
        make_json_result($is_best);
    }
    else
    {
        make_json_error($GLOBALS['db']->errorMsg());
    }
}

/*------------------------------------------------------ */
//-- 修改新品推荐状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_new')
{
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $is_new         = intval($_POST['val']);

    if (update_goods($goods_id, 'is_new', $is_new))
    {
        make_json_result($is_new);
    }
    else
    {
        make_json_error($GLOBALS['db']->errorMsg());
    }
}

/*------------------------------------------------------ */
//-- 修改热销推荐状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_hot')
{
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $is_hot         = intval($_POST['val']);

    if (update_goods($goods_id, 'is_hot', $is_hot))
    {
        make_json_result($is_hot);
    }
    else
    {
        make_json_error($GLOBALS['db']->errorMsg());
    }
}

/*------------------------------------------------------ */
//-- 放入回收站
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    $goods_id = intval($_REQUEST['id']);

    /* 检查权限 */
    check_authz_json('remove_back');

    if (update_goods($goods_id, 'is_delete', '1'))
    {
        $sql        = "SELECT goods_name FROM " . $GLOBALS['ecs']->table('goods') . " WHERE goods_id = '$goods_id'";
        $goods_name = $GLOBALS['db']->getOne($sql);

        admin_log(addslashes($goods_name), 'trash', 'goods'); // 记录日志

        $url = 'virtual_card.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

        header("Location: $url\n");
        exit;
    }
    else
    {
        make_json_error($GLOBALS['db']->errorMsg());
    }
}

/*------------------------------------------------------ */
//-- 删除图片
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_image')
{
    check_authz_json('goods_manage');

    $img_id = empty($_REQUEST['img_id']) ? 0 : intval($_REQUEST['img_id']);

    /* 删除图片文件 */
    $sql = "SELECT img_url, thumb_url, img_original " .
            " FROM " . $GLOBALS['ecs']->table('goods_gallery') .
            " WHERE img_id = '$img_id'";
    $row = $GLOBALS['db']->getRow($sql);

    if ($row['img_url'] != '' && is_file('../' . $row['img_url']))
    {
        @unlink('../' . $row['img_url']);
    }
    if ($row['thumb_url'] != '' && is_file('../' . $row['thumb_url']))
    {
        @unlink('../' . $row['thumb_url']);
    }
    if ($row['img_original'] != '' && is_file('../' . $row['img_original']))
    {
        @unlink('../' . $row['img_original']);
    }

    /* 删除数据 */
    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('goods_gallery') . " WHERE img_id = '$img_id' LIMIT 1";
    $GLOBALS['db']->query($sql);

    make_json_result($img_id);
}

/*------------------------------------------------------ */
//-- 切换是否已出售状态
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'toggle_sold')
{
    check_authz_json('goods_manage');

    $id = intval($_POST['id']);
    $val = intval($_POST['val']);

    $sql = "UPDATE ".$ecs->table('virtual_card')." SET is_saled= '$val' WHERE card_id='$id'";

    if ($db->query($sql, 'SILENT'))
    {
        make_json_result($val);
    }
    else
    {
        make_json_error($_LANG['action_fail'] . "\n" .$db->error());
    }
}

/*------------------------------------------------------ */
//-- 删除卡片
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove_card')
{
    check_authz_json('goods_manage');

    $id = intval($_GET['id']);

    $row = $db->GetRow('SELECT card_sn, goods_id FROM ' . $ecs->table('virtual_card') . " WHERE card_id = '$id'");

    $sql = 'DELETE FROM ' . $ecs->table('virtual_card') . " WHERE card_id = '$id'";
    if ($db->query($sql, 'SILENT'))
    {
        /* 商品数量减1 */
        $db->query('UPDATE ' . $ecs->table('goods') . " SET goods_number = goods_number - 1 WHERE goods_id = '$row[goods_id]'");

        $url = 'virtual_card.php?act=query_card&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

        header("Location: $url\n");
        exit;
    }
    else
    {
        make_json_error($db->error());
    }
}

/*------------------------------------------------------ */
//-- 开始更改加密串：先检查原串和新串
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'start_change')
{
    $old_key = trim($_GET['old_key']);
    $new_key = trim($_GET['new_key']);

    if ($old_key != OLD_AUTH_KEY)
    {
        make_json_error($GLOBALS['_LANG']['invalid_old_string']);
    }

    // 检查新加密串是否正确
    if ($new_key != AUTH_KEY)
    {
        make_json_error($GLOBALS['_LANG']['invalid_new_string']);
    }

    // 检查原加密串和新加密串是否相同
    if ($old_key == $new_key || crc32($old_key) == crc32($new_key))
    {
        make_json_error($GLOBALS['_LANG']['same_string']);
    }

    // 查询统计信息：总记录，使用原串的记录，使用新串的记录，使用未知串的记录
    $stat = array('all' => 0, 'new' => 0, 'old' => 0, 'unknown' => 0);
    $sql = "SELECT crc32, count(*) AS cnt FROM " . $ecs->table('virtual_card') . " GROUP BY crc32";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $db->fetchRow($res))
    {
        $stat['all'] += $row['cnt'];
        if (crc32($new_key) == $row['crc32'])
        {
            $stat['new'] += $row['cnt'];
        }
        elseif (crc32($old_key) == $row['crc32'])
        {
            $stat['old'] += $row['cnt'];
        }
        else
        {
            $stat['unknown'] += $row['cnt'];
        }
    }

    make_json_result(sprintf($GLOBALS['_LANG']['old_stat'], $stat['all'], $stat['new'], $stat['old'], $stat['unknown']));
}

/*------------------------------------------------------ */
//-- 更新加密串
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'on_change')
{
   // 重新加密卡号和密码
   $each_num    = 1;
   $old_crc32   = crc32(OLD_AUTH_KEY);
   $new_crc32   = crc32(AUTH_KEY);
   $updated     = intval($_GET['updated']);

   $sql = "SELECT card_id, card_sn, card_password ".
            " FROM " . $ecs->table('virtual_card') .
            " WHERE crc32 = '$old_crc32' LIMIT $each_num";
   $res = $db->query($sql);

   while ($row = $db->fetchRow($res))
   {
       $row['card_sn']       = encrypt(decrypt($row['card_sn'], OLD_AUTH_KEY));
       $row['card_password'] = encrypt(decrypt($row['card_password'], OLD_AUTH_KEY));
       $row['crc32']         = $new_crc32;

       if (!$db->autoExecute($ecs->table('virtual_card'), $row, 'UPDATE', 'card_id = ' . $row['card_id']))
       {
           make_json_error($updated, 0, $_LANG['update_error'] ."\n". $db->error());
       }

       $updated++;
    }

    // 查询是否还有未更新的
    $sql      = "SELECT COUNT(*) FROM " . $ecs->table('virtual_card') . " WHERE crc32 = '$old_crc32' ";
    $left_num = $db->getOne($sql);

    if ($left_num > 0)
    {
        make_json_result($updated);
    }
    else
    {
        // 查询统计信息
        $stat = array('new' => 0, 'unknown' => 0);
        $sql = "SELECT crc32, count(*) AS cnt FROM " . $GLOBALS['ecs']->table('virtual_card') . " GROUP BY crc32";
        $res = $GLOBALS['db']->query($sql);
        while ($row = $db->fetchRow($res))
        {
            if ($new_crc32 == $row['crc32'])
            {
                $stat['new'] += $row['cnt'];
            }
            else
            {
                $stat['unknown'] += $row['cnt'];
            }
        }

        make_json_result($updated, sprintf($_LANG['new_stat'], $stat['new'], $stat['unknown']));
    }
}

/**
 * 返回补货列表
 *
 * @return array
 */
function get_replenish_list()
{
    /* 查询条件 */
    $filter['goods_id']    = empty($_REQUEST['goods_id'])    ? 0 : intval($_REQUEST['goods_id']);
    $filter['search_type'] = empty($_REQUEST['search_type']) ? 0 : trim($_REQUEST['search_type']);
    $filter['order_sn']    = empty($_REQUEST['order_sn'])    ? 0 : trim($_REQUEST['order_sn']);
    $filter['keyword']     = empty($_REQUEST['keyword'])     ? 0 : trim($_REQUEST['keyword']);
    $filter['sort_by']     = empty($_REQUEST['sort_by'])     ? 'card_id' : trim($_REQUEST['sort_by']);
    $filter['sort_order']  = empty($_REQUEST['sort_order'])  ? 'DESC' : trim($_REQUEST['sort_order']);

    $where  = (!empty($filter['goods_id'])) ? " AND goods_id = '" . $filter['goods_id'] . "' " : '';
    $where .= (!empty($filter['order_sn'])) ? " AND order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%' " : '';

    if (!empty($filter['keyword']))
    {
        if ($filter['search_type'] == 'card_sn')
        {
            $where .= " AND card_sn = '" .encrypt($filter['keyword']). "'";
        }
        else
        {
            $where .= " AND order_sn LIKE '%" . mysql_like_quote($filter['keyword']). "%' ";
        }
    }

    $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('virtual_card') . " WHERE 1 $where";
    $filter['record_count'] = $GLOBALS['db']->getOne($sql);

    /* 分页大小 */
    $filter = page_and_size($filter);
    $start  = ($filter['page'] - 1) * $filter['page_size'];

    /* 查询 */
    $sql = "SELECT card_id, goods_id, card_sn, card_password, end_date, is_saled, order_sn, crc32 ".
            " FROM ".$GLOBALS['ecs']->table('virtual_card').
            " WHERE 1 ".$where.
            " ORDER BY $filter[sort_by] $filter[sort_order] ".
            " LIMIT $start, $filter[page_size]";
    $all = $GLOBALS['db']->getAll($sql);

    $arr = array();
    foreach ($all AS $key => $row)
    {
        if ($row['crc32'] == 0 || $row['crc32'] == crc32(AUTH_KEY))
        {
            $row['card_sn']       = decrypt($row['card_sn']);
            $row['card_password'] = decrypt($row['card_password']);
        }
        elseif ($row['crc32'] == crc32(OLD_AUTH_KEY))
        {
            $row['card_sn']       = decrypt($row['card_sn'], OLD_AUTH_KEY);
            $row['card_password'] = decrypt($row['card_password'], OLD_AUTH_KEY);
        }
        else
        {
            $row['card_sn']       = '***';
            $row['card_password'] = '***';
        }

        $row['end_date'] = date($GLOBALS['_CFG']['date_format'], $row['end_date']);

        $arr[] = $row;
    }

    return array('item' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

?>