<?php

namespace wechat\server;

use common\models\Developers;
use common\models\House;
use common\models\HouseAlbum;
use common\models\HouseComment;
use common\models\HouseCommentLikes;
use common\models\HouseCommentreply;
use common\models\Search;
use wechat\base\Help;
use Yii;
use common\models\HouseNews;
use common\models\CategoryLabel;
use common\models\HousePermit;
use common\models\HouseType;

class HouseServer{


    public static function Search($abroad = 1)
    {
        //搜索内容
        $renderData = [];
        $CityModel = new \common\models\CategoryCity();
        $CityModel->pid = 0;
        $CityModel->state = 1;
        if(Yii::$app->hostserver->hostId != 0)
        {
            $CityModel->pid = Yii::$app->hostserver->hostId;
        }else{
            $CityModel->abroad = $abroad;
        }
//        $renderData['city'] = $CityModel->getList([],['city_name','id']);
        $renderData['city'] = $CityModel->getList([],['city_name','id','pinyin']);
//            p($renderData);
        $input = Yii::$app->request->get();
        if(!empty($input['city']))
        {
            $renderData['select_city'] =  $CityModel->FindById($input['city']);
        }
        $PriceModel = new \common\models\HousesPrice();
        $renderData['price'] = $PriceModel->getList([],['id','price']);

        if(!empty($input['price']))
        {
            $renderData['select_price'] = $input['price'];
        }

        $TypeModel = new \common\models\CategoryHousetype();
        $renderData['type'] = $TypeModel->getList([],['id','huxing_name']);

        if(!empty($input['type']))
        {
            $renderData['select_type'] =  $TypeModel->FindById($input['type']);
        }
        $zhutiModel = new \common\models\Characteristic();
        $renderData['zhuti'] = $zhutiModel->getList([],['id','name']);
        if(!empty($input['characteristic']))
        {
            $renderData['select_zhuti'] = $zhutiModel->FindById($input['characteristic']);
        }
        return $renderData;
    }

