<?php

/**
 * 前台 酒店列表 模块 Model
 * ============================================================================
 * ZhunaCMS 住哪网酒店分销联盟程序php版　BY Tmac PHP MVC framework
 * $Author: zhaojianjun $  <zwttmac@qq.com>
 * $Id: hotellist.class.php 127 2012-01-12 07:56:00Z zhaojianjun $
 * http://un.zhuna.cn；
 */
class hotellist extends Model
{

    private $db;
    private $hotel_table;
    private $search_table;
    private $common_model;
    private $liansuohotel_model;
    private $hotel_left_model;

    /**
     * 初始化变量　定义私有变量
     */
    public function _init()
    {
        //连接数据库
        $this->db = $this->connect();
        $this->hotel_table = DB_PREFIX . 'hotel';
        $this->search_table = DB_PREFIX . 'search';
        $this->common_model = Tmac::model('common');
        $this->liansuohotel_model = Tmac::model('liansuohotel');
        $this->hotel_left_model = Tmac::model('hotelLeft');
    }

    /**
     * 根据搜索条件where 取搜索出来的酒店列表
     * @param <type> $searchArray
     * @return hotelarray
     */
    public function getHotelList($searchArray)
    {
        $juli_limit = '5000';   //在多少米内第一次拉框搜索XX附近酒店
        $nofind = '';   //初始化为空
        $pagesize = 8;
        $url_array = array();   //初始化url参数;
        $url = PHP_SELF . '?m=hotellist';
        $keyName = 'hotel_id, hotelname, star, address, content, cbd_id, cbd_name, chain_name, chain_id, picture, haoping, cityname, cityid, nearbypoints';
        $where = "WHERE cityid = {$searchArray['cityid']} ";
        $url .= "&cityid={$searchArray['cityid']}";
        if (!empty($searchArray['cbd_id'])) {
            $where .= "AND cbd_id = {$searchArray['cbd_id']} ";
            $url_array['cbd_id'] = $searchArray['cbd_id'];
        }
        if (!empty($searchArray['minprice'])) {
            $where .= "AND min_price >= {$searchArray['minprice']} ";
            $url_array['minprice'] = $searchArray['minprice'];
        }
        if (!empty($searchArray['maxprice'])) {
            $where .= "AND min_price <= {$searchArray['maxprice']} ";
            $url_array['maxprice'] = $searchArray['maxprice'];
        }
        if (!empty($searchArray['rank'])) {
            $rankstar = $this->hotelRankNum($searchArray['rank']);
            $where .= "AND star {$rankstar} ";
            $url_array['rank'] = $searchArray['rank'];
        }
        if (!empty($searchArray['chain_id'])) {
            $where .= "AND chain_id = {$searchArray['chain_id']} ";
            $url_array['chain_id'] = $searchArray['chain_id'];
        }
        if (!empty($searchArray['hn'])) {
            $where .= "AND hotelname like '%{$searchArray['hn']}%' ";
            $hn = urlencode($searchArray['hn']);
            $url_array['hn'] = $hn;
        }

        //先检查cookies里有没有已经存在的搜索结果key
        $search_key_cookie = HttpResponse::getCookie('search_key');
        $key_x_cookie = HttpResponse::getCookie('key_x');
        $key_y_cookie = HttpResponse::getCookie('key_y');
        if (!empty($search_key_cookie) && ($search_key_cookie == $searchArray['key']) && !empty($key_x_cookie) && !empty($key_y_cookie)) {
            $getkeyxy_result['retmsg'] = 'ok';
            $key_x = $key_x_cookie;
            $key_y = $key_y_cookie;
            $key_result_q = $search_key_cookie;
            $searchArray['key'] = $key_result_q;
            $keyName .= ',x,y';
            $where .= "AND (x BETWEEN {$key_x}-{$juli_limit} AND {$key_x}+{$juli_limit}) and (y BETWEEN {$key_y}-{$juli_limit} AND {$key_y}+{$juli_limit}) ";
            $url_array['key'] = urlencode($searchArray['key']);
        } else {
            //附近地标        
            if (!empty($searchArray['key'])) {
                $cfg_apiurl = Tmac::config('configcache.config.cfg_apiurl', APP_NAME, '.inc.php');
                $api_url = $cfg_apiurl . "getkeyxy_json.php?cityid={$searchArray['cityid']}";
                $keyword = urlencode($searchArray['key']);
                $api_url .= "&key={$keyword}";
//            echo $api_url.'<br>';
                $getkeyxy_result = json_decode(Functions::GetHttps($api_url), true);
                if ($getkeyxy_result['retmsg'] != 'ok') {
                    $nofind = '<div class="no_find"><p>系统没有查询到"<font color="#207DD4">' . $searchArray['cityname'] . '  ' . $searchArray['key'] . '</font>"附近相关酒店,请更换条件或选择以下酒店。</p></div>';
                    $searchArray['key'] = '';
                    $key_x = 0;
                    $key_y = 0;
                    $key_result_q = '';
                } else {
                    $key_x = $getkeyxy_result['reqdata']['x'];
                    $key_y = $getkeyxy_result['reqdata']['y'];
                    $key_result_q = $getkeyxy_result['reqdata']['result_q'];
                    //TODO 判断如果返回值和查询key不一样时的报告;
                    if (urldecode($keyword) != $key_result_q) {
                        $nofind = '<div class="no_find"><p>我猜您要找的是"<font color="#207DD4">' . $key_result_q . '</font>"附近酒店</p></div>';
                        $searchArray['key'] = $key_result_q;
                    }
                }

                $keyName .= ',x,y';
                $where .= "AND (x BETWEEN {$key_x}-{$juli_limit} AND {$key_x}+{$juli_limit}) and (y BETWEEN {$key_y}-{$juli_limit} AND {$key_y}+{$juli_limit}) ";
                $url_array['key'] = urlencode($searchArray['key']);
                //开始把查询到的key结果扔到cookies里
                HttpResponse::setCookie('search_key', $key_result_q);
                HttpResponse::setCookie('key_x', $key_x);
                HttpResponse::setCookie('key_y', $key_y);
            } else {
                $getkeyxy_result['retmsg'] = 'nokey';
            }
        }
        /* 附近地标结束 */
        if (!empty($searchArray['key']) && $searchArray['px'] == 1)
            $searchArray['px'] = 5;
        //如果px是以价格来排序的
        if ($searchArray['px'] == 2)
            $where .= "AND min_price > 0 ";

        //处理排序
        switch ($searchArray['px'])
        {
            case 1: //网站推荐
                $order = 'px_index DESC,hotel_id DESC';
                break;
            case 2: //价格排序
                $order = 'Min_price ASC,px_index DESC,hotel_id DESC';
                break;
            case 3: //星级排序
                $order = 'star DESC,px_index DESC,hotel_id DESC';
                break;
            case 4: //人气排序
                $order = 'px_hot DESC,px_index DESC,hotel_id DESC';
                break;
            case 5: //距离排序
                $order = "px_index DESC";
                break;
            default :
                $order = 'px_index DESC,Px_hot DESC';
        }
        if (!empty($order))
            $order = 'ORDER BY ' . $order;

        $url_array['px'] = $searchArray['px'];  //把px参数放在url数组中
        #add 联合查询url begin
        //处理url
        $url_price = $this->replaceUrl($url, $url_array, 'minprice,maxprice'); //价格范围url
        $url_cbd_id = $this->replaceUrl($url, $url_array, 'cbd_id');           //著名商圈url
        $url_rank = $this->replaceUrl($url, $url_array, 'rank');               //星级档次url
        $url_chain_id = $this->replaceUrl($url, $url_array, 'chain_id');       //品牌连锁url        
        $url_px = $this->replaceUrl($url, $url_array, 'px');                   //pxurl
        $url_px .= '&px=';
        $url_page = $this->replaceUrl($url, $url_array, 'page') . '&page=';    //分页的url        
        #add 联合查询url over
        //组合sql_count from+where
        $sql_count = "SELECT COUNT(*) FROM $this->hotel_table " . $where;
        //取查询到的总数
        $count = $this->db->getOne($sql_count);
        //开始判断来源如果是百度或者google就定位到第一页中
        $refer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $pagenow = 0;
        if (!empty($refer)) {
            if (strpos($refer, 'http://www.baidu.com/') !== false || strpos($refer, 'http://www.google.com') !== false) {
                $pagenow = 1;
            }
        }
        $pages = $this->P('Pages', $pagenow);
        $pages->setTotal($count);
        $pages->setUrl($url_page);
        $pages->setPrepage($pagesize);
        $limit = $pages->getSqlLimit();
        $pagenow = $pages->getNowPage();
        //组合$sql from+where+order
        $sql = "SELECT {$keyName} FROM $this->hotel_table ";
        //如果有搜索XX附近的地标||就把所有的数据取出来计算距离
        if ($getkeyxy_result['retmsg'] == 'ok') {
            $sql .= $where . $order;
            $page = ceil($count / $pagesize);
            //如果当前currentPage 大于 总pages的话就显示最后一页
            $pagenow > $page && $pagenow = $page;
            $pagenow = ($pagenow - 1) * $pagesize;
        } else {
            $sql .= $where . $order . " LIMIT $limit";
        }
//        echo $sql;
        $hotel_result_array = array();
        $h_id_array = array();
        $query = $this->db->query($sql);
        if ($query) {
            while ($hotel_array = $this->db->fetch($query)) {
                //如果有搜索XX附近的地标||就计算距离
                if ($getkeyxy_result['retmsg'] == 'ok') {
                    $juli = self::getDistance($key_x, $key_y, $hotel_array['x'], $hotel_array['y']);
                    $hotel_array['juli'] = round($juli / 100000000, 2);
                }
                //遍历取hotel_id数组
                $h_id_array[] = $hotel_array['hotel_id'];
                $hotel_result_array[] = $hotel_array;
            }
        }
        unset($hotel_array);
        //如果有搜索XX附近的地标||就计算按距离排序
        if ($getkeyxy_result['retmsg'] == 'ok') {
            $hotel_result_array = $this->array_sort($hotel_result_array, 'juli', $pagenow, $pagesize);
            $rs = $hotel_result_array['rs'];
            $hid = implode(',', $hotel_result_array['hid']);
        } else {
            $rs = $hotel_result_array;
            $hid = implode(',', $h_id_array);
        }


        $title_key_des_array = $this->getTitleKeywordsDescription($searchArray, $pages->getNowPage());
        if ($count == 0) {
            $nofind_key = $searchArray['cityname'] . $title_key_des_array['key_fu'] . $title_key_des_array['cbd_name'] . $title_key_des_array['chain_name'] . $title_key_des_array['star'] . $title_key_des_array['minjiage'] . $title_key_des_array['maxjiage'] . $searchArray['hn'];
            $nofind_key = str_replace($searchArray['cityname'] . $searchArray['cityname'], $searchArray['cityname'], $nofind_key);
            $nofind = '<div class="no_find"><p>系统没有查询到"<font color="#207DD4">' . $nofind_key . '</font>"酒店,您可以<a href="' . PHP_SELF . '?m=hotellist&cityid=' . $searchArray['cityid'] . '">重新设置条件进行搜索</a></p></div>';
        }

        //设置搜索cookies        
        HttpResponse::setCookie('cityid', $searchArray['cityid']);
        HttpResponse::setCookie('cityname', $searchArray['cityname']);

        
        //列表图片伪静态
        $cfg_rewrite_pic = Tmac::config('configcache.config.cfg_rewrite_pic', APP_NAME, '.inc.php');
        $picurl = !empty($cfg_rewrite_pic) ? 'http://' . $_SERVER['HTTP_HOST'] . '/pic.php?p=' : $GLOBALS['TmacConfig']['config']['picurl']; 
               
        $result = array(
            'hotel_slist' => $rs,
            'pageCurrent' => $pages->getNowPage(),
            'totalrecord' => $count,
            'page' => $pages->show(),
            'key' => $searchArray['key'],
            'hid' => $hid,
            'picurl' => $picurl,
            'maxprice' => $searchArray['maxprice'],
            'minprice' => $searchArray['minprice'],
            'rank' => $searchArray['rank'],
            'chain_id' => $searchArray['chain_id'],
            'cbd_id' => $searchArray['cbd_id'],
            'px' => $searchArray['px'],
            /* 联合查询url */
            'url_price' => $url_price,
            'url_cbd_id' => $url_cbd_id,
            'url_rank' => $url_rank,
            'url_chain_id' => $url_chain_id,
            'url_px' => $url_px,
            'price_array' => Tmac::config('hotellist.price'),
            'price_now' => $searchArray['minprice'] . '-' . $searchArray['maxprice'],
            /* 取房态所用到的参数 price.un.zhuna.cn */
            'tm1' => $searchArray['tm1'],
            'tm2' => $searchArray['tm2'],
            'nofind' => $nofind,
            'hid' => $hid,
            'title_key_des_array' => $title_key_des_array
        );
        return $result;
    }

