<?php

/**
 * 
 *
 * @author sun
 */
class GrowthLevelWayPermission { 
    /**
     * 主数据库
     */
    private $db;

    /**
     * 从数据库
     */
    private $dbback;

    /**
     * 缓存对象
     */
    private $mc;
    
    /**
     * 关联的表名
     * @var string
     */
    private $table;
    
    /**
     * 表中包含字段
     * @var array
     */
    private static $fields = array('id','type', 'name', 'subclass','way_alias','is_display');

    public function __construct() {
        $container = Container::getInstance();
        $this->db = $container->get('db');
        $this->dbback = $container->get('dbback');
        $this->mc = $container->get('mc');
        $this->table = 'growth_level_way_permission';
    }
    
    /**
     * 
     * @param type $arrFields
     * @return type
     */
    public function initData($arrFields) {
        $sql = SqlCombinHelper::insert_sql($this->table, $arrFields);
        return $this->db->execute($sql);
    }
    
    /**
     * 获取根据是否展示状态位获取需要绑定等级的权限
     * @param int $isDisplay 是否显示 默认展示
     * @return array 返回所有需要和绑定等级的权限
     */
    public function findAllByDisplay($isDisplay = 1) {
        $sql = SqlCombinHelper::select_sql($this->table, self::$fields, 
                "is_display = $isDisplay");
        return $this->dbback->getAll($sql);
    }
    
    /**
     * 保存数据
     * @param array $fields 数据结构
     * @return boolean
     */
    public function saveData($fields) {
        $sql = SqlCombinHelper::replace_sql($this->table, $fields);
        return $this->db->execute($sql);
    }
    
    /**
     * 清空
     */
    public function emptyTable() {
        $sql = "TRUNCATE TABLE $this->table";
        $this->db->Execute($sql);
    }
    
    /**
     * 根据别名获取等级的关系
     * @param type $arrWayAlias
     * @param type $type
     */
    public function findLevelByWayAliasAndType($wayAlias, $type = 1) {
        $sql = SqlCombinHelper::innerSelect_sql('growth_level_permission as lp', 
                'growth_level_way_permission as lwp', 'lp.level_id',
                'lp.way_id = lwp.id', 'lwp.type = ' . $type . ' AND lwp.way_alias '
                . "= '$wayAlias' AND lp.status = 1");
        return $this->dbback->getAll($sql);
    }
    
    /**
     * 取得最小要求等级
     * @param type $arrWayAlias
     * @param type $type
     */
    public function findMinLevelByWayAliasAndType($wayAlias, $type = 1) {
        $sql = SqlCombinHelper::innerSelect_sql('growth_level_permission as lp', 
                'growth_level_way_permission as lwp', 'min(lp.level_id)',
                'lp.way_id = lwp.id', 'lwp.type = ' . $type . ' AND lwp.way_alias '
                . "= '$wayAlias' AND lp.status = 1");
        $min = $this->dbback->getOne($sql);
        if($min) { return $min;} else { return 1;}
    }
}
