<?php
/**
* @author moufer<moufer@163.com>
* @copyright www.modoer.com
*/
class ClassModle {

    var $db = null;
    var $tablename = 'classcode';

    function ClassModle() {
        global $db, $dbpre;
        $this->db =& $db;
        $this->tablename = $dbpre.$this->tablename;
    }

    function cacheClass() {
        global $_config;

        $orderby = $_config['classorder'] == 'total' ? 'total DESC' : 'classorder';
        $query = $this->db->query("SELECT cid,classcode,classname,classsort,total FROM {$this->tablename} ORDER BY $orderby");
        $contents = "\$_classcodes = array(\r\n";
        while ($classcode = $this->db->fetch_array($query)) {
            $contents .= "\t'{$classcode['classcode']}' =>\r\n".
                "\tarray ( \r\n".
                    "\t\t'cid' => '".$classcode['cid']."',\r\n".
                    "\t\t'classname' => '".add_cs_lashes($classcode['classname'])."',\r\n".
                "\t),\r\n";
            if($classcode['classsort'] == 1) {
                $panels[] = $classcode;
            } elseif($classcode['classsort'] == 2) {
                $classes[] = $classcode;
            }
        }
        $contents .= ");\r\n\r\n";

        if($classes) {
            foreach($classes as $val) {
                $contents .= "\$_classes['".substr($val['classcode'],0,2)."']['".$val['classcode']."'] = '".$val['classname']."';\r\n";
            }
            $contents .= "\r\n";
        }

        if($panels) foreach($panels as $panel) {
            $contents .= "\$_classcode_option['{$panel['classcode']}'] = \r\n";
            if($classes) foreach($classes as $class) {
                if(substr($class['classcode'], 0, 2) == $panel['classcode']) {
                    $contents .= "\t'<option value=\"{$class['classcode']}\">".add_cs_lashes($class['classname'])."</option>'.\"\\r\\n\".\r\n";
                }
            }
            $contents .= "'';\r\n";
        }
        write_cache('classcode', $contents);
    }

    function cachePanel() {

        $query = $this->db->query("SELECT cid,classname,classcode,config FROM {$this->tablename} WHERE classsort=1 ORDER BY classorder");
        $contents = "\$_panels = array(\r\n";
        $option = "\$_panels_option = \r\n";
        $config = "\$_panel_config = array(\r\n";
        while($panelcode = $this->db->fetch_array($query)) {
            $contents .= "\t'".$panelcode['classcode']."' => '".add_cs_lashes($panelcode['classname'])."',\r\n";
            $uz_config = unserialize($panelcode['config']);
            if($uz_config['suitplaces']) {
                $uz_config['suitplaces'] = html_special_chars(explode("\r\n",$uz_config['suitplaces']));
            }
            $config .= "'{$panelcode['classcode']}' => ".var_export($uz_config, true).",\r\n";
            $option .= "\t'<option value=\"{$panelcode['classcode']}\">".add_cs_lashes($panelcode['classname'])."</option>'.\"\\r\\n\".\r\n";
        }
        $contents .= ");\r\n\n";
        $option .= "'';\r\n\n";
        $config .= ');';
        write_cache('panels', $contents.$option.$config);

    }

    function & getClasscodes($pcd='') {
        $where = "";
        if(empty($pcd)) {
            $where="classsort=1";
        } else {
            $where="classsort=2 AND classcode LIKE '{$pcd}%'";
        }

        $query = $this->db->query("SELECT cid,classname,classcode,classsort,classorder FROM {$this->tablename} WHERE $where ORDER BY classorder");
        $result = array();
        while($row=$this->db->fetch_array($query)) {
            $result[] = $row;
        }
        unset($row);
        return $result;
    }

    function updateListOrder(& $cids) {
        if(!is_array($cids) || count($cids)==0) return false;

        foreach($cids as $cid=>$val) {
            $val = intval($val);
            $this->db->update("UPDATE {$this->tablename} SET classorder='$val' WHERE cid='$cid'");
        }
        unset($cid,$val);
        return true;
    }

    function & getClasscode($classcode) {
        $result = $this->db->get_one("SELECT * FROM {$this->tablename} WHERE classcode='$classcode'");
        return empty($result) ? false : $result;
    }

