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

class Shop_Model extends MY_Model {

	const NORMAL = 1;
    const LEVLE1 = 2;
    const LEVLE2 = 3;


    protected $table = 'shop';
    protected $key = 'sid';

    protected $insert_filed = array('name', 'password','title', 'level2_des', 'category', 'loc', 'pic',
    	'address','shop_des', 'message', 'date', 'strat_time', 'end_time', 'update_time', 'create_time', 'status' ,'aid');


    public function insert($data){
        list($data['pic'], $a, $b) = explode('|', $data['small_pics'][0]);
        $data['name'] = $data['shopname'];
        $data['password'] = $this->encrypt($data['password1']);
    	$data['update_time'] = time();
    	$data['create_time'] = time();
    	$data['status'] = self::NORMAL;
    	return parent::insert($data);
    }


    public function update($data, $id){

        $data['update_time'] = time();
        list($data['pic'], $a, $b) = explode('|', $data['small_pics'][0]);
        $data['name'] = $data['shopname'];
        $data = $this->check_insert($data);
        $this->db->where('sid', $id);
        $this->db->update($this->table, $data);
        return $id;
    }

    public function updateBySid($data, $id){

        $this->db->where('sid', $id);
        $this->db->update($this->table, $data);
        return $id;
    }
    
    /**
     * [updateShopStatus 更改商家状态]
     * @param  [type] $data [商家的状态]
     * @param  [type] $sid  [商家sid]
     * @return [type]       [TRUE]
     */
    public function updateShopStatus($data,$sid){

        $this->db->where('sid', $sid);
        $this->db->update($this->table, $data);
        return TRUE;
    }


    public function updateShopTel($shop_tel, $shop_id){
    	$this->db->delete('shop_tel', array('sid' => $shop_id));
    	$insert = array();
    	foreach($shop_tel as $tel){
    		$row['sid'] = $shop_id;
    		$row['tel'] = $tel;
    		$insert[] = $row;
    	}
    	$this->db->insert_batch('shop_tel', $insert);
    }

    public function updateShopPic($shop_pic, $type, $shop_id){
    	$this->db->delete('shop_pic', array('sid' => $shop_id, 'type' => $type));
    	$insert = array();
    	foreach($shop_pic as $pic){
            list($pic, $width, $height) = explode('|', $pic);
    		$row['sid'] = $shop_id;
    		$row['pic'] = $pic;
            $row['width'] = $width;
            $row['height'] = $height;
    		$row['type'] = $type;
    		$insert[] = $row;
    	}
    	$this->db->insert_batch('shop_pic', $insert);
    }





    public function getShopInfo($shop_id){
    	$shop_info = $this->db->get_where('shop', array('sid' => $shop_id))->row_array();

    	if(empty($shop_info)){
    		return false;
    	}

    	$shop_info['tel'] = $this->db->get_where('shop_tel', array('sid' => $shop_id))->result_array();
    	$shop_info['pic'] = $this->db->order_by('id', 'asc')->get_where('shop_pic', array('sid' => $shop_id, 'type' => 1))->result_array();
        $shop_info['top_pic'] = $this->db->order_by('id', 'asc')->get_where('shop_pic', array('sid' => $shop_id, 'type' => 2))->result_array();
        $shop_info['message_pic'] = $this->db->order_by('id', 'asc')->get_where('shop_pic', array('sid' => $shop_id, 'type' => 3))->result_array();
    	return $shop_info;

    }

    public function insertDate($data){
        $this->db->insert_batch('shop_date', $data);
    }


    public function countShops($category = 0, $aid = 0){
        $this->db->where('status', self::NORMAL);
        if(!empty($category)){
            $this->db->where('category', $category);
        }
        if(!empty($aid)){
            $this->db->where('aid', $aid);
        }
        $this->db->from($this->table);
        return $this->db->count_all_results();
    }

    public function countLevel2ByDate($timestamp, $category ){
       
        $this->db->from('shop_date AS d');
        $this->db->join('shop AS s', 'd.sid = s.sid');
        $this->db->where('d.timestamp', $timestamp);
        $this->db->where('s.status', self::NORMAL);
        if(!empty($category)){
            $this->db->where('s.category', $category);
        }
        return $this->db->count_all_results();
    }



    public function getLevelByDate($sid, $date){
        $this->db->where('timestamp',  strtotime($date));
        $this->db->where('sid', $sid);


        $query = $this->db->get('shop_date');

        if($query->num_rows() > 0){
            return '2';
        }else{
            return '1';
        }

    }


