<?php
define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
//require_once(ROOT_PATH . '/' . ADMIN_PATH . '/includes/lib_homestay.php');
include_once(ROOT_PATH . '/includes/cls_image.php');
$image = new cls_image($_CFG['bgcolor']);
$exc = new exchange($ecs->table('hs_room'), $db, 'id', 'name');

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

if ($_REQUEST['act'] == 'list')
{
//    admin_priv('room_manage');


    $room_ur = array('' => $_LANG['01_room_list'], 'virtual_card'=>$_LANG['50_virtual_card_list']);
    $ur_here = ($_REQUEST['act'] == 'list') ? $room_ur[$code] : $_LANG['11_room_trash'];
    $smarty->assign('ur_here', $ur_here);
    $action_link = array('href' => 'room.php?act=add', 'text' => '加入房間');
    $smarty->assign('action_link',  $action_link);

    $smarty->assign('code',     $code);
//    $smarty->assign('cat_list',     room_cat_list(0, $cat_id));
    $smarty->assign('lang',         $_LANG);
    $smarty->assign('list_type',    $_REQUEST['act'] == 'list' ? 'room' : 'trash');
    $smarty->assign('use_storage',  empty($_CFG['use_storage']) ? 0 : 1);

    $room_list = room_list($_SESSION['user_id']);
    $smarty->assign('room_list',   	$room_list['room']);
    $smarty->assign('filter',       $room_list['filter']);
    $smarty->assign('record_count', $room_list['record_count']);
    $smarty->assign('page_count',   $room_list['page_count']);
    $smarty->assign('full_page',    1);

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

    /* 获取商品类型存在规格的类型 */

    assign_menu_info();
    assign_query_info();
    $smarty->display('room_list.htm');
}