    //搜索
    public function SearchForm($input)
    {
        $query = new House();

        if(!empty($input['price']))
        {
            $query->price = $input['price'];
        }


        if(!empty($input['characteristic']))
        {
            $query->characteristic = $input['characteristic'];
        }

        if(!empty($input['name']))
        {
            $query->name = $input['name'];
        }

        //处理区域
        if(!empty($input['city']))
        {
            $CityModel = new \common\models\CategoryCity();
            $pro = $CityModel->FindById($input['city']);
            if($pro['pid'] == 0)
            {
                $r =  $CityModel->GetAllSon($input['city'],['city_name','id']);
                if(!empty($r))
                {
                    $input['city'] = array_column($r,'id');
                }
            }
            $query->city = $input['city'];
        }
        else if(empty($input['city']) && Yii::$app->hostserver->hostId !=0)
        {
            $query->city = (new \common\models\CategoryCity())->TestingId(Yii::$app->hostserver->hostId);
        }else  if(empty($input['city']))
        {
            $CityModel = new \common\models\CategoryCity();
            $CityModel->pid = 0;
            $CityModel->state = 1;
            $CityModel->abroad = $input['abroad'];
            $mainCity = $CityModel->getList([],['id']);
            if($mainCity)
            {
                $city_Id = $CityModel->GetAllSon(array_column($mainCity,'id'),['id']);
                if(!empty($city_Id))
                {
                    $query->city = array_column($city_Id,'id');
                }
            }
        }

        if(!empty($input['type']))
        {
            $type = \common\models\HouseType::find();
            $typeModel = $type->andWhere(['type_id'=>$input['type'],'del'=>1])->asArray()->all();
            if(!empty($typeModel))
            {
                $query->id = array_unique(array_column($typeModel,'hid'));
            }else{
                $query->id = 0;
            }
        }

        if(!empty($input['name']))
            {
                $arr = (new \common\api\HouseServer())->HouseNameConvert($input['name']);
                if(!empty($arr['pinyin']))
                {
                    $query->pinyin = $arr['pinyin'];
                }
                if(!empty($arr['zhongwen']))
                {
                    $query->name = $arr['zhongwen'];
                }
                $query->city = '';
            }

        if (!empty($input['hao'])){
            $data = $query->PcHouseList($input,['pfg_house.area','pfg_category_city.city_name','pfg_house.id','pfg_house.is_tel','pfg_house.city','pfg_house.price','pfg_house.name','pfg_house_detail.address','pfg_house_detail.developers','pfg_house_detail.main_units','pfg_house_detail.price_unit','pfg_house.thumb','pfg_house.sale_price','pfg_house.characteristic','pfg_pushm_mansion.haoqi','pfg_pushm_mansion.jingmi','pfg_pushm_mansion.reason','pfg_pushm_mansion.img as hao_img','pfg_developers.logo']);
        }else{

            $data = $query->PcHouseList($input,['pfg_house.area','pfg_category_city.city_name','pfg_house.id','pfg_house.is_tel','pfg_house.city','pfg_house.price','pfg_house.name','pfg_house_detail.address','pfg_house_detail.main_units','pfg_house_detail.price_unit','pfg_house.thumb','pfg_house.sale_price','pfg_house.characteristic','pfg_house.click_num']);
        }
        //豪宅总数
        if (!empty($input['hao'])){
            $count = $query->Count_Mansion();
        }else{
            //正常数据的整数
            $count = $query->PcHouseListTotal();
        }

        if($count<1)
        {
            $count = 0;
        }
        if($data != null) {

//            $Tel = new \common\models\CategoryTelCity();
//            $telRow = $Tel->QgetAll();
//
//            $cityTel = [];
//            foreach ($telRow as &$v) {
//                $cityTel[$v['cid']] = explode(',', $v['tel']);
//            }

            $randArr = [];
            foreach ($data as &$val) {
                if($val['click_num'] < 100)
                {
                    $val['click_num'] = rand(200,900);
                }
                $val['thumb'] = Yii::$app->params['httpImg']['hosts'].Yii::$app->params['httpImg']['houses'].$val['thumb'];
                if (!empty($val['hao_img'])){
                    $val['hao_img'] = $imgUrl = Yii::$app->params['httpImg']['host'].Yii::$app->params['httpImg']['housealbum'] . $val['hao_img'];
                }
                if (!empty($val['logo'])){
                    $val['logo'] = $imgUrl = Yii::$app->params['httpImg']['host'].Yii::$app->params['httpImg']['developers'] . $val['logo'];
                }
                $val['characteristic'] = \common\fm\HouseHandle::ChangeCharacteristic($val['characteristic']);


                $val['citytel'] = \common\fm\HouseHandle::ChangeCityTel($val['city']);

                if(empty($val['is_tel']))
                {
                    if(!empty($val['area']) && \common\fm\HouseHandle::ChangeCityTel($val['area']) != Yii::$app->params['default_dialtel']){

                        $val['citytel'] = \common\fm\HouseHandle::ChangeCityTel($val['area']);
                    }else{
                        $val['citytel'] = \common\fm\HouseHandle::ChangeCityTel($val['city']);
                    }

//                    $val['citytel'] = \common\fm\HouseHandle::ChangeCityTel($val['city']);
                }
                else {
                    $val['citytel'] = $val['is_tel'];
                }





                //                if (isset($cityTel[$val['city']])) {
//                    $rand = array_rand($cityTel[$val['city']], 1);
//                    $val['citytel'] = $cityTel[$val['city']][$rand];
//
//                } else {
//                    $val['citytel'] = Yii::$app->params['default_dialtel'];
//                }
            }
			return ['data'=>$data,'count'=>$count];
        }
    }

    /*
     * 搜索楼盘名字
     * */
    public function SearchHouseName($input)
    {
        if(!empty($input['title']))
            {
                (new Search())->SaveSearch($input['title']);
                $query = new House();
                $arr = (new \common\api\HouseServer())->HouseNameConvert($input['title']);
                if(!empty($arr['pinyin']))
                {
                    $query->pinyin = $arr['pinyin'];
                }
                if(!empty($arr['zhongwen']))
                {
                    $query->name = $arr['zhongwen'];
                }

                $result = $query->HouseName();

                return $result;
            }
    }
    
