<?php
/**
 * 房豆操作记录
 *
 * @author sun
 */
class PaymentHousebeanRecord {
    
    /**
     * 主数据库 
     * @var TINY_ADODB 
     */    
    private $db;
    
    /**
     * 从数据库
     * @var type 
     */
    private $dbback;
    
    /**
     * 缓存对象
     * @var type 
     */
    private $mc;

    /**
     * 关联的表名 
     * @var String 
     */
    private $table;
    
    /**
     * 构造函数，初始化db memcache 等。
     * @param string $table 表名，可以使用默认值。
     */
    public function __construct() {
        $container = Container::getInstance();
        $this->db = $container->get('db');
        $this->dbback = $container->get('dbback');
        $this->table = $this->getTableName();
        $this->mc = $container->get('mc');
        $sqlfield = "DESC $this->table";
        $fieldsMKey = $sqlfield;
        $this->fields = $this->mc->get($fieldsMKey);
        if($this->fields === false) {
            $fields = $this->dbback->getAll($sqlfield);
            foreach ($fields as $field) {
                $this->fields[] = $field['Field'];
            }
            $this->mc->set($fieldsMKey, $this->fields, 3600);
        }
    }
    
    /**
     * 查询区间范围
     * @param int $start 开始值
     * @param int $limit 每页显示多少条
     * @return string
     */
    private function getLimitCond($start, $limit) {
        $start = $start > 0 ? $start : 0;
        $limit_cond = ($start == 0 && $limit == 0) ? '' : ' LIMIT '
                      . $start . ' , ' . $limit;
        return $limit_cond;
    }
    
    /**
     * 验证字段是否合法
     * @param type $field
     * @return type
     */
    private function validateFiled($field) {
        return in_array($field, $this->fields);
    }
    
    /**
     * 排序规则
     * @param string $orderField 字段
     * @param string $order 排序规则
     * @return string
     */
    private function getOrder($orderField, $order = 'ASC') {
        $strOrder = '';
        if ($this->validateFiled($orderField)) {
            $strOrder = "ORDER BY $orderField $order";
        }
        return $strOrder;
    }
    
    private function getTableName() {
        $tbl = 'payment_housebean_record';
        return $tbl;
    }
    
    /**
     * 获取类型
     */
    private function getOpertorTypeWhere($opertorType) {
        return $opertorType == 'expend' ? ' num < 0' : ' num > 0';
    }
    
    /**
     * 获得经纪人当前积分的数组。
     * @return array  
     */
    public function getBrokerCredit($brokerId) {
        $credit = new GrowthCredit();
        return $credit->getValidCredit($brokerId);
    }
    
    /**
     * 插入房豆操作记录
     * @param int $brokerId 经纪人编号
     * @param string $transactionId 交易号
     * @param string $wayAlias 别名
     * @param int $source 来源
     * @param int $num 房豆数量
     * @param string $description 操作说明
     * @param int $discard 是否废弃，1废弃，0正常状态
     * @return int
     */
    public function insert($brokerId, $transactionId, $wayAlias, $source, 
            $num, $description, $ishidden, $discard = 0) {
        global $functionSwitch,$housebeanExpirationTimeType;
        $fieldsValue = array();
        $credit = $this->getBrokerCredit($brokerId);
        $fieldsValue['broker_id'] = $brokerId;
        $fieldsValue['transaction_id'] = $transactionId;
        $fieldsValue['way_alias'] = $wayAlias;
        $fieldsValue['source'] = $source;
        $fieldsValue['num'] = $num;
        $fieldsValue['remain_num'] = $credit;
        $fieldsValue['description'] = $description;
        $fieldsValue['ishidden'] = $ishidden;
        $fieldsValue['status'] = 0;
        $fieldsValue['ip'] = GetIp();
        $fieldsValue['discard'] = $discard;
        $fieldsValue['ctime'] = date('Y-m-d H:i:s');
		$fieldsValue['createtime'] = time();


        //优先房豆消耗权限
        //$functionSwitch = config_item('functionSwitch');

        //$housebeanExpirationTimeType = config_item('housebeanExpirationTimeType');
        if($num > 0 && !empty($functionSwitch['priorityHousebeanConsume']) && !empty($housebeanExpirationTimeType) && in_array($wayAlias,array('recharge','AgencyAllo')))
        {

            $endtime = 0;
            if($wayAlias == 'recharge' && !empty($housebeanExpirationTimeType['paymentExpireTime']))
            {
                $endtime = $housebeanExpirationTimeType['paymentExpireTime'];
            }
            elseif(!empty($housebeanExpirationTimeType['otherExpireTime']))
            {
                $endtime = $housebeanExpirationTimeType['otherExpireTime'];
            }

            $fieldsValue['endtime'] = $endtime;
            $fieldsValue['total'] = $num;
        }

        $sql = SqlCombinHelper::insert_sql($this->table, $fieldsValue);

        return $this->db->execute($sql);
    }
    