elseif ($_REQUEST['act'] == 'query')
{
    $room_list = room_list($_SESSION['user_id']);

 
    $smarty->assign('room_list',   $room_list['room']);
    $smarty->assign('filter',       $room_list['filter']);
    $smarty->assign('record_count', $room_list['record_count']);
    $smarty->assign('page_count',   $room_list['page_count']);

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

    /* 获取商品类型存在规格的类型 */

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

elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
{

    $is_add = $_REQUEST['act'] == 'add'; // 添加还是编辑的标识
//    admin_priv('room_manage'); // 检查权限
    /* 如果是安全模式，检查目录是否存在 */
	
    if (ini_get('safe_mode') == 1 && (!file_exists('../' . IMAGE_DIR . '/'.date('Ym')) || !is_dir('../' . IMAGE_DIR . '/'.date('Ym'))))
    {
        if (@!mkdir('../' . IMAGE_DIR . '/'.date('Ym'), 0777))
        {
            $warning = sprintf($_LANG['safe_mode_warning'], '../' . IMAGE_DIR . '/'.date('Ym'));
            $smarty->assign('warning', $warning);
        }
    }

    /* 如果目录存在但不可写，提示用户 */
    elseif (file_exists('../' . IMAGE_DIR . '/'.date('Ym')) && file_mode_info('../' . IMAGE_DIR . '/'.date('Ym')) < 2)
    {
        $warning = sprintf($_LANG['not_writable_warning'], '../' . IMAGE_DIR . '/'.date('Ym'));
        $smarty->assign('warning', $warning);
    }

    /* 取得商品信息 */
    if ($is_add)
    {
        $room = array(
            'id'      => 0,
            'name'    => '',
            'intro'    => '',
            'notice'    => '',
        );
        /* 图片列表 */
        $img_list = array();
    }
    else
    {
        /* 商品信息 */
        $sql = "SELECT * FROM " . $ecs->table('hs_room') . " WHERE id = '$_REQUEST[id]'";
        $room = $db->getRow($sql);
        if (empty($room) === true)
        {
            /* 默认值 */
			$room = array(
				'id'      => 0,
				'name'    => '',
				'intro'    => '',
				'notice'    => '',
			);
        }

        /* 图片列表 */
        $sql = "SELECT * FROM " . $ecs->table('rm_gallery') . " WHERE rm_id = '$room[id]' order by img_desc";

        $img_list = $db->getAll($sql);

        /* 格式化相册图片路径 */
        if (isset($GLOBALS['shop_id']) && ($GLOBALS['shop_id'] > 0))
        {
            foreach ($img_list as $key => $gallery_img)
            {
                $gallery_img[$key]['img_url'] = get_image_path($gallery_img['room_id'], $gallery_img['img_original'], false, 'gallery');
                $gallery_img[$key]['thumb_url'] = get_image_path($gallery_img['room_id'], $gallery_img['img_original'], true, 'gallery');
            }
        }
        else
        {
            foreach ($img_list as $key => $gallery_img)
            {
                $gallery_img[$key]['thumb_url'] = '../' . (empty($gallery_img['thumb_url']) ? $gallery_img['img_url'] : $gallery_img['thumb_url']);
            }
        }
    }


    /* 创建 html editor */
    //create_html_editor('room_desc', $room['room_desc']);
    //$smarty->assign('room_desc',    $room['room_desc']);

    /* 模板赋值 */
    $smarty->assign('ur_here', $is_add ? (empty($code) ? $_LANG['02_room_add'] : $_LANG['51_virtual_card_add']) : ($_REQUEST['act'] == 'edit' ? $_LANG['edit_room'] : $_LANG['copy_room']));
    $smarty->assign('action_link', list_link($is_add, $code));
    $smarty->assign('room', $room);
    $smarty->assign('cfg', $_CFG);
    $smarty->assign('form_act', $is_add ? 'insert' : ($_REQUEST['act'] == 'edit' ? 'update' : 'insert'));
    if ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
    {
        $smarty->assign('is_add', true);
    }
    $smarty->assign('img_list', $img_list);
    $smarty->assign('gd', gd_version());
    $smarty->assign('thumb_width', 200);
    $smarty->assign('thumb_height', 0);
//    $smarty->assign('room_attr_html', build_attr_html($room['room_type'], $room['room_id']));

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

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

elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')
{
//    admin_priv('room_manage'); // 检查权限
    /* 检查图片：如果有错误，检查尺寸是否超过最大值；否则，检查文件类型 */
    if (isset($_FILES['image1']['error'])) // php 4.2 版本才支持 error
    {
        // 最大上传文件大小
        $php_maxsize = ini_get('upload_max_filesize');
        $htm_maxsize = '20M';

        // 商品图片
        if ($_FILES['image1']['error'] == 0)
        {
            if (!$image->check_img_type($_FILES['image1']['type']))
            {
                sys_msg('圖片格式錯誤', 1, array(), false);
            }
        }
        elseif ($_FILES['image1']['error'] == 1)
        {
            sys_msg(sprintf('圖檔太大', $php_maxsize), 1, array(), false);
        }
        elseif ($_FILES['image1']['error'] == 2)
        {
            sys_msg(sprintf('圖檔太大', $htm_maxsize), 1, array(), false);
        }

        // 相冊圖片 - 功能保留
        foreach ($_FILES['img_url']['error'] AS $key => $value)
        {
            if ($value == 0)
            {
                if (!$image->check_img_type($_FILES['img_url']['type'][$key]))
                {
                    sys_msg(sprintf($_LANG['invalid_img_url'], $key + 1), 1, array(), false);
                }
            }
            elseif ($value == 1)
            {
                sys_msg(sprintf('圖檔太大', $key + 1, $php_maxsize), 1, array(), false);
            }
            elseif ($_FILES['img_url']['error'] == 2)
            {
                sys_msg(sprintf('圖檔太大', $key + 1, $htm_maxsize), 1, array(), false);
            }
        }
    }
    /* 4.1版本 */
    else
    {
        // 商品图片
        if ($_FILES['image1']['tmp_name'] != 'none' && $_FILES['image1']['tmp_name'] != '')
        {
            if (!$image->check_img_type($_FILES['image1']['type']))
            {

                sys_msg($_LANG['invalid_room_img'], 1, array(), false);
            }
        }

        // 相册图片
        foreach ($_FILES['img_url']['tmp_name'] AS $key => $value)
        {
            if ($value != 'none' &&$value != '')
            {
                if (!$image->check_img_type($_FILES['img_url']['type'][$key]))
                {
                    sys_msg(sprintf($_LANG['invalid_img_url'], $key + 1), 1, array(), false);
                }
            }
        }
    }

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

    /* 处理商品图片 */
    $image1        = '';  // 初始化商品图片
    $old_image1 = '';  // 初始化原始图片旧图

    // 如果上传了商品图片，相应处理
    if (($_FILES['image1']['tmp_name'] != '' && $_FILES['image1']['tmp_name'] != 'none'))
    {
        if ($_REQUEST['id'] > 0)
        {
            /* 删除原来的图片文件 */
            $sql = "SELECT image1 " .
                    " FROM " . $ecs->table('hs_room') .
                    " WHERE id = '$_REQUEST[id]'";
            $row = $db->getRow($sql);
            if ($row['image1'] != '' && is_file('../' . $row['image1']))
            {
                @unlink('../' . $row['image1']);
            }
        }
        $original_img   = $image->upload_image($_FILES['image1']); // 原始图片
        if ($original_img === false)
        {
            sys_msg($image->error_msg(), 1, array(), false);
        }
        $image1      = $original_img;   // 商品图片
		
	}


    /* 處理數據 */
    $catgory_id = empty($_POST['cat_id']) ? '' : intval($_POST['cat_id']);

    $room_thumb = (empty($room_thumb) && !empty($_POST['room_thumb_url']) && room_parse_url($_POST['room_thumb_url'])) ? htmlspecialchars(trim($_POST['room_thumb_url'])) : $room_thumb;
    $room_thumb = (empty($room_thumb) && isset($_POST['auto_thumb']))? $room_img : $room_thumb;

    /* 入库 */
    if ($is_insert)
    {
            $sql = "INSERT INTO " . $ecs->table('hs_room') . " (hs_id,name, price,intro, notice, " .
					"image1,".
                    " cstamp, ustamp)" .
                "VALUES ('$_SESSION[user_id]','$_POST[name]','$_POST[price]', '$_POST[intro]','$_POST[notice]', " .
                "'$image1',".
                    " '" . date('Y-m-d h:i:s',gmtime()) . "', '". date('Y-m-d h:i:s',gmtime()) ."')";
    }
    else
    {
        /* 如果有上传图片，删除原来的商品图 */
        //$sql = "SELECT image1 " .
        //            " FROM " . $ecs->table('hs_room') .
        //            " WHERE id = '$_REQUEST[id]'";
        //$row = $db->getRow($sql);
        //if ($row['image1'])
        //{
        //    @unlink(ROOT_PATH . $row['image1']);
        //}

        $sql = "UPDATE " . $ecs->table('hs_room') . " SET " .
                "name = '$_POST[name]', " .
                "price = '$_POST[price]', " .
                "intro = '$_POST[intro]', " .
                "notice = '$_POST[notice]', ";

        /* 如果有上传图片，需要更新数据库 */
        if ($image1)
        {
            $sql .= "image1 = '$image1', ";
        }
        $sql .= "ustamp = '". gmtime() ."' ".
                "WHERE id = '$_REQUEST[id]' LIMIT 1";
    }

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

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


    /* 处理相册图片 */
    handle_gallery_image($id, $_FILES['img_url'], $_POST['img_desc']);

    /* 编辑时处理相册图片描述 */
    if (!$is_insert && isset($_POST['old_img_desc']))
    {
        foreach ($_POST['old_img_desc'] AS $img_id => $img_desc)
        {
            $sql = "UPDATE " . $ecs->table('rm_gallery') . " SET img_desc = '$img_desc' WHERE img_id = '$img_id' LIMIT 1";
            $db->query($sql);
        }
    }

    /* 不保留商品原图的时候删除原图 */
    if ($proc_thumb && !$_CFG['retain_original_img'] && !empty($original_img))
    {
        $db->query("UPDATE " . $ecs->table('room') . " SET original_img='' WHERE `room_id`='{$room_id}'");
        $db->query("UPDATE " . $ecs->table('rm_gallery') . " SET img_original='' WHERE `room_id`='{$room_id}'");
        @unlink('../' . $original_img);
        @unlink('../' . $img);
    }

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

    /* 是否有货品 */
//    $specifications_list = get_room_specifications_list($room_id);
//    $product_list_url = $GLOBALS['ecs']->url()."admin/room.php?act=product_list&room_id=".$room_id;
//    if($specifications_list){
//        echo '<script type="text/javascript">window.location.href="'.$product_list_url.'";</script>';exit;
//    }
    /* 提示页面 */
//    $link = array();
//    if (check_room_specifications_exist($room_id) && $specifications_list)
//    {
//        $link[0] = array('href' => 'room.php?act=product_list&room_id=' . $room_id, 'text' => $_LANG['product']);
//    }
//    if ($code == 'virtual_card')
//    {
//        $link[1] = array('href' => 'virtual_card.php?act=replenish&room_id=' . $room_id, 'text' => $_LANG['add_replenish']);
//    }
    if ($is_insert)
    {
        $link[0] = add_link();
    }else{
		$link[0] = array('href' => 'room.php?act=edit&id='.$_REQUEST['id'], 'text' => '繼續編輯');
		
	}
    $link[1] = list_link($is_insert);


    //$key_array = array_keys($link);
    for($i=0;$i<count($link);$i++)
    {
       $key_array[]=$i;
    }
    krsort($link);
    $link = array_combine($key_array, $link);


    sys_msg($is_insert ? '新增完成' : '編輯完成', 0, $link);
}

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

elseif ($_REQUEST['act'] == 'batch')
{
    $code = empty($_REQUEST['extension_code'])? '' : trim($_REQUEST['extension_code']);

    /* 取得要操作的商品编号 */
    $room_id = !empty($_POST['checkboxes']) ? join(',', $_POST['checkboxes']) : 0;

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

            update_room($room_id, 'is_delete', '1');

            /* 记录日志 */
            admin_log('', 'batch_trash', 'room');
        }
        /* 上架 */
        elseif ($_POST['type'] == 'on_sale')
        {
            /* 检查权限 */
            admin_priv('room_manage');
            update_room($room_id, 'is_on_sale', '1');
        }

        /* 下架 */
        elseif ($_POST['type'] == 'not_on_sale')
        {
            /* 检查权限 */
            admin_priv('room_manage');
            update_room($room_id, 'is_on_sale', '0');
        }

        /* 设为精品 */
        elseif ($_POST['type'] == 'best')
        {
            /* 检查权限 */
            admin_priv('room_manage');
            update_room($room_id, 'is_best', '1');
        }

        /* 取消精品 */
        elseif ($_POST['type'] == 'not_best')
        {
            /* 检查权限 */
            admin_priv('room_manage');
            update_room($room_id, 'is_best', '0');
        }

        /* 设为新品 */
        elseif ($_POST['type'] == 'new')
        {
            /* 检查权限 */
            admin_priv('room_manage');
            update_room($room_id, 'is_new', '1');
        }

        /* 取消新品 */
        elseif ($_POST['type'] == 'not_new')
        {
            /* 检查权限 */
            admin_priv('room_manage');
            update_room($room_id, 'is_new', '0');
        }

        /* 设为热销 */
        elseif ($_POST['type'] == 'hot')
        {
            /* 检查权限 */
            admin_priv('room_manage');
            update_room($room_id, 'is_hot', '1');
        }

        /* 取消热销 */
        elseif ($_POST['type'] == 'not_hot')
        {
            /* 检查权限 */
            admin_priv('room_manage');
            update_room($room_id, 'is_hot', '0');
        }

        /* 转移到分类 */
        elseif ($_POST['type'] == 'move_to')
        {
            /* 检查权限 */
            admin_priv('room_manage');
            update_room($room_id, 'cat_id', $_POST['target_cat']);
        }

        /* 转移到供货商 */
        elseif ($_POST['type'] == 'suppliers_move_to')
        {
            /* 检查权限 */
            admin_priv('room_manage');
            update_room($room_id, 'suppliers_id', $_POST['suppliers_id']);
        }

        /* 还原 */
        elseif ($_POST['type'] == 'restore')
        {
            /* 检查权限 */
            admin_priv('remove_back');

            update_room($room_id, 'is_delete', '0');

            /* 记录日志 */
            admin_log('', 'batch_restore', 'room');
        }
        /* 删除 */
        elseif ($_POST['type'] == 'drop')
        {
            /* 检查权限 */
            admin_priv('remove_back');

            delete_room($room_id);

            /* 记录日志 */
            admin_log('', 'batch_remove', 'room');
        }
    }

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

    if ($_POST['type'] == 'drop' || $_POST['type'] == 'restore')
    {
        $link[] = array('href' => 'room.php?act=trash', 'text' => $_LANG['11_room_trash']);
    }
    else
    {
        $link[] = list_link(true, $code);
    }
    sys_msg($_LANG['batch_handle_ok'], 0, $link);
}