    public function Details()
    {
        $input = Yii::$app->request->get();
        if(isset($input['hid']) && is_numeric($input['hid']))
        {
            //楼盘点击量
            $click = new \common\api\HouseServer();
            $click->HouseClick($input['hid']);

            $arr = [];
            //所有信息,后期优化显示字段
            $model = new House();
            $model->id = $input['hid'];
            $select = ['pfg_house.*','pfg_house_detail.*','pfg_category_city.city_name'];
            $arr['house'] = $model->Qdetails($select);
//            $arr['house']['info'] = strip_tags($arr['house']['info']);

            //楼盘点击量
            if(!empty($arr['house']))
            {
                //特色主题
//                $sub = new IndexServer();
//                $arr['characteristic'] = $sub->Subject(json_decode($arr['house']['characteristic']),3);
                if(isset($arr['house']['characteristic']))
                {
                    $arr['characteristic'] = \common\fm\HouseHandle::ChangeCharacteristic($arr['house']['characteristic']);
                }

                //楼盘相册
                $queryAlbum = new  HouseAlbum();
                $arr['album'] = $queryAlbum->Groupfind_Total(['hid'=>$input['hid']],4);

                //楼盘户型
                $queryType = new  \common\models\HouseType();
                $queryType->hid = $input['hid'];
                $arr['type'] =  $queryType->MgetList(2,['area','title','img','indoor_info']);
                //电话
//                $arr['house']['tel'] = $sub->RandTel(  $arr['house']['city']);

//                $arr['house']['tel'] = \common\fm\HouseHandle::ChangeCityTel($arr['house']['city']);
//                if(empty($arr['house']['is_tel']))
//                {
//                    $arr['house']['tel'] = \common\fm\HouseHandle::ChangeCityTel($arr['house']['city']);
//                }
//                else
//                {
//                    $arr['house']['tel'] = $arr['house']['is_tel'];
//                }

//                $arr['house']['tel'] = Yii::$app->params['default_dialtel'];

                $arr['house']['tel'] = \common\fm\HouseHandle::ChangeCityTel($arr['house']['city']);

                if(empty($arr['house']['is_tel']))
                {
                    //新增三级联动区域的电话获取修改
                    if(!empty($arr['house']['area']) && \common\fm\HouseHandle::ChangeCityTel($arr['house']['area']) != Yii::$app->params['default_dialtel']){
                        $arr['house']['tel'] = \common\fm\HouseHandle::ChangeCityTel($arr['house']['area']);
                    }else{
                        $arr['house']['tel'] = \common\fm\HouseHandle::ChangeCityTel($arr['house']['city']);
                    }

                }
                else
                {
                    $arr['house']['tel'] = $arr['house']['is_tel'];
                }

                $arr['house']['info'] = strip_tags($arr['house']['info']);

                //预售证书
                $certificate = new \common\models\HousePermit();
                $certificate->hid = $input['hid'];
                $arr['certificate'] = $certificate->FindNewest();
                //楼盘状态
                $arr['house']['state'] =Yii::$app->params['HouseSalesStatus'][$arr['house']['state']];
                //新闻
                $arr['news'] = $this->NewsDynamic($input);

                //推荐楼盘
                $model = new \common\models\House();
                $model->city = $arr['house']['city'];
                $model->is_push = 2;
                $arr['tuijian_house'] = $model->randList(3,['house_id'=>$arr['house']['id']]);

                if(!empty($arr['tuijian_house']))
                {
                    foreach($arr['tuijian_house'] as &$val)
                    {
                         $val['characteristic'] = \common\fm\HouseHandle::ChangeCharacteristic($val['characteristic']);
                        $val['tel'] = \common\fm\HouseHandle::ChangeCityTel($val['city']);
                        $val['thumb'] = Yii::$app->params['httpImg']['hosts'].Yii::$app->params['httpImg']['houses'].$val['thumb'].'/'.'same';
                    }
                }

				//楼盘点评
                $arr['remark'] = $this->getHouseRemarkList($input,2);

                return $arr;
            }
        }
    }

    public function NewsDynamic($input)
    {
        $model = new HouseNews();
        $model->hid =$input['hid'];
        $rows = $model->QgetNews(2);
        if($rows != null)
        {
            return $rows;
        }
    }

    //楼盘详情页数据
    public function ParamsDetails()
    {
        $input = Yii::$app->request->get();
        if(is_numeric($input['hid']))
        {
            $result = [];
            $model = new House();
            $model->id = $input['hid'];
            $result['house'] = $model->HousesAll();
            if($result['house'])
            {
                $sub = new IndexServer();
                $result['house']['characteristic'] = $sub->Subject(json_decode($result['house']['characteristic']),3);
                $result['house']['tel'] = $sub->RandTel($result['house']['city']);
                $result['house']['architecture_type'] = $this->ArchitectureType(json_decode($result['house']['architecture_type']));

                //预售证号
                $zheng = new HousePermit();
                $result['house']['zhengshu'] =$zheng->getList($input);
                return $result;
            }


            //价格历史
//                $price = new HousePriceRecord();
//                $price->hid =  $input['hid'];
//                $result['house']['price_record'] = $price->getList([]);

            //                p(   $result['house']['price_record']);
//                $peitao = new HouseFacilities();
//                $peitao->hid = $input['hid'];
//                $pei  = $peitao->InfoList();
//                if(!empty($pei))
//                {
//                    $peiArr = [];
//                    foreach ($pei as $key=>$val)
//                    {
//                        $peiArr[$val['name']]['name'][] = $val['pname'];
//                    }
//                    $result['peitao'] = $peiArr;
//                }

        }
    }