    /**
     * 计算满意度
     * @param <type> $haoping 
     */
    public function manyidu($haoping)
    {
        $hp_array = explode('$', $haoping);
        $CountHaoping = array_sum($hp_array);
        $haoping_good = $hp_array[0] + $hp_array[1];
        if ($CountHaoping == 0) {
            $myd = '100';
        } else {
            $myd = (int) (($haoping_good * 100) / $CountHaoping);
        }
        return $myd;
    }

    /**
     * 取px的当前style
     * @param <type> $my
     * @param <type> $value 
     */
    public function getpx_style($my, $value)
    {
        if ($my == $value) {
            echo 'id="info_current"';
        } else {
            echo '';
        }
    }

    /**
     * 保存搜索记录 搜索历史
     * @param <type> $searchArray 
     */
    public function save_search($searchArray)
    {
        $s_title = $searchArray['cityname'];
        if (empty($searchArray['key']) && empty($searchArray['hn'])) {
            return;
        }
        //key
        if (!empty($searchArray['key'])) {
            if (!strpos($searchArray['key'], $s_title)) {
                $s_title = $s_title . $searchArray['key'] . "附近";
            } else {
                $s_title = $searchArray['key'] . "附近";
            }
        }

        //取cbd_name
        if (!empty($searchArray['cbd_id'])) {
            $cbd_info = $this->common_model->getCbdInfo($searchArray['cbd_id']);
            $cbd_name = $cbd_info['cbd_name'];

            if (!strpos($cbd_name, $s_title)) {
                $s_title = $s_title . $cbd_name;
            } else {
                $s_title = $cbd_name;
            }
        }

        //取hn
        if (!empty($searchArray['hn'])) {
            $s_title = $s_title . $searchArray['hn'];
        }

        //取chain_name
        if (!empty($searchArray['chain_id'])) {
            $chain_info = $this->liansuohotel_model->getChainInfo($searchArray['chain_id']);
            $chain_name = $chain_info['chain_shortname'];
            $s_title = $s_title . $chain_name;
        }

        $s_cityid = $searchArray['cityid'];
        $s_hn = $searchArray['hn'];
        $s_key = $searchArray['key'];
        $s_url = $this->H($_SERVER['REQUEST_URI']);

        if (!empty($s_key)) {
            $sql = "SELECT * FROM $this->search_table WHERE s_key = '{$s_key}' LIMIT 0, 1";
            $searchinfo = $this->db->getRow($sql);
            $info = array(
                's_title' => $s_title,
                's_url' => $s_url,
                's_key' => $s_key,
                's_cityid' => $s_cityid,
                's_updatetime' => time(),
                's_count' => 1
            );
            if ($searchinfo) {
                $time = time();
                $sql = "UPDATE $this->search_table SET `s_title` = '{$s_title}', `s_url` = '{$s_url}', `s_key` = '{$s_key}', `s_cityid` = '{$s_cityid}', `s_updatetime` = '{$time}', `s_count` = s_count+1 WHERE s_key = '{$s_key}'";
                $rs = $this->db->execute($sql);
            } else {
                $rs = $this->db->autoExecute($this->search_table, $info, 'INSERT');
            }
        }

        if (!empty($s_hn)) {
            $sql = "SELECT * FROM $this->search_table WHERE s_hn = '{$s_hn}' LIMIT 0, 1";
            $searchinfo = $this->db->getRow($sql);
            $info = array(
                's_title' => $s_title,
                's_url' => $s_url,
                's_hn' => $s_hn,
                's_cityid' => $s_cityid,
                's_updatetime' => time(),
                's_count' => 1
            );
            if ($searchinfo) {
                $time = time();
                $sql = "UPDATE $this->search_table SET `s_title` = '{$s_title}', `s_url` = '{$s_url}', `s_hn` = '{$s_hn}', `s_cityid` = '{$s_cityid}', `s_updatetime` = '{$time}', `s_count` = s_count+1 WHERE s_hn = '{$s_hn}'";
                $rs = $this->db->execute($sql);
            } else {
                $rs = $this->db->autoExecute($this->search_table, $info, 'INSERT');
            }
        }
    }