/*------------------------------------------------------ */
//-- 显示图片
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'show_image')
{

//    $img_url = $_GET['img_url'];
    $img_url = '../' . $_GET['img_url'];
    $smarty->assign('img_url', $img_url);
    $smarty->display('show_image.htm');
}

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

    $room_id   = intval($_POST['id']);
    $room_name = json_str_iconv(trim($_POST['val']));

    if ($exc->edit("room_name = '$room_name', last_update=" .gmtime(), $room_id))
    {
        clear_cache_files();
        make_json_result(stripslashes($room_name));
    }
}

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

    $room_id = intval($_POST['id']);
    $room_sn = json_str_iconv(trim($_POST['val']));

    /* 检查是否重复 */
    if (!$exc->is_only('room_sn', $room_sn, $room_id))
    {
        make_json_error($_LANG['room_sn_exists']);
    }
    if ($exc->edit("room_sn = '$room_sn', last_update=" .gmtime(), $room_id))
    {
        clear_cache_files();
        make_json_result(stripslashes($room_sn));
    }
}

elseif ($_REQUEST['act'] == 'check_room_sn')
{
    check_authz_json('room_manage');

    $room_id = intval($_REQUEST['room_id']);
    $room_sn = htmlspecialchars(json_str_iconv(trim($_REQUEST['room_sn'])));

    /* 检查是否重复 */
    if (!$exc->is_only('room_sn', $room_sn, $room_id))
    {
        make_json_error($_LANG['room_sn_exists']);
    }
    make_json_result('');
}
elseif ($_REQUEST['act'] == 'check_products_room_sn')
{
    check_authz_json('room_manage');

    $room_id = intval($_REQUEST['room_id']);
    $room_sn = json_str_iconv(trim($_REQUEST['room_sn']));
    $products_sn=explode('||',$room_sn);
    if(!is_array($products_sn))
    {
        make_json_result('');
    }
    else
    {
        foreach ($products_sn as $val)
        {
            if(empty($val))
            {
                 continue;
            }
            if(is_array($int_arry))
            {
                if(in_array($val,$int_arry))
                {
                     make_json_error($val.$_LANG['room_sn_exists']);
                }
            }
            $int_arry[]=$val;
            if (!$exc->is_only('room_sn', $val, '0'))
            {
                make_json_error($val.$_LANG['room_sn_exists']);
            }
        }
    }
    /* 检查是否重复 */
    make_json_result('');
}

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

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

    if ($exc->edit("enable = '$val'", $id))
    {
        clear_cache_files();
        make_json_result($val);
    }
}

