<?php
/**
 * 经纪人充值记录
 * @author sun
 */
class PaymentRechargeRecord {
    
    /**
     * 主数据库 
     * @var TINY_ADODB 
     */    
    private $db;
    
    /**
     * 从数据库
     * @var type 
     */
    private $dbback;
    
    /**
     * 缓存对象
     * @var type 
     */
    private $mc;

    /**
     * 关联的表名 
     * @var String 
     */
    private $table;

    private $credit;
    /**
     * 构造函数，初始化db memcache 等。
     * @param string $table 表名，可以使用默认值。
     */
    public function __construct() {
        $container = Container::getInstance();
        $this->db = $container->get('db');
        $this->dbback = $container->get('dbback');
        $this->table = 'payment_housebean_recharge_record';
        $this->table_success = 'payment_housebean_recharge_success_record';
		$this->table_success_job = 'payment_housebean_recharge_success_record_job';
        $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;
    }

    /**
     * 获得经纪人当前积分的数组。
     * @return array  
     */
    public function getBrokerCredit($brokerId) {
        $credit = new GrowthCredit();
        return $credit->findByBrokerId($brokerId);
    }
    
    /**
     * 插入充值记录
     * @param int $brokerId 经纪人编号
     * @param int $active_type 套餐类型
     * @param int $price 价格
     * @param int $price 价格
     * @param int $type 获取途径 暂为充值
     * @param string $transaction_id 交易号
     * @param string $program 充值方案描述
     * @param int $source 来源
     * @param int $num 房豆数量
     * @param string $invoice 发票抬头
     * @return int
     */
    public function insert($brokerId, $active_type, $price, $bank_name,
            $transaction_id, $program, $source, $num, $invoice, $type = 1) {
        $fieldsValue = array();
        $creditOne = $this->getBrokerCredit($brokerId);
        $fieldsValue['broker_id'] = $brokerId;
        $sql = SqlCombinHelper::select_sql('broker', 'agentcode',
                'uid = ' . $brokerId);
        $fieldsValue['agentcode'] = $this->dbback->getOne($sql);
        $fieldsValue['active_type'] = $active_type;
        $fieldsValue['price'] = $price;
        $fieldsValue['bank_name'] = $bank_name;
        $fieldsValue['type'] = $type;
        $fieldsValue['transaction_id'] = $transaction_id;
        $fieldsValue['program'] = $program;
        $fieldsValue['source'] = $source;
        $fieldsValue['num'] = $num;
        $fieldsValue['remain_num'] = $creditOne['credit'];
        $fieldsValue['invoice'] = $invoice;
        $fieldsValue['status'] = 0;
        $fieldsValue['ip'] = GetIp();
        $fieldsValue['discard'] = 0;
        $fieldsValue['ctime'] = date('Y-m-d H:i:s');
        $sql = SqlCombinHelper::insert_sql($this->table, $fieldsValue);
        $this->db->execute($sql);
        return $this->db->Insert_ID();
    }

    /**
     * 复制支付成功数据到成功表中
     * @param int $id 记录编号
     */
    public function copyRechargeSuccessRecord($id) 
    {
        $fields = implode(',', $this->fields);
        $sql = 'INSERT INTO ' . $this->table_success . ' (' . $fields 
             . ') SELECT * FROM ' . $this->table . ' where id = ' . $id;
        return $this->db->execute($sql);
    }
    
    /**
     * 更新支付参数
     * @param array $fieldValues 参数数组
     * @param int $id 编号
     * @param int $brokerId 经纪人编号
     * @return boolean
     */
    public function update($fieldValues, $id, $brokerId) {
        $sql = SqlCombinHelper::update_sql($this->table, $fieldValues,
                "id = {$id} and broker_id = {$brokerId} and status <> 1");
        return $this->db->execute($sql);
    }
    
    /**
     * 获取充值交易列表
     * @param int $brokerId 经纪人编号
     * @param date $starttime 开始时间
     * @param date $endtime 结束时间
     * @param int $type 获取类型
     * @param int $source 来源
     * @param int $start 开始
     * @param int $pagesize 每页多少条
     * @param string $order 排序
     * @return array
     */
    public function getListBy($brokerId, $starttime, $endtime, $type = 1, 
            $source = null, $start = null, $pagesize = null, $order = null) {
        $where = '';
        $where .= "broker_id = $brokerId and type = $type and ctime >= '$starttime'"
                . " and ctime <= '$endtime'";
        //来源 1 PC端 2 APP
        if ($source != null && $source != '0') {
            $where .= ' and source = ' . $source;
        }
        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 date $starttime 开始时间
     * @param date $endtime 结束时间
     * @param int $type 获取类型
     * @param int $source 来源
     * @return int
     */
    public function getCountBy($brokerId, $starttime, $endtime,
            $type, $source = null) {
        $where = '';
        $where .= "broker_id = $brokerId and type = $type and ctime >= '$starttime'"
                . " and ctime <= '$endtime'";
        //来源 1 PC端 2 APP
        if ($source != null && $source != '0') {
            $where .= ' and source = ' . $source;
        }
        $sql = SqlCombinHelper::count_sql($this->table, $where);
        return $this->dbback->getOne($sql);
    }
    
    /**
     * 获取充值房豆交易总数
     * @param int $brokerId 经纪人编号
     * @param date $starttime 开始时间
     * @param date $endtime 结束时间
     * @param int $type 获取类型
     * @param int $source 来源
     * @return int
     */
    public function getSumBy($brokerId, $starttime, $endtime,
            $type, $source = null) {
        $where = '';
        $where .= "broker_id = $brokerId and type = $type and ctime >= '$starttime'"
                . " and ctime <= '$endtime'";
        //来源 1 PC端 2 APP
        if ($source != null && $source != '0') {
            $where .= ' and source = ' . $source;
        }
        $sql = SqlCombinHelper::sum_sql($this->table, 'num', $where);
		//echo $sql;
        return $this->dbback->getOne($sql);
    }
    
    /**
     * 根据编号id和经纪人编号获取一条充值记录
     * @param int $id 编号
     * @param int $brokerId 经纪人编号
     * @return array
     */
    public function getOneByIdAndBrokerId($id, $brokerId, $status) {
        $sql = SqlCombinHelper::select_sql($this->table, $this->fields, 
                "id = {$id} and broker_id = {$brokerId} and status = $status");
        return $this->dbback->getRow($sql);
    }

    public function getOneByIdAndBrokerIdNoStatus($id, $brokerId) {
        $sql = SqlCombinHelper::select_sql($this->table, $this->fields,
            "id = {$id} and broker_id = {$brokerId}");
        return $this->dbback->getRow($sql);
    }

    public function getAllSuccessById($id) {
        $sql = SqlCombinHelper::select_sql($this->table_success, $this->fields, 
                "id > {$id} and status = 1 and invoice <> '' order by id asc limit 10");
        return $this->dbback->getAll($sql);
    }

	public function successJobInsert($data = array())
	{
        if(empty($data))
		{
			return '0';
		}

        $sql = SqlCombinHelper::insert_sql($this->table_success_job, $data);
        $this->db->execute($sql);
        return $this->db->Insert_ID();
    }
}