    public function getShopList($start, $limit, $level, $category,  $order){
        $now_time = time();
        if($level == 1){
            //过期的
            $this->db->where('end_time < ', $now_time);
            //未开通的
            $this->db->or_where('end_time', 0);
        }else{
             $this->db->where('end_time > ', $now_time);
        }

        if(!empty($category)){
            $this->db->where('category', $category);
        }

      

        $this->db->order_by($order, 'DESC');
        $this->db->order_by('praise_num', 'DESC');
        return $this->db->get($this->table)->result_array();
    }


    public function getLevel1List($timestamp, $start, $limit,  $category, $aid, $order){
        $shop_date_table = $this->db->dbprefix('shop_date');
        $shop_table = $this->db->dbprefix('shop');

        $this->db->where('status', self::NORMAL);

        
      
 
        $this->db->where(" sid NOT IN (SELECT sid FROM {$shop_date_table} WHERE timestamp ='{$timestamp}')", null ,false);

        if(!empty($aid)){
            $this->db->where('aid', $aid);
        }
        
        if(!empty($category)){
            $this->db->where('category', $category);
        }

        if($order == 'create_time'){
            $this->db->order_by('sort', 'asc');
        }
        $this->db->order_by($order, 'DESC');
        $this->db->order_by('praise_num', 'DESC');
        $this->db->limit($limit, $start);

        return  $this->db->get('shop')->result_array();

    }

    public function getLevel2List($timestamp, $start, $limit, $category, $aid = 0, $order){
        $shop_date_table = $this->db->dbprefix('shop_date');
        $shop_table = $this->db->dbprefix('shop');
        $where = array();
        if(!empty($timestamp)){
            $where[] = " `{$shop_date_table}`.`timestamp`='{$timestamp}' ";



            $orderby = $order == 'create_time' ? " {$shop_table}.sort ASC,{$shop_table}.{$order} DESC, {$shop_table}.create_time DESC" : " {$shop_table}.{$order} DESC, {$shop_table}.create_time DESC";
        }else{
            $where[] = " {$shop_date_table}.timestamp <> '' ";
            //默认排序
            if($order == 'create_time'){
                $orderby = " {$shop_date_table}.timestamp ASC,{$shop_table}.sort ASC, {$shop_table}.{$order} DESC, {$shop_table}.create_time DESC ";
            }else{
                $orderby = " {$shop_date_table}.timestamp ASC,{$shop_table}.{$order} DESC, {$shop_table}.create_time DESC ";
            }

            
        }

        if(!empty($category)){
            $where[] = " {$shop_table}.category = '{$category}' ";
        }

        if(!empty($aid)){
            $where[] = " {$shop_table}.aid = '{$aid}'";
        }

        //默认条件
        $today = strtotime('today');
        $where[] = " `{$shop_date_table}`.`timestamp` >= {$today} ";
        $where[] = " `{$shop_table}`.status = ".self::NORMAL." ";

        if(!empty($where)){
            $where = 'WHERE'. implode(' AND ', $where);
        }else{
            $where = '';
        }


        $sql = "SELECT * FROM {$shop_table}  
                LEFT JOIN {$shop_date_table} ON {$shop_date_table}.sid={$shop_table}.sid
                $where
               ORDER BY $orderby 
               LIMIT {$start},{$limit}";

        return  $this->db->query($sql)->result_array();

    }


    public function login($sid, $password){
        $this->db->where('sid', $sid);
        $this->db->where('status',1);//删除的商家不能登录
        $result = $this->db->get($this->table)->row_array();

        if($result['password'] == $this->encrypt($password)){
            $result['tel'] = $this->db->get_where('shop_tel', array('sid' => $sid))->result_array();
            return $result;
        }

        return false;
    }

    public function updatePassword($password, $sid){
        $this->db->where('sid', $sid);
        return $this->db->update($this->table, array('password' => $this->encrypt($password)));
    }

    /**
     * [getSellerList description]
     * @return [type] [description]
     */
    public function getSellerList($limit,$offset)
    {
        $this->db->order_by('status', 'desc');

        $this->db->order_by('create_time', 'desc');
        return $this->db->get($this->table,$limit,$offset)->result_array();   
    }

    public function count()
    {
        return $this->db->count_all($this->table);
    }

    public function deleteShopDate($sid){
        $this->db->delete('shop_date', array('sid' => $sid));
    }

    public function encrypt($password){

        return md5('sdfsdf'.md5($password));
    }







}