/*------------------------------------------------------ */
//-- 修改商品排序
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_sort_order')
{
    // check_authz_json('room_manage');
    $room_id       = intval($_POST['id']);
    $sort_order     = intval($_POST['val']);

    if ($exc->edit("sort_order = '$sort_order', ustamp=" .time(), $room_id))
    {
        clear_cache_files();
        make_json_result($sort_order);
    }
}



/*------------------------------------------------------ */
//-- 删除
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    // 检查权限
//    check_authz_json('remove');

    // 取得参数
    $id = intval($_REQUEST['id']);
    if ($id <= 0)
    {
        make_json_error('invalid params');
    }

    /* 取得商品信息 */
    $sql = "SELECT * " .
            "FROM " . $ecs->table('hs_room') .
            " WHERE id = '$id'";
    $room = $db->getRow($sql);

    if (empty($room))
    {
        make_json_error($_LANG['room_not_exist']);
    }

    /* 删除商品图片和轮播图片 */
    if (!empty($room['image1']))
    {
        @unlink('../' . $room['image1']);
    }

    /* 删除商品 */
    $exc->drop($id);


    /* 记录日志 */
//    admin_log(addslashes($room['name']), 'remove', 'room');

    /* 删除商品相册 */
    $sql = "SELECT img_url, thumb_url, img_original " .
            "FROM " . $ecs->table('rm_gallery') .
            " WHERE rm_id = '$id'";
    $res = $db->query($sql);
    while ($row = $db->fetchRow($res))
    {
        if (!empty($row['img_url']))
        {
            @unlink('../' . $row['img_url']);
        }
        if (!empty($row['thumb_url']))
        {
            @unlink('../' . $row['thumb_url']);
        }
        if (!empty($row['img_original']))
        {
            @unlink('../' . $row['img_original']);
        }
    }

    $sql = "DELETE FROM " . $ecs->table('rm_gallery') . " WHERE rm_id = '$id'";
    $db->query($sql);

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

    ecs_header("Location: $url\n");

    exit;
}

/*------------------------------------------------------ */
//-- 切换商品类型
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'get_attr')
{
    check_authz_json('room_manage');

    $room_id   = empty($_GET['room_id']) ? 0 : intval($_GET['room_id']);
    $room_type = empty($_GET['room_type']) ? 0 : intval($_GET['room_type']);

    $content    = build_attr_html($room_type, $room_id);

    make_json_result($content);
}

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

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

    /* 删除图片文件 */
    $sql = "SELECT img_url, thumb_url, img_original " .
            " FROM " . $GLOBALS['ecs']->table('rm_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('rm_gallery') . " WHERE img_id = '$img_id' LIMIT 1";
    $GLOBALS['db']->query($sql);

    clear_cache_files();
    make_json_result($img_id);
}

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

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

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

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

    make_json_result($opt);
}

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

    check_authz_json('room_manage');

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

    foreach ($linked_array AS $val)
    {
        if ($is_double)
        {
            /* 双向关联 */
            $sql = "INSERT INTO " . $ecs->table('link_room') . " (room_id, link_room_id, is_double, admin_id) " .
                    "VALUES ('$val', '$room_id', '$is_double', '$_SESSION[admin_id]')";
            $db->query($sql, 'SILENT');
        }

        $sql = "INSERT INTO " . $ecs->table('link_room') . " (room_id, link_room_id, is_double, admin_id) " .
                "VALUES ('$room_id', '$val', '$is_double', '$_SESSION[admin_id]')";
        $db->query($sql, 'SILENT');
    }

    $linked_room   = get_linked_room($room_id);
    $options        = array();

    foreach ($linked_room AS $val)
    {
        $options[] = array('value'  => $val['room_id'],
                        'text'      => $val['room_name'],
                        'data'      => '');
    }

    clear_cache_files();
    make_json_result($options);
}

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

    check_authz_json('room_manage');

    $drop_room     = $json->decode($_GET['drop_ids']);
    $drop_room_ids = db_create_in($drop_room);
    $linked_room   = $json->decode($_GET['JSON']);
    $room_id       = $linked_room[0];
    $is_signle      = $linked_room[1];

    if (!$is_signle)
    {
        $sql = "DELETE FROM " .$ecs->table('link_room') .
                " WHERE link_room_id = '$room_id' AND room_id " . $drop_room_ids;
    }
    else
    {
        $sql = "UPDATE " .$ecs->table('link_room') . " SET is_double = 0 ".
                " WHERE link_room_id = '$room_id' AND room_id " . $drop_room_ids;
    }
    if ($room_id == 0)
    {
        $sql .= " AND admin_id = '$_SESSION[admin_id]'";
    }
    $db->query($sql);

    $sql = "DELETE FROM " .$ecs->table('link_room') .
            " WHERE room_id = '$room_id' AND link_room_id " . $drop_room_ids;
    if ($room_id == 0)
    {
        $sql .= " AND admin_id = '$_SESSION[admin_id]'";
    }
    $db->query($sql);

    $linked_room = get_linked_room($room_id);
    $options      = array();

    foreach ($linked_room AS $val)
    {
        $options[] = array(
                        'value' => $val['room_id'],
                        'text'  => $val['room_name'],
                        'data'  => '');
    }

    clear_cache_files();
    make_json_result($options);
}