    public function hotelRankNum($rank)
    {
        switch ($rank)
        {
            case 2:
                $hotelranknum = 'between 6 and 17';
                break;

            case 3:
                $hotelranknum = 'between 4 and 7';
                break;

            case 4:
                $hotelranknum = 'between 2 and 5';
                break;

            case 5:
                $hotelranknum = 'between 0 and 3';
                break;
        }
        return $hotelranknum;
    }

    /**
     * 把url数组组合成字符串
     * @param <type> $url_array
     * @param <type> $key
     * @return <type>
     */
    public function replaceUrl($url, $url_array, $key)
    {
        $urls = '';
        $key_array = explode(',', $key);
        foreach ($key_array AS $k => $v) {
            unset($url_array[$v]);
        }
        if (is_array($url_array)) {
            foreach ($url_array AS $k => $v) {
                if (!empty($v))
                    $urls .= '&' . $k . '=' . $v;
            }
        }
        return $url . $urls;
    }

    /**
     * 取搜索列表cbd数组
     * @param <type> $cityid
     * @param <type> $cbd_id
     * @param <type> $limit
     * @return <type> 
     */
    public function getSearchCbd($cityid, $cbd_id, $limit)
    {
        $cbd_array = $this->hotel_left_model->cbdList($cityid, $limit);
        $cbd_arr = array();
        foreach ($cbd_array AS $k => $v) {
            $kk = $k + 1;
            if ($v['cbd_id'] == $cbd_id) {
                $cbd_arr[0] = $v;
            } else {
                $cbd_arr[$kk] = $v;
            }
        }
        //TODO 大家觉得这样有问题
        //ksort($cbd_arr);    //对数组按照键名排序
        return $cbd_arr;
    }