    /*
     * 建筑类别
     * */
    public function ArchitectureType($id)
    {
       if(!empty($id))
       {
           $model = new CategoryLabel();

           $model->id = $id;
           $model->type = 2;
           $rows =  $model->getList([],['name']);
           if(!empty($rows))
           {
               return array_column($rows,'name');
           }
       }
            return [];
    }

    /*
     * 楼盘户型-分组
     * */
    public function HouseType()
    {
        $input = Yii::$app->request->get();
        $typeModel = new HouseType();
        $typeModel->hid =$input['hid'];
        $groupType = $typeModel->TypeGroup();
        return $groupType;
    }

    //楼盘户型分组数据
    public function HouseTypeGroupAll($input)
    {
        if(!empty($input['hid']) && !empty($input['type_id']))
        {
            $typeModel = new HouseType();
            $typeModel->hid = $input['hid'];
            $typeModel->type_id = $input['type_id'];
            $list = $typeModel->QgetList();
            if($list != null)
            {
                foreach ($list as &$val)
                {
                    $val['img'] = Yii::$app->params['httpImg']['hosts'].Yii::$app->params['httpImg']['housetypes'].$val['img'].Yii::$app->params['pfgwatermark'];
                }
            }
            return $list;
        }
    }

    //获取楼盘相册逻辑
    public function HouseAlbum()
    {
        $input = Yii::$app->request->get();


        \common\models\House::find();
        $queryAlbum = new  HouseAlbum();
        $arr = $queryAlbum->AlbumGroup(['hid'=>$input['hid']]);
        return $arr;
    }

    //获取楼盘分类的所有相册信息
    public function HouseAlbumAll()
    {
        $input = Yii::$app->request->post();
        if(!empty($input['hid']) && is_numeric($input['hid']))
        {
            $queryAlbum = new  HouseAlbum();
            $queryAlbum->hid = $input['hid'];
            $queryAlbum->album_id = $input['album_id'];
            $rows = $queryAlbum->getList();
            if($rows)
            {
                foreach($rows as &$val)
                {
                    $val['img'] = Yii::$app->params['httpImg']['hosts']. Yii::$app->params['httpImg']['housealbums'].$val['img'].Yii::$app->params['pfgwatermark'];
                }
                return $rows;
            }
        }
    }



        //楼盘资讯
        public function HouseNewsList()
        {
            $input = Yii::$app->request->get();
            if(is_numeric($input['hid']))
            {
                $model = new HouseNews();
                $model->hid = $input['hid'];
                $result  = $model->AllHouseNews();



                //            foreach ($result as &$val)
                //            {
                //                $time_int = strtotime($val['open_time']);
                //
                //                $val['y'] = date('Y',$time_int);
                //                $val['md'] = date('m-d',$time_int);
                //                $val['thumb'] =  json_decode($val['thumb']);
                //            }
                return $result;
            }
        }




        public function getHouseRemarkList($input,$page){

            $houseComment = new HouseComment();
            $houseCommentLikes = new HouseCommentLikes();
            $houseCommentReply = new HouseCommentreply();
            $houseComment->hid = $input['hid'];
            $houseCommentList = $houseComment->getHouseList($page);

            if($houseCommentList != null)
            {
                foreach($houseCommentList  as &$value){
                    $value['allremark'] = floor(($value['diduan']+$value['jiaotong']+$value['peitao']+$value['huanjing']+$value["xingjiabi"])/5);
                    $value['mobile'] = preg_replace("/(\d{3})\d{4}(\d{2})/","\$1******\$3",$value['mobile']);
                    
                    $houseCommentLikes->hid = $value['hid'];
                    $houseCommentLikes->hcid = $value['id'];
                    $value['count_likes'] = $houseCommentLikes->Total();
                    $value['reply'] = $houseCommentReply->getCommentReply($value['id']);
                }
                return $houseCommentList;
            }
        }
}