/*------------------------------------------------------ */
//-- 增加一个配件
/*------------------------------------------------------ */

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

    check_authz_json('room_manage');

    $fittings   = $json->decode($_GET['add_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $room_id   = $arguments[0];
    $price      = $arguments[1];

    foreach ($fittings AS $val)
    {
        $sql = "INSERT INTO " . $ecs->table('group_room') . " (parent_id, room_id, room_price, admin_id) " .
                "VALUES ('$room_id', '$val', '$price', '$_SESSION[admin_id]')";
        $db->query($sql, 'SILENT');
    }

    $arr = get_group_room($room_id);
    $opt = array();

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

    clear_cache_files();
    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 删除一个配件
/*------------------------------------------------------ */

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

    check_authz_json('room_manage');

    $fittings   = $json->decode($_GET['drop_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $room_id   = $arguments[0];
    $price      = $arguments[1];

    $sql = "DELETE FROM " .$ecs->table('group_room') .
            " WHERE parent_id='$room_id' AND " .db_create_in($fittings, 'room_id');
    if ($room_id == 0)
    {
        $sql .= " AND admin_id = '$_SESSION[admin_id]'";
    }
    $db->query($sql);

    $arr = get_group_room($room_id);
    $opt = array();

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

    clear_cache_files();
    make_json_result($opt);
}

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

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

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

    $where = " WHERE cat_id > 0 ";
    if (!empty($filters['title']))
    {
        $keyword  = trim($filters['title']);
        $where   .=  " AND title LIKE '%" . mysql_like_quote($keyword) . "%' ";
    }

    $sql        = 'SELECT article_id, title FROM ' .$ecs->table('article'). $where.
                  '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_room_article')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    check_authz_json('room_manage');

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

    foreach ($articles AS $val)
    {
        $sql = "INSERT INTO " . $ecs->table('room_article') . " (room_id, article_id, admin_id) " .
                "VALUES ('$room_id', '$val', '$_SESSION[admin_id]')";
        $db->query($sql);
    }

    $arr = get_room_articles($room_id);
    $opt = array();

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

    clear_cache_files();
    make_json_result($opt);
}

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

    check_authz_json('room_manage');

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

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

    $arr = get_room_articles($room_id);
    $opt = array();

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

    clear_cache_files();
    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 货品列表
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'product_list')
{
    admin_priv('room_manage');

    /* 是否存在商品id */
    if (empty($_GET['room_id']))
    {
        $link[] = array('href' => 'room.php?act=list', 'text' => $_LANG['cannot_found_room']);
        sys_msg($_LANG['cannot_found_room'], 1, $link);
    }
    else
    {
        $room_id = intval($_GET['room_id']);
    }

    /* 取出商品信息 */
    $sql = "SELECT room_sn, room_name, room_type, shop_price FROM " . $ecs->table('room') . " WHERE room_id = '$room_id'";
    $room = $db->getRow($sql);
    if (empty($room))
    {
        $link[] = array('href' => 'room.php?act=list', 'text' => $_LANG['01_room_list']);
        sys_msg($_LANG['cannot_found_room'], 1, $link);
    }
    $smarty->assign('sn', sprintf($_LANG['good_room_sn'], $room['room_sn']));
    $smarty->assign('price', sprintf($_LANG['good_shop_price'], $room['shop_price']));
    $smarty->assign('room_name', sprintf($_LANG['products_title'], $room['room_name']));
    $smarty->assign('room_sn', sprintf($_LANG['products_title_2'], $room['room_sn']));


    /* 获取商品规格列表 */
    $attribute = get_room_specifications_list($room_id);
    if (empty($attribute))
    {
        $link[] = array('href' => 'room.php?act=edit&room_id=' . $room_id, 'text' => $_LANG['edit_room']);
        sys_msg($_LANG['not_exist_room_attr'], 1, $link);
    }
    foreach ($attribute as $attribute_value)
    {
        //转换成数组
        $_attribute[$attribute_value['attr_id']]['attr_values'][] = $attribute_value['attr_value'];
        $_attribute[$attribute_value['attr_id']]['attr_id'] = $attribute_value['attr_id'];
        $_attribute[$attribute_value['attr_id']]['attr_name'] = $attribute_value['attr_name'];
    }
    $attribute_count = count($_attribute);

    $smarty->assign('attribute_count',          $attribute_count);
    $smarty->assign('attribute_count_3',        ($attribute_count + 3));
    $smarty->assign('attribute',                $_attribute);
    $smarty->assign('product_sn',               $room['room_sn'] . '_');
    $smarty->assign('product_number',           $_CFG['default_storage']);

    /* 取商品的货品 */
    $product = product_list($room_id, '');

    $smarty->assign('ur_here',      $_LANG['18_product_list']);
    $smarty->assign('action_link',  array('href' => 'room.php?act=list', 'text' => $_LANG['01_room_list']));
    $smarty->assign('product_list', $product['product']);
    $smarty->assign('product_null', empty($product['product']) ? 0 : 1);
    $smarty->assign('use_storage',  empty($_CFG['use_storage']) ? 0 : 1);
    $smarty->assign('room_id',     $room_id);
    $smarty->assign('filter',       $product['filter']);
    $smarty->assign('full_page',    1);

    /* 显示商品列表页面 */
    assign_query_info();

    $smarty->display('product_info.htm');
}