    /**
     * 取搜索连锁
     * @param type $cityid
     * @param type $lsid
     * @param type $limit
     * @return type 
     */
    public function getSearchLiansuo($cityid, $lsid, $limit)
    {
        $liansuo_array = $this->hotel_left_model->getChain($cityid, $limit);
        $liansuo_arr = array();
        foreach ($liansuo_array AS $k => $v) {
            $kk = $k + 1;
            if ($v['chain_id'] == $lsid) {
                $liansuo_arr[0] = $v;
            } else {
                $liansuo_arr[$kk] = $v;
            }
        }
        ksort($liansuo_arr);    //对数组按照键名排序
        return $liansuo_arr;
    }

    /**
     * 取搜索列表页的title, keyword, description信息
     * @param type $Searchinfo
     * @param type $pg
     * @return string 
     */
    public function getTitleKeywordsDescription($Searchinfo, $pg)
    {
        //title keywords description k_page(hotelist)
        $key = empty($Searchinfo['key']) ? '' : $Searchinfo['key'];
        $key_fu = empty($key) ? '' : $key . '附近';
        $star = empty($rank) ? '' : $rank . '星级';
        $minjiage = ($Searchinfo['minprice'] == '' || $Searchinfo['minprice'] == 0) ? '' : $Searchinfo['minprice'] . '元';
        $maxjiage = ($Searchinfo['maxprice'] == '' || $Searchinfo['maxprice'] == 0) ? '' : $Searchinfo['maxprice'] . '元';

        $chain_name = '';
        if (!empty($Searchinfo['chain_id'])) {
            $chain_info = $this->liansuohotel_model->getChainInfo($Searchinfo['chain_id']);
            if ($chain_info) {
                $chain_name = $chain_info['chain_shortname'];
            } else {
                $chain_name = '连锁酒店'.$Searchinfo['chain_id'];
            }
        }
        //取cbd_name
        $cbd_name = '';
        if (!empty($Searchinfo['cbd_id'])) {
            $cbd_info = $this->common_model->getCbdInfo($Searchinfo['cbd_id']);
            $cbd_name = $cbd_info['cbd_name'];
        }
                
        $dibiao_string = '第'.$pg.'页';
        
        $array = array(
            'key' => $key,
            'key_fu' => $key_fu,
            'star' => $star,
            'minjiage' => $minjiage,
            'maxjiage' => $maxjiage,
            'chain_name' => $chain_name,
            'cbd_name' => $cbd_name,
            'dibiao_string' => $dibiao_string
        );
        return $array;
    }

