<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');


class MY_Model extends CI_Model
{
    protected $form_name; //定义表名字

    public function __construct()
    {
        parent::__construct();

        $this->db_esf = $this->load->database('dsn_esf',true);

        //$this->db_esfbak = $this->db_esf;
        $this->db_esfbak = $this->load->database('dsn_esfbak',true);

        $this->db_esfhouse = $this->load->database('dsn_esfhouse',true);
        $this->db_esfhousebak = $this->load->database('dsn_esfhousebak',true);


        $this->load->library('server',array('appName'=>NS_SELL,'strCheckMethod'=>"",'returnMethod'=>"ary",'returnCharSet'=>"gbk"),'server_sell');
        $this->load->library('server',array('appName'=>NS_RENT,'strCheckMethod'=>"",'returnMethod'=>"ary",'returnCharSet'=>"gbk"),'server_rent');
    }

    /**
     * @param Str $form_name  设置表名
     * @return true
     */
    public function set_table($form_name)
    {
        $this->form_name = $form_name;
    }

       /**
     * @param Str $form_name
     * @param Array $data
     * @return insert_id or 0
     */
    public function add($data,$con='db_esf') {
        $this->dbselect($con);
        if (empty($data) || !is_array($data)) {
            $result = 0;
        } else {
            $this->db->insert($this->form_name, $data);    //插入数据
            if (($this->db->affected_rows()) >= 1) {
                $result = $this->db->insert_id();      //如果插入成功，则返回插入的id
            } else {	
				$uid = isset($data['uid']) ? $data['uid'] : 0;
				$id = isset($data['rowid']) ? $data['rowid'] : 0;
				$num = isset($data['refresh_num']) ? $data['refresh_num'] : 0;
				$city = isset($data['cityname']) ? $data['cityname'] : 0;
				$tbl = isset($data['tbl']) ? $data['tbl'] : 0;

				file_put_contents('test.log',"edit：会员id=".$uid." 房源id=".$id." 刷新次数=".$num." 城市=".$city."  房源类型tbl=".$tbl."  记录时间=".date('Y-m-d H:i:s')."\r\n",FILE_APPEND);

                $result = 0;    //如果插入失败,返回0
            }
        }
        return $result;
    }

    /**
     * @param Array $data
     * @ int $id 大于0
     * @return 1 or 0
     */
    public function save($arr, $data,$con='db_esf') {
        $this->dbselect($con);
        if (!empty($data) && is_array($data) && !empty($arr) && is_array($arr)) {
            $this->db->where($arr);
            if ($return = $this->db->update($this->form_name, $data)) {
			    //echo $this->db->last_query();
                $result = 1; //更新成功，返回1
            } else {
                $result = 0; //失败，返回0
            }
        } else {
            $result = 0;
        }
        return $result;
    }

    /**
     * 删除takeaway
     *
     * @param int $id
     * @return 0 or 1
     */
    public function del($id,$con='esf') {
        $this->dbselect($con);
        $id = intval($id);
        if (is_numeric($id) && $id > 0) {
            $this->db->where('id', $id);
            $this->db->delete($this->form_name);
            if (($this->db->affected_rows()) >= 1) {
                $result = 1;      //如果删除成功，则返回1
            } else {
                $result = 0;    //如果删除失败，返回0
            }
        } else {
            $result = 0;
        }
        return $result;
    }


     /**
     * 批量删除takeaway
     *
     * @param int $id
     * @return 0 or 1
     */
    public function del_mul($string,$name,$con='esf') {
        $this->dbselect($con);
        $tmp_arr = explode(',',$string);
        if ($tmp_arr) {
            $this->db->where_in($name, $tmp_arr);
            $this->db->delete($this->form_name);
            if (($this->db->affected_rows()) >= 1) {
                $result = 1;      //如果删除成功，则返回1
            } else {
                $result = 0;    //如果删除失败，返回0
            }
        } else {
            $result = 0;
        }
        return $result;
    }

    /**
     *
     * @return Array
     */
    public function findAll() {
        $list = array();
        $query = $this->db->get($this->form_name);
        $result = $query->result_array();
        $sqls = $this->db->last_query();
		//echo "<!--$sqls-->";
                //echo $this->db->last_query();exit;
        foreach ($result as $key1 => $val1) {
            foreach ($val1 as $key2 => $val2) {
                $row[$key2] = stripslashes($val2);
            }
            $list[] = $row;
            $row = array();
        }
        return $list;
    }