/*------------------------------------------------------ */
//-- 货品排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'product_query')
{
    /* 是否存在商品id */
    if (empty($_REQUEST['room_id']))
    {
        make_json_error($_LANG['sys']['wrong'] . $_LANG['cannot_found_room']);
    }
    else
    {
        $room_id = intval($_REQUEST['room_id']);
    }

    /* 取出商品信息 */
    $sql = "SELECT room_sn, room_name, room_type, shop_price FROM " . $ecs->table('room') . " WHERE room_id = '$room_id'";
    $room = $db->getRow($sql);
    if (empty($room))
    {
        make_json_error($_LANG['sys']['wrong'] . $_LANG['cannot_found_room']);
    }
    $smarty->assign('sn', sprintf($_LANG['good_room_sn'], $room['room_sn']));
    $smarty->assign('price', sprintf($_LANG['good_shop_price'], $room['shop_price']));
    $smarty->assign('room_name', sprintf($_LANG['products_title'], $room['room_name']));
    $smarty->assign('room_sn', sprintf($_LANG['products_title_2'], $room['room_sn']));


    /* 获取商品规格列表 */
    $attribute = get_room_specifications_list($room_id);
    if (empty($attribute))
    {
        make_json_error($_LANG['sys']['wrong'] . $_LANG['cannot_found_room']);
    }
    foreach ($attribute as $attribute_value)
    {
        //转换成数组
        $_attribute[$attribute_value['attr_id']]['attr_values'][] = $attribute_value['attr_value'];
        $_attribute[$attribute_value['attr_id']]['attr_id'] = $attribute_value['attr_id'];
        $_attribute[$attribute_value['attr_id']]['attr_name'] = $attribute_value['attr_name'];
    }
    $attribute_count = count($_attribute);

    $smarty->assign('attribute_count',          $attribute_count);
    $smarty->assign('attribute',                $_attribute);
    $smarty->assign('attribute_count_3',        ($attribute_count + 3));
    $smarty->assign('product_sn',               $room['room_sn'] . '_');
    $smarty->assign('product_number',           $_CFG['default_storage']);

    /* 取商品的货品 */
    $product = product_list($room_id, '');

    $smarty->assign('ur_here', $_LANG['18_product_list']);
    $smarty->assign('action_link', array('href' => 'room.php?act=list', 'text' => $_LANG['01_room_list']));
    $smarty->assign('product_list',  $product['product']);
    $smarty->assign('use_storage',  empty($_CFG['use_storage']) ? 0 : 1);
    $smarty->assign('room_id',    $room_id);
    $smarty->assign('filter',       $product['filter']);

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

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

/*------------------------------------------------------ */
//-- 货品删除
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'product_remove')
{
    /* 检查权限 */
    check_authz_json('remove_back');

    /* 是否存在商品id */
    if (empty($_REQUEST['id']))
    {
        make_json_error($_LANG['product_id_null']);
    }
    else
    {
        $product_id = intval($_REQUEST['id']);
    }

    /* 货品库存 */
    $product = get_product_info($product_id, 'product_number, room_id');

    /* 删除货品 */
    $sql = "DELETE FROM " . $ecs->table('products') . " WHERE product_id = '$product_id'";
    $result = $db->query($sql);
    if ($result)
    {
        /* 修改商品库存 */
        if (update_room_stock($product['room_id'], $product_number - $product['product_number']))
        {
            //记录日志
            admin_log('', 'update', 'room');
        }

        //记录日志
        admin_log('', 'trash', 'products');

        $url = 'room.php?act=product_query&' . str_replace('act=product_remove', '', $_SERVER['QUERY_STRING']);

        ecs_header("Location: $url\n");
        exit;
    }
}

/*------------------------------------------------------ */
//-- 修改货品价格
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_product_sn')
{
    check_authz_json('room_manage');

    $product_id       = intval($_POST['id']);
    $product_sn       = json_str_iconv(trim($_POST['val']));
    $product_sn       = ($_LANG['n_a'] == $product_sn) ? '' : $product_sn;

    if (check_product_sn_exist($product_sn, $product_id))
    {
        make_json_error($_LANG['sys']['wrong'] . $_LANG['exist_same_product_sn']);
    }

    /* 修改 */
    $sql = "UPDATE " . $ecs->table('products') . " SET product_sn = '$product_sn' WHERE product_id = '$product_id'";
    $result = $db->query($sql);
    if ($result)
    {
        clear_cache_files();
        make_json_result($product_sn);
    }
}

/*------------------------------------------------------ */
//-- 修改货品库存
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_product_number')
{
    check_authz_json('room_manage');

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

    /* 货品库存 */
    $product = get_product_info($product_id, 'product_number, room_id');

    /* 修改货品库存 */
    $sql = "UPDATE " . $ecs->table('products') . " SET product_number = '$product_number' WHERE product_id = '$product_id'";
    $result = $db->query($sql);
    if ($result)
    {
        /* 修改商品库存 */
        if (update_room_stock($product['room_id'], $product_number - $product['product_number']))
        {
            clear_cache_files();
            make_json_result($product_number);
        }
    }
}

/*------------------------------------------------------ */
//-- 货品添加 执行
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'product_add_execute')
{
    admin_priv('room_manage');

    $product['room_id']        = intval($_POST['room_id']);
    $product['attr']            = $_POST['attr'];
    $product['product_sn']      = $_POST['product_sn'];
    $product['product_number']  = $_POST['product_number'];

    /* 是否存在商品id */
    if (empty($product['room_id']))
    {
        sys_msg($_LANG['sys']['wrong'] . $_LANG['cannot_found_room'], 1, array(), false);
    }

    /* 判断是否为初次添加 */
    $insert = true;
    if (product_number_count($product['room_id']) > 0)
    {
        $insert = false;
    }

    /* 取出商品信息 */
    $sql = "SELECT room_sn, room_name, room_type, shop_price FROM " . $ecs->table('room') . " WHERE room_id = '" . $product['room_id'] . "'";
    $room = $db->getRow($sql);
    if (empty($room))
    {
        sys_msg($_LANG['sys']['wrong'] . $_LANG['cannot_found_room'], 1, array(), false);
    }

    /*  */
    foreach($product['product_sn'] as $key => $value)
    {
        //过滤
        $product['product_number'][$key] = empty($product['product_number'][$key]) ? (empty($_CFG['use_storage']) ? 0 : $_CFG['default_storage']) : trim($product['product_number'][$key]); //库存

        //获取规格在商品属性表中的id
        foreach($product['attr'] as $attr_key => $attr_value)
        {
            /* 检测：如果当前所添加的货品规格存在空值或0 */
            if (empty($attr_value[$key]))
            {
                continue 2;
            }

            $is_spec_list[$attr_key] = 'true';

            $value_price_list[$attr_key] = $attr_value[$key] . chr(9) . ''; //$key，当前

            $id_list[$attr_key] = $attr_key;
        }
        $room_attr_id = handle_room_attr($product['room_id'], $id_list, $is_spec_list, $value_price_list);

        /* 是否为重复规格的货品 */
        $room_attr = sort_room_attr_id_array($room_attr_id);
        $room_attr = implode('|', $room_attr['sort']);
        if (check_room_attr_exist($room_attr, $product['room_id']))
        {
            continue;
            //sys_msg($_LANG['sys']['wrong'] . $_LANG['exist_same_room_attr'], 1, array(), false);
        }
        //货品号不为空
        if (!empty($value))
        {
            /* 检测：货品货号是否在商品表和货品表中重复 */
            if (check_room_sn_exist($value))
            {
                continue;
                //sys_msg($_LANG['sys']['wrong'] . $_LANG['exist_same_room_sn'], 1, array(), false);
            }
            if (check_product_sn_exist($value))
            {
                continue;
                //sys_msg($_LANG['sys']['wrong'] . $_LANG['exist_same_product_sn'], 1, array(), false);
            }
        }

        /* 插入货品表 */
        $sql = "INSERT INTO " . $GLOBALS['ecs']->table('products') . " (room_id, room_attr, product_sn, product_number)  VALUES ('" . $product['room_id'] . "', '$room_attr', '$value', '" . $product['product_number'][$key] . "')";
        if (!$GLOBALS['db']->query($sql))
        {
            continue;
            //sys_msg($_LANG['sys']['wrong'] . $_LANG['cannot_add_products'], 1, array(), false);
        }

        //货品号为空 自动补货品号
        if (empty($value))
        {
            $sql = "UPDATE " . $GLOBALS['ecs']->table('products') . "
                    SET product_sn = '" . $room['room_sn'] . "g_p" . $GLOBALS['db']->insert_id() . "'
                    WHERE product_id = '" . $GLOBALS['db']->insert_id() . "'";
            $GLOBALS['db']->query($sql);
        }

        /* 修改商品表库存 */
        $product_count = product_number_count($product['room_id']);
        if (update_room($product['room_id'], 'room_number', $product_count))
        {
            //记录日志
            admin_log($product['room_id'], 'update', 'room');
        }
    }

    clear_cache_files();

    /* 返回 */
    if ($insert)
    {
         $link[] = array('href' => 'room.php?act=add', 'text' => $_LANG['02_room_add']);
         $link[] = array('href' => 'room.php?act=list', 'text' => $_LANG['01_room_list']);
         $link[] = array('href' => 'room.php?act=product_list&room_id=' . $product['room_id'], 'text' => $_LANG['18_product_list']);
    }
    else
    {
         $link[] = array('href' => 'room.php?act=list&uselastfilter=1', 'text' => $_LANG['01_room_list']);
         $link[] = array('href' => 'room.php?act=edit&room_id=' . $product['room_id'], 'text' => $_LANG['edit_room']);
         $link[] = array('href' => 'room.php?act=product_list&room_id=' . $product['room_id'], 'text' => $_LANG['18_product_list']);
    }
    sys_msg($_LANG['save_products'], 0, $link);
}