    /**
     * 按星级和城市查找酒店
     * @author zhaojianjun
     * @param $rank
     * @param $cityid
     * @param $order
     * @param $limit
     */
    function getHotelByRank($rank, $cityid, $order=1, $limit=10)
    {
        $rankstar = $this->hotelRankNum($rank);
        //处理排序
        switch ($order)
        {
            case 1: //网站推荐
                $order = 'px_index DESC,hotel_id DESC';
                break;
            case 2: //价格排序
                $order = 'Min_price ASC,px_index DESC,hotel_id DESC';
                break;
            case 3: //星级排序
                $order = 'star DESC,px_index DESC,hotel_id DESC';
                break;
            case 4: //人气排序
                $order = 'px_hot DESC,px_index DESC,hotel_id DESC';
                break;
            default :
                $order = 'px_index DESC,hotel_id DESC';
        }
        $sql = "SELECT hotel_id, hotelname, min_price,star, address, content, cbd_id, cbd_name, chain_name, chain_id, picture, haoping, cityname, cityid, nearbypoints FROM $this->hotel_table where cityid=$cityid and star $rankstar order by $order limit $limit";
        $hotellist = $this->db->getAll($sql);
        return $hotellist;
    }

    /**
     * 二维数组排序函数|冒泡|分页
     * @param type $arr
     * @param type $keys
     * @param type $pagenow
     * @param type $pagesize
     * @param type $type
     * @return type 
     */
    function array_sort($arr, $keys, $pagenow, $pagesize, $type='asc')
    {
        $keysvalue = $new_array = array();
        foreach ($arr as $k => $v) {
            $keysvalue[$k] = $v[$keys];
        }
        if ($type == 'asc') {
            asort($keysvalue);
        } else {
            arsort($keysvalue);
        }
        reset($keysvalue);
        $i = 0;
        $h_id_array = array();
        foreach ($keysvalue as $k => $v) {
            $i++;
            if ($i <= $pagenow) {
                continue;
            }
            $new_array[] = $arr[$k];
            //遍历取hotel_id数组
            $h_id_array[] = $arr[$k]['hotel_id'];
            if ($i >= ($pagenow + $pagesize)) {
                break;
            }
        }
        unset($i);
        $array['rs'] = $new_array;
        $array['hid'] = $h_id_array;
        return $array;
    }

    /**
     * 计算两点之间的球面距离
     *
     * return 距离 单位(m)
     */
    static function getDistance($lng0, $lat0, $lng1, $lat1)
    {
        $EARTH_RADIUS = 6378137.0;
        $x = ($lng1 - $lng0) * M_PI * $EARTH_RADIUS * cos(($lat0 + $lat1) / 2 * M_PI / 180) / 180;
        $y = ($lat1 - $lat0) * M_PI * $EARTH_RADIUS / 180;
        return sqrt($x * $x + $y * $y);
    }

}