    /**
     * 获取房豆交易列表
     * @param int $brokerId 经纪人编号
     * @param date $starttime 开始时间
     * @param date $endtime 结束时间
     * @param string $opertorType 操作类型 
     * @param int $source 来源
     * @param string $wayAlias 别名
     * @param int $start 开始
     * @param int $pagesize 每页多少条
     * @param string $order 排序
     * @return array
     */
    public function getListBy($brokerId, $starttime, $endtime, $opertorType = null, 
            $source = null, $wayAlias = null, $start = null, $pagesize = null, 
            $order = null) {
        $where = '';
        $where .= "broker_id = $brokerId AND ctime >= "
                . "'{$starttime}' " . " AND ctime <= '{$endtime}' AND ishidden = 1";
        //获取get 消耗 pay
        if ($opertorType != null) 
		{
            $where .= ' AND' . $this->getOpertorTypeWhere($opertorType);
        }

        //来源 1 PC端 2 APP
        if ($source != null && $source != '0') 
		{
            $where .= ' AND source = ' . $source;
        }

        //操作别名
        if ($wayAlias != null && $wayAlias != '0' ) 
		{
            if (is_array($wayAlias))
            {
                $where .= " AND way_alias in ('".  implode("','", $wayAlias)."')";
            }
            else
            {
                $where .= ' AND way_alias = ' . "'$wayAlias'";
            }
        }

        if($start !== null && $pagesize !== null) 
		{
            $limit = $this->getLimitCond($start, $pagesize);
        } 
		else 
		{
            $limit = '';
        }

		if($order !== null)
		{
		    $order = $this->getOrder('ctime', $order);
        } 
		else 
		{
            $order = $this->getOrder('id', 'desc');
        }

        $where .=  ' ' . $order . ' ' . $limit;
        $sql = SqlCombinHelper::select_sql($this->table, $this->fields, $where);
        return $this->dbback->getAll($sql);
    }


	/**
     * 按操作别名获取最新几个交易记录
     * @param int $brokerId 经纪人编号
     * @param array wayAlias 经纪人编号
     * @param int $limit 个数
     * @return array
     */
    public function getNewByWayAlias($brokerId,$wayAlias = null, $limit = 6) {      
        $where = '';
        $where .= "broker_id = $brokerId and ishidden = 1 ";
          //操作别名
        if ($wayAlias != null && $wayAlias != '0' ) {
            if (is_array($wayAlias))
            {
                $where .= " and way_alias in ('".  implode("','", $wayAlias)."')";
            }
            else
            {
                $where .= ' and way_alias = ' . "'$wayAlias'";
            }
        }
        $limit = $this->getLimitCond(0, $limit);
        $where .= " order by id desc {$limit}";
        $sql = SqlCombinHelper::select_sql($this->table, $this->fields, $where);		
        return $this->dbback->getAll($sql);
    }
    
    
    /**
     * 获取最新几个交易记录
     * @param int $brokerId 经纪人编号
     * @param int $limit 个数
     * @return array
     */
    public function getNewBy($brokerId, $limit = 6) {
        $where = '';
        $limit = $this->getLimitCond(0, $limit);
        $where .= "broker_id = $brokerId and ishidden = 1 order by id desc {$limit}";
        $sql = SqlCombinHelper::select_sql($this->table, $this->fields, $where);
        return $this->dbback->getAll($sql);
    }
    
    /**
     * 获取房豆交易总数
     * @param int $brokerId 经纪人编号
     * @param date $starttime 开始时间
     * @param date $endtime 结束时间
     * @param string $opertorType 操作类型 
     * @param int $source 来源
     * @param string or array $wayAlias 别名
     * @return array
     */
    public function getCountBy($brokerId, $starttime, $endtime, 
            $opertorType = null, $source = null, $wayAlias = null) {

		$starttime = strtotime($starttime);
		$endtime = strtotime($endtime);

        $where = '';
        $where .= "broker_id = $brokerId  and ishidden = 1 and createtime >= "
                . "'$starttime' and createtime <= '$endtime'";
        //获取get 消耗 pay
        if ($opertorType != null) {
            $where .= ' and' . $this->getOpertorTypeWhere($opertorType);
        }
        //来源 1 PC端 2 APP
        if ($source != null && $source != '0') {
            $where .= ' and source = ' . $source;
        }
        //操作别名
        if ($wayAlias != null && $wayAlias != '0') {
            if (is_array($wayAlias))
            {
                $where .= " and way_alias in ('".  implode("','", $wayAlias)."')";
            }
            else
            {
                $where .= ' and way_alias = ' . "'$wayAlias'";
            }
        }
        $sql = SqlCombinHelper::count_sql($this->table, $where);

        return $this->dbback->getOne($sql);
    }
    
    /**
     * 获取房豆交易消耗和获取数量
     * @param int $brokerId 经纪人编号
     * @param date $starttime 开始时间
     * @param date $endtime 结束时间
     * @param string $opertorType 操作类型 
     * @param int $source 来源
     * @param string or array $wayAlias 别名
     * @return array
     */
    public function getSumBy($brokerId, $starttime, $endtime, 
            $opertorType = null, $source = null, $wayAlias = null) {
         $where = '';
        $where .= "broker_id = $brokerId  and ishidden = 1 and ctime >= "
                . "'$starttime' and ctime <= '$endtime'";
        //获取get 消耗 pay
        /**
        if ($opertorType != null) {
            $where .= ' and' . $this->getOpertorTypeWhere($opertorType);
        }***/
        //来源 1 PC端 2 APP
        if ($source != null && $source != '0') {
            $where .= ' and source = ' . $source;
        }
        //操作别名
        if ($wayAlias != null && $wayAlias != '0') {
            if (is_array($wayAlias))
            {
                $where .= " and way_alias in ('".  implode("','", $wayAlias)."')";
            }
            else
            {
                $where .= ' and way_alias = ' . "'$wayAlias'";
            }
        }
        $sql = SqlCombinHelper::sum_sql($this->table, 'num', $where);
		//echo $sql;
        return $this->dbback->getOne($sql);
    }
}