/*------------------------------------------------------ */
//-- 货品批量操作
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'batch_product')
{
    /* 定义返回 */
    $link[] = array('href' => 'room.php?act=product_list&room_id=' . $_POST['room_id'], 'text' => $_LANG['item_list']);

    /* 批量操作 - 批量删除 */
    if ($_POST['type'] == 'drop')
    {
        //检查权限
        admin_priv('remove_back');

        //取得要操作的商品编号
        $product_id = !empty($_POST['checkboxes']) ? join(',', $_POST['checkboxes']) : 0;
        $product_bound = db_create_in($product_id);

        //取出货品库存总数
        $sum = 0;
        $room_id = 0;
        $sql = "SELECT product_id, room_id, product_number FROM  " . $GLOBALS['ecs']->table('products') . " WHERE product_id $product_bound";
        $product_array = $GLOBALS['db']->getAll($sql);
        if (!empty($product_array))
        {
            foreach ($product_array as $value)
            {
                $sum += $value['product_number'];
            }
            $room_id = $product_array[0]['room_id'];

            /* 删除货品 */
            $sql = "DELETE FROM " . $ecs->table('products') . " WHERE product_id $product_bound";
            if ($db->query($sql))
            {
                //记录日志
                admin_log('', 'delete', 'products');
            }

            /* 修改商品库存 */
            if (update_room_stock($room_id, -$sum))
            {
                //记录日志
                admin_log('', 'update', 'room');
            }

            /* 返回 */
            sys_msg($_LANG['product_batch_del_success'], 0, $link);
        }
        else
        {
            /* 错误 */
            sys_msg($_LANG['cannot_found_products'], 1, $link);
        }
    }

    /* 返回 */
    sys_msg($_LANG['no_operation'], 1, $link);
}
/*------------------------------------------------------ */
//-- 修改商品虚拟数量
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_virtual_sales')
{
    check_authz_json('room_manage');
    $room_id   = intval($_POST['id']);
    $virtual_sales  = intval($_POST['val']);
    if($virtual_sales < 0 || $virtual_sales == 0 && $_POST['val'] != "$virtual_sales")
    {
        make_json_error($_LANG['virtual_sales_error']);
    }
    if(check_room_product_exist($room_id) == 1)
    {
        make_json_error($_LANG['sys']['wrong'] . $_LANG['cannot_room_number']);
    }
    if ($exc->edit("virtual_sales = '$virtual_sales', last_update=" .gmtime(), $room_id))
    {
        clear_cache_files();
        make_json_result($virtual_sales);
    }
}

/**
 * 列表链接
 * @param   bool    $is_add         是否添加（插入）
 * @param   string  $extension_code 虚拟商品扩展代码，实体商品为空
 * @return  array('href' => $href, 'text' => $text)
 */
function list_link($is_add = true)
{
    $href = 'room.php?act=list';
    if (!$is_add)
    {
        $href .= '&' . list_link_postfix();
    }

    $text = '房間清單';

    return array('href' => $href, 'text' => $text);
}

/**
 * 添加链接
 * @param   string  $extension_code 虚拟商品扩展代码，实体商品为空
 * @return  array('href' => $href, 'text' => $text)
 */
function add_link()
{
    $href = 'room.php?act=add';

    $text = '繼續新增';

    return array('href' => $href, 'text' => $text);
}

/**
 * 检查图片网址是否合法
 *
 * @param string $url 网址
 *
 * @return boolean
 */
function room_parse_url($url)
{
    $parse_url = @parse_url($url);
    return (!empty($parse_url['scheme']) && !empty($parse_url['host']));
}

