<?php
/**
 * 聯動選擇管理
 *
 * @version        $Id: stepselect_main.php 1 16:22 2010年7月20日Z tianya $
 * @package        DedeCMS.Administrator
 * @copyright      Copyright (c) 2007 - 2010, DesDev, Inc.
 * @license        http://help.dedecms.com/usersguide/license.html
 * @link           http://www.dedecms.com
 */
require_once(dirname(__FILE__)."/config.php");
CheckPurview('c_Stepselect');
require_once(DEDEINC."/datalistcp.class.php");
require_once(DEDEINC.'/enums.func.php');
/*-----------------
前台視圖
function __show() { }
------------------*/
$ENV_GOBACK_URL = (isset($ENV_GOBACK_URL) ? $ENV_GOBACK_URL : 'stepselect_main.php');
if(empty($action))
{
    setcookie("ENV_GOBACK_URL",$dedeNowurl,time()+3600,"/");
    if(!isset($egroup)) $egroup = '';
    if(!isset($topvalue)) $topvalue = 0;
    $etypes = array();
    $egroups = array();
    $dsql->Execute('me','SELECT * FROM `#@__stepselect` ORDER BY id DESC');
    while($arr = $dsql->GetArray())
    {
        $etypes[] = $arr;
        $egroups[$arr['egroup']] = $arr['itemname'];
    }

    if($egroup!='')
    {
        $orderby = 'ORDER BY disorder ASC, evalue ASC';
        if(!empty($topvalue))
        {
            // 判斷是否為1級聯動
            if ($topvalue % 500 == 0)
            {
                $egroupsql = " WHERE egroup LIKE '$egroup' AND evalue>=$topvalue AND evalue < ".($topvalue + 500);
            } else { 
                $egroupsql = " WHERE (evalue LIKE '$topvalue.%%%' OR evalue=$topvalue) AND egroup LIKE '$egroup'";
            }
        }
        else
        {
            $egroupsql = " WHERE egroup LIKE '$egroup' ";
        }
        $sql = "SELECT * FROM `#@__sys_enum` $egroupsql $orderby";
    } else {
        $egroupsql = '';
        $sql = "SELECT * FROM `#@__stepselect` ORDER BY id DESC";
    }
    $dlist = new DataListCP();
    $dlist->SetParameter('egroup',$egroup);
    $dlist->SetParameter('topvalue',$topvalue);
    $dlist->SetTemplet(DEDEADMIN."/templets/stepselect_main.htm");
    $dlist->SetSource($sql);
    $dlist->display();
    exit();
}
else if($action=='edit' || $action=='addnew' || $action=='addenum' || $action=='view')
{
    AjaxHead();
    include('./templets/stepselect_showajax.htm');
    exit();
}
/*-----------------
刪除類型或枚舉值
function __del() { }
------------------*/
else if($action=='del')
{
    $arr = $dsql->GetOne("SELECT * FROM `#@__stepselect` WHERE id='$id' ");
    if(!is_array($arr))
    {
        ShowMsg("無法獲取分類信息，不允許後續操作！", "stepselect_main.php?".ExecTime());
        exit();
    }
    if($arr['issystem']==1)
    {
        ShowMsg("系統內置的枚舉分類不能刪除！", "stepselect_main.php?".ExecTime());
        exit();
    }
    $dsql->ExecuteNoneQuery("DELETE FROM `#@__stepselect` WHERE id='$id'; ");
    $dsql->ExecuteNoneQuery("DELETE FROM `#@__sys_enum` WHERE egroup='{$arr['egroup']}'; ");
    ShowMsg("成功刪除一個分類！", "stepselect_main.php?".ExecTime());
    exit();
}
else if($action=='delenumAllSel')
{
    if(isset($ids) && is_array($ids))
    {
        $id = join(',', $ids);

        $groups = array();
        $dsql->Execute('me', "SELECT egroup FROM `#@__sys_enum` WHERE id IN($id) GROUP BY egroup");
        while($row = $dsql->GetArray('me'))
        {
            $groups[] = $row['egroup'];
        }

        $dsql->ExecuteNoneQuery("DELETE FROM `#@__sys_enum` WHERE id IN($id); ");

        //更新緩存
        foreach($groups as $egropu) 
        {
            WriteEnumsCache($egroup);
        }

        ShowMsg("成功刪除選中的枚舉分類！", $ENV_GOBACK_URL);
    }
    else
    {
        ShowMsg("你沒選擇任何分類！", "-1");
    }
    exit();
}
else if($action=='delenum')
{
    $row = $dsql->GetOne("SELECT egroup FROM `#@__sys_enum` WHERE id = '$id' ");
    $dsql->ExecuteNoneQuery("DELETE FROM `#@__sys_enum` WHERE id='{$id}'; ");
    WriteEnumsCache($row['egroup']);
    ShowMsg("成功刪除一個枚舉！", $ENV_GOBACK_URL);
    exit();
}
/*-----------------
保存類型修改
function __edit_save() { }
------------------*/
else if($action=='edit_save')
{
    if(preg_match("#[^0-9a-z_-]#i", $egroup))
    {
        ShowMsg("組名稱不能有全角字符或特殊符號！","-1");
        exit();
    }
    $dsql->ExecuteNoneQuery("UPDATE `#@__stepselect` SET `itemname`='$itemname',`egroup`='$egroup' WHERE id='$id'; ");
    ShowMsg("成功修改一個分類！", "stepselect_main.php?".ExecTime());
    exit();
}
/*-----------------
保存新類型
function __addnew_save() { }
------------------*/
else if($action=='addnew_save')
{
    if(preg_match("#[^0-9a-z_-]#i", $egroup))
    {
        ShowMsg("組名稱不能有全角字符或特殊符號！", "-1");
        exit();
    }
    $arr = $dsql->GetOne("SELECT * FROM `#@__stepselect` WHERE itemname LIKE '$itemname' OR egroup LIKE '$egroup' ");
    if(is_array($arr))
    {
        ShowMsg("你指定的類別名稱或組名稱已經存在，不能使用！","stepselect_main.php");
        exit();
    }
    $dsql->ExecuteNoneQuery("INSERT INTO `#@__stepselect`(`itemname`,`egroup`,`issign`,`issystem`) VALUES('$itemname','$egroup','0','0'); ");
    WriteEnumsCache($egroup);
    ShowMsg("成功添加一個分類！","stepselect_main.php?egroup=$egroup");
    exit();
}
/*---------
把舊版全國省市表替換當前地區數據
function __exarea() { }
----------*/
else if($action=='exarea')
{
    $bigtypes = array();
    $dsql->ExecuteNoneQuery("DELETE FROM `#@__sys_enum` WHERE egroup='nativeplace'; ");
    $query = "SELECT * FROM `#@__area` WHERE reid =0 order by id asc";
    $dsql->Execute('me', $query);
    $n = 1;
    while($row = $dsql->GetArray())
    {
        $bigtypes[$row['id']] = $evalue = $disorder = $n * 500;
        $dsql->ExecuteNoneQuery("INSERT INTO `#@__sys_enum`(`ename`,`evalue`,`egroup`,`disorder`,`issign`)
                                 VALUES('{$row['name']}','$evalue','nativeplace','$disorder','0'); ");
        $n++;                                
    }
    $stypes = array();
    foreach($bigtypes as $k=>$v)
    {
        $query = "SELECT * FROM `#@__area` WHERE reid=$k order by id asc";
        $dsql->Execute('me', $query);
        $n = 1;
        while($row = $dsql->GetArray())
        {
            $stypes[$row['id']] = $evalue = $disorder = $v + $n;
            $dsql->ExecuteNoneQuery("INSERT INTO `#@__sys_enum`(`ename`,`evalue`,`egroup`,`disorder`,`issign`)
                                   VALUES('{$row['name']}','$evalue','nativeplace','$disorder','0'); ");
            $n++; 
        }
    }
    WriteEnumsCache('nativeplace');
    ShowMsg("成功導入所有舊的地區數據！", "stepselect_main.php?egroup=nativeplace");
    exit();
}
/*--------------------
function __addenum_save() { }
關於二級枚舉的說明，為了節省查詢速度，二級枚舉是通過特殊算法生成的，原理為
凡是能被 500 整除的都是一級枚舉，(500 * n) + 1 < em < 500 * (n+1) 為下級枚舉
如：1000 的下級枚舉對應的值為 1001,1002,1003...1499
對於 issign=1 的，表示這個類別只有一級枚舉，則不受上面的算法限制
------------------------------------------------------------------------
更新算法:
新增二級枚舉下添加"-N"自己類別選擇,例如:
1001二級枚舉下面的3級類目,則為1001-1,1001-2...
這時候需要issign=2
---------------------*/
else if($action=='addenum_save')
{
    if(empty($ename) || empty($egroup)) 
    {
         Showmsg("類別名稱或組名稱不能為空！","-1");
         exit();
    }
    if($issign == 1 || $topvalue == 0)
    {
        $enames = explode(',', $ename);
        foreach($enames as $ename)
        {
            $arr = $dsql->GetOne("SELECT * FROM `#@__sys_enum` WHERE egroup='$egroup' AND (evalue MOD 500)=0 ORDER BY disorder DESC ");
            if(!is_array($arr)) $disorder = $evalue = ($issign==1 ? 1 : 500);
            else $disorder = $evalue = $arr['disorder'] + ($issign==1 ? 1 : 500);
                
            $dsql->ExecuteNoneQuery("INSERT INTO `#@__sys_enum`(`ename`,`evalue`,`egroup`,`disorder`,`issign`) 
                                    VALUES('$ename','$evalue','$egroup','$disorder','$issign'); "); 
        }
        WriteEnumsCache($egroup);                                                          
        ShowMsg("成功添加枚舉分類！".$dsql->GetError(), $ENV_GOBACK_URL);
        exit();
    } else if ($issign == 2 && $topvalue != 0)
    {
        $minid = $topvalue;
        $maxnum = 500; // 三級子類最多500個
        $enames = explode(',', $ename);
        foreach ($enames as $ename)
        {
            $arr = $dsql->GetOne("SELECT * FROM `#@__sys_enum` WHERE egroup='$egroup' AND evalue LIKE '$topvalue.%%%' ORDER BY evalue DESC ");
            if(!is_array($arr))
            {
                $disorder = $minid;
                $evalue = $minid.'.1';
            }
            else
            {
                $disorder = $minid;
                preg_match("#([0-9]{1,})\.([0-9]{1,})#", $arr['evalue'], $matchs);
                $addvalue = $matchs[2] + 1;
                $addvalue = sprintf("%03d", $addvalue);
                $evalue = $matchs[1].'.'.$addvalue;
            }
            $sql = "INSERT INTO `#@__sys_enum`(`ename`,`evalue`,`egroup`,`disorder`,`issign`) 
                                    VALUES('$ename','$evalue','$egroup','$disorder','$issign'); ";
            // echo $sql;exit;
            $dsql->ExecuteNoneQuery($sql); 
        }
        // echo $minid;
        WriteEnumsCache($egroup);
        ShowMsg("成功添加枚舉分類！", $ENV_GOBACK_URL);
        exit();
    } else {
        $minid = $topvalue;
        $maxid = $topvalue + 500;
        $enames = explode(',', $ename);
        foreach($enames as $ename)
        {
            $arr = $dsql->GetOne("SELECT * FROM `#@__sys_enum` WHERE egroup='$egroup' AND evalue>$minid AND evalue<$maxid ORDER BY evalue DESC ");
            if(!is_array($arr))
            {
                $disorder = $evalue = $minid+1;
            }
            else
            {
                $disorder = $arr['disorder']+1;
                $evalue = $arr['evalue']+1;
            }
            $dsql->ExecuteNoneQuery("INSERT INTO `#@__sys_enum`(`ename`,`evalue`,`egroup`,`disorder`,`issign`) 
                          VALUES('$ename','$evalue','$egroup','$disorder','$issign'); ");
        }
        WriteEnumsCache($egroup);
        ShowMsg("成功添加枚舉分類！", $ENV_GOBACK_URL);
        exit();
    }
}
/*-----------------
修改枚舉名稱和排序
function __upenum() { }
------------------*/
else if($action=='upenum')
{
    $ename = trim(str_replace(' └─','',$ename));
    $row = $dsql->GetOne("SELECT egroup FROM `#@__sys_enum` WHERE id = '$aid' ");
    WriteEnumsCache($row['egroup']);
    $dsql->ExecuteNoneQuery("UPDATE `#@__sys_enum` SET `ename`='$ename',`disorder`='$disorder' WHERE id='$aid'; ");
    ShowMsg("成功修改一個枚舉！", $ENV_GOBACK_URL);
    exit();
}
/*-----------------
更新枚舉緩存
function __upallcache() { }
------------------*/
else if($action=='upallcache')
{
    if(!isset($egroup)) $egroup = '';
    WriteEnumsCache($egroup);
    ShowMsg("成更新枚舉緩存！", $ENV_GOBACK_URL);
    exit();
}