    function saveSubClasscode(& $post, $classcode='') {
        $data = array();
        $data['classname'] = $post['classname'];
        $data['classorder'] = $post['classorder'];
        $data['classsort'] = 2;
        $data['config'] = '';

        if($classcode) {
            if(substr($classcode,0,2) != $post['panelcode']) {
                // 建立新的分类Code
                $newclasscode = $this->_createNewClasscode($post['panelcode']);
                // 移动了主分类，需要对本子分类下的商铺进行更新Classcode
                if(function_exists('updateItemClass')) {
                    require_once(MOD_ROOT.'./include/fun_item.php');
                }
                updateItemClass($classcode, $newclasscode);
                $data['classcode'] = $newclasscode;
            }
            $this->db->update_new($this->tablename, "classcode='$classcode'", $data);
        } else {
            $data['classcode'] = $this->_createNewClasscode($post['panelcode']);
            $this->db->insert_new($this->tablename, $data);
        }
    }

    function saveClasscode(& $post, $panelcode='') {
        $data = array();
        $data['classname'] = $post['classname'];
        $data['classorder'] = $post['classorder'];
        $data['classsort'] = 1;

        foreach($post['sorts'] as $key => $val) {
            $val = html_special_chars_ex($val);
            if($val) {
                $review[$key] = $val;
            }
        }
        !$review && cpmsg('未填写点评评分项，请返回修改。');
        $post['suitplaces'] = html_special_chars_ex(preg_replace("/\s*(\r\n|\n\r|\n|\r)\s*/", "\r\n", $post['suitplaces']));
        if(count(explode("\r\n",$post['suitplaces'])) > 5) {
            cpmsg("适合场所过多，最多只能填写5个。");
        }
        $post['meta_keywords'] = html_special_chars_ex($post['meta_keywords']);
        $post['meta_description'] = html_special_chars_ex($post['meta_description']);

        $data['config'] = addslashes(serialize(array(
            'review'             => $review,
            'mapmark'            => intval($post['mapmark']),
            'catemap'            => intval($post['catemap']),
            'catemap_time'       => intval($post['catemap_time'])*1000,
            'catemap_level'      => intval($post['catemap_level']),
            'itemapply'          => intval($post['itemapply']),
            'listorder'          => $post['listorder'],
            'tplname_list'       => $post['tplname_list'],
            'tplname_detail'     => $post['tplname_detail'],
            'avgprice_need'      => intval($post['avgprice_need']),
            'suitplace_enable'   => intval($post['suitplace_enable']),
            'suitplaces'         => $post['suitplaces'],
            'scoretype'          => intval($post['scoretype']),
            'decimalpoint'       => intval($post['decimalpoint']),
            'meta_keywords'      => $post['meta_keywords'],
            'meta_description'   => $post['meta_description'],
        )));

        if($panelcode) {
            $this->db->update_new($this->tablename, "classcode='$panelcode'", $data);
            $pcd = $panelcode;
        } else {
            $data['classcode'] = $this->_createNewClasscode('');

            $this->db->insert_new($this->tablename, $data);
            $pcd = $data['classcode'];
        }
        return $pcd;
    }

    function getSubClassCount($panelcode) {
        return $this->db->get_value("SELECT COUNT(*) FROM {$this->tablename} WHERE classcode>'{$panelcode}00' AND classcode<='{$panelcode}99'");
    }

    function deleteClass($classcode) {
        if(empty($classcode)) return;
        $this->db->query("DELETE FROM {$this->tablename} WHERE classcode='$classcode'");
    }

    function _createNewClasscode($panelcode) {
        $classes = array();
        if($panelcode) {
            $query = $this->db->query("SELECT classcode FROM {$this->tablename} WHERE classcode like '{$panelcode}__'");
            $newclasscode = 1;
        } else {
            $query = $this->db->query("SELECT classcode FROM {$this->tablename} WHERE classsort=1");
            $newclasscode = 10;
        }
        while($class = $this->db->fetch_array($query)) $classes[] = $class['classcode'];
        while(in_array($panelcode.sprintf("%02d", $newclasscode), $classes)) $newclasscode++;
        return $panelcode.sprintf("%02d", $newclasscode);
    }

}
?>