function room_list($id)
{
    /* 过滤条件 */
    $result = get_filter();

    if ($result === false)
    {
        $filter['keyword']          = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        $filter['sort_by']          = empty($_REQUEST['sort_by']) ? 'sort_order' : trim($_REQUEST['sort_by']);
        $filter['sort_order']       = empty($_REQUEST['sort_order']) ? 'ASC' : trim($_REQUEST['sort_order']);

        /* 关键字 */
        if (!empty($filter['keyword']))
        {
//            $where .= " AND (goods_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%')";
        }

        /* 记录总数 */
        $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('hs_room'). " AS g WHERE hs_id=" .$id. $where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        /* 分页大小 */
        $filter = page_and_size($filter);

        $sql = "SELECT * " .
                    " FROM " . $GLOBALS['ecs']->table('hs_room') . " AS g WHERE hs_id=".$id .$where .
                    " ORDER BY $filter[sort_by] $filter[sort_order] ".
                    " LIMIT " . $filter['start'] . ",$filter[page_size]";

        $filter['keyword'] = stripslashes($filter['keyword']);
        set_filter($filter, $sql, $param_str);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }

    $row = $GLOBALS['db']->getAll($sql);

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

function handle_gallery_image($id, $image_files, $image_descs)
{
    /* 是否处理缩略图 */
    $proc_thumb =  true;
    foreach ($image_descs AS $key => $img_desc)
    {
        /* 是否成功上传 */
        $flag = false;
        if (isset($image_files['error']))
        {
            if ($image_files['error'][$key] == 0)
            {
                $flag = true;
            }
        }
        else
        {
            if ($image_files['tmp_name'][$key] != 'none')
            {
                $flag = true;
            }
        }

        if ($flag)
        {
            // 生成缩略图
            if ($proc_thumb)
            {
                $thumb_url = $GLOBALS['image']->make_thumb($image_files['tmp_name'][$key], $GLOBALS['_CFG']['thumb_width'],  $GLOBALS['_CFG']['thumb_height']);
                $thumb_url = is_string($thumb_url) ? $thumb_url : '';
            }

            $upload = array(
                'name' => $image_files['name'][$key],
                'type' => $image_files['type'][$key],
                'tmp_name' => $image_files['tmp_name'][$key],
                'size' => $image_files['size'][$key],
            );
            if (isset($image_files['error']))
            {
                $upload['error'] = $image_files['error'][$key];
            }
            $img_original = $GLOBALS['image']->upload_image($upload);
            if ($img_original === false)
            {
                sys_msg($GLOBALS['image']->error_msg(), 1, array(), false);
            }
            $img_url = $img_original;

            if (!$proc_thumb)
            {
                $thumb_url = $img_original;
            }
            // 如果服务器支持GD 则添加水印
            if ($proc_thumb && gd_version() > 0)
            {
                $pos        = strpos(basename($img_original), '.');
                $newname    = dirname($img_original) . '/' . $GLOBALS['image']->random_filename() . substr(basename($img_original), $pos);
                copy('../' . $img_original, '../' . $newname);
                $img_url    = $newname;

                $GLOBALS['image']->add_watermark('../'.$img_url,'',$GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']);
            }

            /* 重新格式化图片名称 */
            $img_original = reformat_image_name('rooms', $id, $img_original, 'source');
            $img_url = reformat_image_name('rooms', $id, $img_url, 'goods');
            $thumb_url = reformat_image_name('rooms_thumb', $id, $thumb_url, 'thumb');
            $sql = "INSERT INTO " . $GLOBALS['ecs']->table('rm_gallery') . " (rm_id, img_url, img_desc, thumb_url, img_original) " .
                    "VALUES ('$id', '$img_url', '$img_desc', '$thumb_url', '$img_original')";
            $GLOBALS['db']->query($sql);
            /* 不保留商品原图的时候删除原图 */
            if ($proc_thumb && !$GLOBALS['_CFG']['retain_original_img'] && !empty($img_original))
            {
                $GLOBALS['db']->query("UPDATE " . $GLOBALS['ecs']->table('rm_gallery') . " SET img_original='' WHERE `rm_id`='{$id}'");
                @unlink('../' . $img_original);
            }
        }
    }
}

/**
 * 格式化商品图片名称（按目录存储）
 *
 */
function reformat_image_name($type, $id, $source_img, $position='')
{
    $rand_name = gmtime() . sprintf("%03d", mt_rand(1,999));
    $img_ext = substr($source_img, strrpos($source_img, '.'));

    $dir = 'images';
    if (defined('IMAGE_DIR'))
    {
        $dir = IMAGE_DIR;
    }
    $sub_dir = date('Ym', gmtime());
    if (!make_dir(ROOT_PATH.$dir.'/'.$sub_dir))
    {
        return false;
    }
    if (!make_dir(ROOT_PATH.$dir.'/'.$sub_dir.'/source_img'))
    {
        return false;
    }
    if (!make_dir(ROOT_PATH.$dir.'/'.$sub_dir.'/rooms_img'))
    {
        return false;
    }
    if (!make_dir(ROOT_PATH.$dir.'/'.$sub_dir.'/thumb_img'))
    {
        return false;
    }
    
    switch($type)
    {
        case 'rooms':
            $img_name = $id . '_G_' . $rand_name;
            break;
        case 'rooms_thumb':
            $img_name = $id . '_thumb_G_' . $rand_name;
            break;
        case 'gallery':
            $img_name = $id . '_P_' . $rand_name;
            break;
        case 'gallery_thumb':
            $img_name = $id . '_thumb_P_' . $rand_name;
            break;
    }
    
    if ($position == 'source')
    {
        if (move_image_file(ROOT_PATH.$source_img, ROOT_PATH.$dir.'/'.$sub_dir.'/source_img/'.$img_name.$img_ext))
        {
            return $dir.'/'.$sub_dir.'/source_img/'.$img_name.$img_ext;
        }
    }
    elseif ($position == 'thumb')
    {
        if (move_image_file(ROOT_PATH.$source_img, ROOT_PATH.$dir.'/'.$sub_dir.'/thumb_img/'.$img_name.$img_ext))
        {
            return $dir.'/'.$sub_dir.'/thumb_img/'.$img_name.$img_ext;
        }
    }
    else
    {
        if (move_image_file(ROOT_PATH.$source_img, ROOT_PATH.$dir.'/'.$sub_dir.'/rooms_img/'.$img_name.$img_ext))
        {
            return $dir.'/'.$sub_dir.'/rooms_img/'.$img_name.$img_ext;
        }
    }
    return false;
}

function move_image_file($source, $dest)
{
    if (@copy($source, $dest))
    {
        @unlink($source);
        return true;
    }
    return false;
}
?>