    /**
     *
     * @return Array
     */
    public function find($con='esfback') {
        $this->dbselect($con);
        $list = array();
        $query = $this->db->get($this->form_name);

        $result = $query->first_row('array');
        foreach ($result as $key => $val) {
            $list[$key] = stripslashes($val);
        }
        return $list;
    }

    /**
     * 匹配表单上传数据
     * @param array $data
     * @return Array
     */
    public function create($data,$con='esfback') {
         $this->dbselect($con);
        $list = array();
        if (!empty($data) && is_array($data)) {   //如果存在$_POST数据 则进行数据筛选
            foreach ($this->db->list_fields($this->form_name) as $field) {
                foreach ($data as $key => $val) {
                    if ($field == $key) {   //取出与数据库字段名相同的POST值
                        if (!get_magic_quotes_gpc())
                            $list[$key] = addslashes(strip_tags($val));
                        else
                            $list[$key] = strip_tags($val);
                    }
                }
            }
            return $list;
        }else {
            return false;
        }
    }

    //递归获取到所有数据
    public function getChildren($array, $pid = 0, &$tdata = array()) {
        if (!empty($array)) {
            foreach ($array as $value) {
                if ($value['pid'] == $pid) {
                    $tdata[] = $value;

                    //递归调用
                    $this->getChildren($array, $value['id'], $tdata);
                } elseif ($value['id'] == $pid) {
                    $tdata[] = $value;
                }
            }

            return $tdata;
        } else {
            return array();
        }
    }

    /**
     * @param Array( 'form_name' = 表单名,'where'=where条件格式 array('id'=>$id, 'status'=>1);
     *
     *
     * @return Array
     */
    public function get_data($data = array(),$con='esfback') {
         $this->dbselect($con);
        if (!empty($data['form_name']) AND isset($data['form_name']))
            $this->form_name = $data['form_name'];

        if (isset($data['select']) AND !empty($data['select'])) {
            $data['select_str'] = implode($data['select'],',');
            $this->db->select($data['select_str']);
        }
        if (isset($data['where']) AND !empty($data['where'])) {
            $this->db->where($data['where']);
        }
        if (isset($data['or_where']) AND !empty($data['or_where'])) {
            $this->db->or_where($data['or_where']);
        }
        if (isset($data['where_in']) AND !empty($data['where_in'])) {
            $this->db->where_in($data['where_in'][0],$data['where_in'][1]);
        }
        if(isset($data['order_by']) AND !empty($data['order_by']))
        {
             $this->db->order_by($data['order_by']);
        }
        if(isset($data['group_by']) AND !empty($data['group_by']))
        {
             $this->db->group_by($data['group_by']);
        }
        if (isset($data['offset']) && strlen($data['offset']) > 0 && is_numeric($data['offset']))
        {
            if ($data['offset'] > 0)
            {
                if (strlen($data['limit']) && is_numeric($data['limit']))
                {
                    ($data['limit'] > 0) ? $this->db->offset($data['offset'])->limit($data['limit']) : $this->db->offset($data['offset'])->limit(20);
                }
                else
                {
                    $this->db->offset($data['offset'])->limit(20);
                }
            }
            else
            {
                if (strlen($data['limit']) && is_numeric($data['limit']))
                {
                    if ($data['limit'] > 0)
                        $this->db->limit($data['limit']);
                }
            }
        }elseif (isset($data['limit']) && strlen($data['limit']) > 0 && is_numeric($data['limit']))
        {
            if ($data['limit'] > 0)
                $this->db->limit($data['limit']);
        }

        $result = $this->findAll();

        return $result;
    }

	function dbselect($con)
	{

		switch ($con)
		{
			case 'dbuser':
			case 'esf':
			$this->db = $this->db_esf;
			break;

			case 'esfbak':
			$this->db = $this->db_esfbak;
			break;

			//case 'bbs':
			//$this->db = $this->db_bbs;//20160219
			//break;

			case 'esfadmin':
			$this->db = $this->db_esfadmin;
			break;

			case 'esfhouse':
			$this->db = $this->db_esfhouse;
			break;

			case 'esfhousebak':
			$this->db = $this->db_esfhousebak;
			break;

			default:
			$this->db = $this->db_esf;
		}
	}


	function __destruct()
    {
        if(is_object($this->db_esf))
        {
            $this->db_esf->close();
        }
		if(is_object($this->db_esfbak))
        {
            $this->db_esfbak->close();
        }
		if(is_object($this->db_esfhouse))
        {
            $this->db_esfhouse->close();
        }
		if(is_object($this->db_esfhousebak))
        {
            $this->db_esfhousebak->close();
        }
    }
}
?>