<?php
/**
 * Created by PhpStorm.
 * User: xiaofeng
 * Date: 2018/4/19
 * Time: 下午2:52
 */

namespace frontend\controllers;

use common\models\CategoryAdviser;
use common\models\CategoryLabel;
use common\models\Brand;
use common\models\Characteristic;
use common\models\House;
use common\models\HouseComment;
use common\models\HouseCommentLikes;
use common\models\PushDiscount;
use common\models\Sensitivewords;
use frontend\base\CommonController;
use common\models\Sendcoderecord;
use frontend\server\IndexServer;
use mobile\server\WordMatcher;
use linslin\yii2\curl;
use Yii;
use yii\data\Pagination;
use frontend\server\HouseServer;
use frontend\base\Help;
use yii\helpers\ArrayHelper;
use yii\helpers\VarDumper;

class HouseController extends CommonController
{
    const LOCATIONCITYHOUSE = 'locationcityhouse';


    public function beforeAction($action)
    {
        if (in_array(Yii::$app->controller->action->id, ['home', 'type', 'details', 'album', 'houseremark', 'news'])) {
            $input = Yii::$app->request->get();
            if (!is_numeric($input['hid'])) {
                $input['hid'] = explode('-', Yii::$app->request->get('hid'))[1];
            }
            if (empty((new House())->HouseIsshow($input['hid']))) {
                return $this->redirect('/public/showhouse')->send();
            }
        }
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    /*
     * 楼盘首页
     * */
    public function actionHome()
    {
        $this->on(self::LOCATIONCITYHOUSE, [new \common\fm\HouseHandle(), 'CityLocation']);
        $this->trigger(self::LOCATIONCITYHOUSE);
        $module = Yii::$app->controller->module->id;
        $model = new HouseServer();
        $rows = $model->Details();
        $adviser = (new CategoryAdviser())->GetAdviser();
        if(!empty($rows['house'])){
            Yii::$app->view->params['TargetCrumbs'] = ['url'=>'','title'=>'>'.$rows['house']['name']];
        }

        //指定楼盘使用指定该53客服
        if ( !empty($rows['house']['type']) && in_array(12, json_decode($rows['house']['type'], true))) {
            Yii::$app->hostserver->zhiding_shangwu = true;
            Yii::$app->hostserver->shangwu = '<script>(function() {var _53code = document.createElement("script");_53code.src = "https://www111.53kf.com/code/code/9e0fdd15a7ccf645325b36076f1273231/4";var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(_53code, s);})();</script>';
        }
        return $this->render($this->action->id, [
            'model' => $rows,
            'module'=> $module,
            'adviser' => $adviser,
        ]);
    }


    /*
     * 楼盘列表
     * */
    public function actionSearch()
    {
        $renderData = [];
        $meta = [];  //SEO 关键字
        $CityModel = new \common\models\CategoryCity();
	    $CityModel->abroad = 1;
        $input = Yii::$app->request->get();
        $meta['province'] = '海南省';
        
        if (Yii::$app->hostserver->hostId == 0) {
            $CityModel->pid = 0;
            $CityModel->state = 1;
            $CityModel->abroad = 1;
            $renderData['city'] = $CityModel->getList([], ['city_name', 'id', 'pinyin']);
//            dump($input);die;
            //处理区域 父类
            if (!empty($input['city'])) {
                $pro = $CityModel->FindById($input['city']);

                if ($pro['pid'] == 0)  //父类ID处理方法
                {
                    $meta['province'] = $pro['city_name'];
                    $r = $CityModel->GetAllSon($input['city'], ['city_name', 'id', 'pinyin'], 2);
                    $renderData['city_son'] = $r;
                    if (!empty($r)) {
                        $input['city'] = array_column($r, 'id');
                    }
                } else //子类处理方法
                {
                    $meta['city'] = $pro['city_name'];
                    $father = $CityModel->FindById($pro['pid']);
                    if (!empty($father)) {
                        $meta['province'] = $father['city_name'];
                    }


//                        if(substr_count($pro['path'],',') == 2)
//                        {
//                            $r =  $CityModel->GetAllSon($pro['pid'],['city_name','id','pid','pinyin'],2);
//                            $renderData['city_son'] = $r;
//                        }

                    if ($pro['level'] == 2) {
                        $r = $CityModel->GetAllSon($pro['pid'], ['city_name', 'id', 'pid', 'pinyin'], 2);
                        $renderData['city_son'] = $r;
                    }
                }
            }
        } else {
            $pro = $CityModel->FindById(Yii::$app->hostserver->hostId);

            $meta['province'] = $pro['city_name'];
            $r = $CityModel->GetAllSon(Yii::$app->hostserver->hostId, ['city_name', 'id', 'pid', 'pinyin'], 2);
            $renderData['city_son'] = $r;


            if (!empty($r)) {
                $input['city'] = array_column($r, 'id');
            }

            if (ArrayHelper::keyExists('city', Yii::$app->request->get()) && !empty(Yii::$app->request->get('city'))) {
                $input['city'] = Yii::$app->request->get('city');
            }
        }

        //区分国家,区域为空的情况下,自动获取国外地区,调出楼盘
        if (empty($input['city'])) {
            $CityModel->pid = 0;
            $CityModel->state = 1;
            $CityModel->abroad = 1;
            $mainCity = $CityModel->getList([], ['id']);
            
            if ($mainCity) {
                $city_Id = $CityModel->GetAllSon(array_column($mainCity, 'id'), ['id']);
                
                if (!empty($city_Id)) {
                    $input['city'] = array_column($city_Id, 'id');
                }
            }
        }

        $PriceModel = new \common\models\HousesPrice();
        $renderData['price'] = $PriceModel->getList([], ['id', 'price', 'price_short']);

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

        $zhutiModel = new \common\models\Characteristic();
        $renderData['zhuti'] = $zhutiModel->getList([], ['id', 'name']);
	
	    //物业类型
	    $labelType = new CategoryLabel();
	    $labelType->type = 1;
	    $labelType->state = 1;
	    $renderData['label'] = $labelType->getList([], ['id', 'name']); //物业
	
	    //品牌馆
	    $BrandModel = new Brand();
	    $renderData['brand'] = $BrandModel->getPcSearchBrand(1);
	    
	    // 特色
	    $renderData['characteristic'] = (new Characteristic())->getListAll();
	
	    $IndexModel = new IndexServer();
        $renderData['ctype'] = $IndexModel->Characteristic();
        //处理搜索条件

        $meta['city'] = '';

        $renderData['seo'] = $meta;
        $renderData['post'] = $input; //用于view选中
        $renderData['count'] = 0;
        $model = new HouseServer();
        $rows = $model->Search($input);
        //右侧热销楼盘
        $hothouselist = (new \common\models\House())->HotList(3);
        $renderData['hothouselist'] = $hothouselist;
        if ($rows['data'] != null) {
            $renderData['models'] = $rows['data'];
            $renderData['page'] = $rows['page'];
            $renderData['count'] = $rows['page']->totalCount;
            $renderData['push_discount'] = (new PushDiscount())->getHomeList(1, 4);
            $renderData['push_house'] = (new PushDiscount())->getHomeList(2, 8);
        }
        return $this->render('search', $renderData);
    }


    public function actionAbroad()
    {
        $renderData = [];
        $meta = [];  //SEO 关键字
        $CityModel = new \common\models\CategoryCity();
        $input = Yii::$app->request->get();
        $meta['province'] = '海外房产';
        if (Yii::$app->hostserver->hostId == 0) {
            $CityModel->pid = 0;
            $CityModel->state = 1;
            $CityModel->abroad = 2;
            $renderData['city'] = $CityModel->getList([], ['city_name', 'id', 'pinyin']);

            //处理区域 父类
            if (!empty($input['city'])) {
                $pro = $CityModel->FindById($input['city']);

                if ($pro['pid'] == 0)  //父类ID处理方法
                {
                    $meta['province'] = $pro['city_name'];
                    $r = $CityModel->GetAllSon($input['city'], ['city_name', 'id', 'pinyin']);
                    $renderData['city_son'] = $r;
                    if (!empty($r)) {
                        $input['city'] = array_column($r, 'id');
                    }
                } else //子类处理方法
                {
                    $meta['city'] = $pro['city_name'];
                    $father = $CityModel->FindById($pro['pid']);
                    if (!empty($father)) {
                        $meta['province'] = $father['city_name'];
                    }


                    if (substr_count($pro['path'], ',') == 2) {
                        $r = $CityModel->GetAllSon($pro['pid'], ['city_name', 'id', 'pid', 'pinyin']);
                        $renderData['city_son'] = $r;
                    }
                }
            }
        } else {
            $pro = $CityModel->FindById(Yii::$app->hostserver->hostId);

            $meta['province'] = $pro['city_name'];
            $r = $CityModel->GetAllSon(Yii::$app->hostserver->hostId, ['city_name', 'id', 'pid', 'pinyin']);
            $renderData['city_son'] = $r;


            if (!empty($r)) {
                $input['city'] = array_column($r, 'id');
            }

            if (ArrayHelper::keyExists('city', Yii::$app->request->get()) && !empty(Yii::$app->request->get('city'))) {
                $input['city'] = Yii::$app->request->get('city');
            }
        }

        //区分国家,区域为空的情况下,自动获取国外地区,调出楼盘
        if (empty($input['city'])) {
            $CityModel->pid = 0;
            $CityModel->state = 1;
            $CityModel->abroad = 2;
            $mainCity = $CityModel->getList([], ['id']);
            if ($mainCity) {
                $city_Id = $CityModel->GetAllSon(array_column($mainCity, 'id'), ['id']);
                if (!empty($city_Id)) {
                    $input['city'] = array_column($city_Id, 'id');
                }
            }
        }


        $PriceModel = new \common\models\HousesPrice();
        $renderData['price'] = $PriceModel->getList([], ['id', 'price']);

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

        $zhutiModel = new \common\models\Characteristic();
        $renderData['zhuti'] = $zhutiModel->getList([], ['id', 'name']);

        $IndexModel = new IndexServer();
        $renderData['ctype'] = $IndexModel->Characteristic();
        //处理搜索条件

        $meta['city'] = '';

        $renderData['seo'] = $meta;
        $renderData['post'] = $input; //用于view选中
        $renderData['count'] = 0;
        $model = new HouseServer();
        $rows = $model->Search($input);

        if ($rows['data'] != null) {
            $renderData['models'] = $rows['data'];
            $renderData['page'] = $rows['page'];
            $renderData['count'] = $rows['page']->totalCount;
        }
        return $this->render('abroad', $renderData);
    }

    public function actionVr()
    {
        $renderData = [];
        $meta = [];  //SEO 关键字
        $CityModel = new \common\models\CategoryCity();
        $input = Yii::$app->request->get();
        $meta['province'] = '海南省';
        if (Yii::$app->hostserver->hostId == 0) {
            $CityModel->pid = 0;
            $CityModel->state = 1;
            $CityModel->abroad = 1;
            $renderData['city'] = $CityModel->getList([], ['city_name', 'id', 'pinyin']);

            //处理区域 父类
            if (!empty($input['city'])) {
                $pro = $CityModel->FindById($input['city']);

                if ($pro['pid'] == 0)  //父类ID处理方法
                {
                    $meta['province'] = $pro['city_name'];
                    $r = $CityModel->GetAllSon($input['city'], ['city_name', 'id', 'pinyin']);
                    $renderData['city_son'] = $r;
                    if (!empty($r)) {
                        $input['city'] = array_column($r, 'id');
                    }
                } else //子类处理方法
                {
                    $meta['city'] = $pro['city_name'];
                    $father = $CityModel->FindById($pro['pid']);
                    if (!empty($father)) {
                        $meta['province'] = $father['city_name'];
                    }


                    if (substr_count($pro['path'], ',') == 2) {
                        $r = $CityModel->GetAllSon($pro['pid'], ['city_name', 'id', 'pid', 'pinyin']);
                        $renderData['city_son'] = $r;
                    }
                }
            }
        } else {
            $pro = $CityModel->FindById(Yii::$app->hostserver->hostId);

            $meta['province'] = $pro['city_name'];
            $r = $CityModel->GetAllSon(Yii::$app->hostserver->hostId, ['city_name', 'id', 'pid', 'pinyin']);
            $renderData['city_son'] = $r;


            if (!empty($r)) {
                $input['city'] = array_column($r, 'id');
            }

            if (ArrayHelper::keyExists('city', Yii::$app->request->get()) && !empty(Yii::$app->request->get('city'))) {
                $input['city'] = Yii::$app->request->get('city');
            }
        }

        //区分国家,区域为空的情况下,自动获取国外地区,调出楼盘
        if (empty($input['city'])) {
            $CityModel->pid = 0;
            $CityModel->state = 1;
            $CityModel->abroad = 1;
            $mainCity = $CityModel->getList([], ['id']);
            if ($mainCity) {
                $city_Id = $CityModel->GetAllSon(array_column($mainCity, 'id'), ['id']);
                if (!empty($city_Id)) {
                    $input['city'] = array_column($city_Id, 'id');
                }
            }
        }

        $PriceModel = new \common\models\HousesPrice();
        $renderData['price'] = $PriceModel->getList([], ['id', 'price']);

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

        $zhutiModel = new \common\models\Characteristic();
        $renderData['zhuti'] = $zhutiModel->getList([], ['id', 'name']);

        $IndexModel = new IndexServer();
        $renderData['ctype'] = $IndexModel->Characteristic();
        //处理搜索条件

        $meta['city'] = '';

        $renderData['seo'] = $meta;
        $renderData['post'] = $input; //用于view选中
        $renderData['count'] = 0;
        $model = new HouseServer();
        $rows = $model->Search($input);

        if ($rows['data'] != null) {
            $renderData['models'] = $rows['data'];
            $renderData['page'] = $rows['page'];
            $renderData['count'] = $rows['page']->totalCount;
        }
        return $this->render('vr', $renderData);
    }

    /*
     * 获取楼盘户型分组和分组总数
     * */
    public function actionType()
    {
        $model = new HouseServer();
        $publiHouse = $model->PublicDetails();
        $type = $model->Type();
        $count = 0;
        if (!empty($type)) {
            foreach ($type as &$val) {
                $count += $val['num'];
            }
        }
        $input['hid'] = Yii::$app->request->get('hid');
        $input['type_id'] = Yii::$app->request->get('type_id', '');
        $rows = $model->TypeAll($input, false);

        $IndexModel = new IndexServer();
        $hotHouse = $IndexModel->HotHouse();  //热销楼盘

        return $this->render('type', ['post' => Yii::$app->request->get(), 'public' => $publiHouse, 'grouptype' => $type,
            'count' => $count, 'typeimg' => $rows, 'selecttype' => Yii::$app->request->get('type_id', ''), 'hotHouse' => $hotHouse]);
    }

    /*
     * 楼盘首页-户型分组后的数据
     * */
    public function actionHousetype()
    {
        $model = new HouseServer();
        $rows = $model->TypeAll(Yii::$app->request->post(), true);
        
        if ($rows != null) {
            return Help::JsonCode(Help::SUCCESS, '成功', $rows);
        }
        return Help::JsonCode(Help::ERROR, '暂无楼盘户型图数据');
    }

    /*
     * 楼盘户型数据
     * */
    public function actionHousetypeall()
    {
        $model = new HouseServer();
        $result = $model->TypeAll(Yii::$app->request->post(), false);
        $IndexModel = new IndexServer();
        $rows['types'] = $result;
        $rows['hotHouse'] = $IndexModel->HotHouse();  //热销楼盘
        if ($rows != null) {
            return Help::JsonCode(Help::SUCCESS, '成功', $rows);
        }
    }


    /*
     * 楼盘首页-楼盘动态
     * */
    public function actionDynamic()
    {
        $model = new HouseServer();
        $rows = $model->NewsDynamic(Yii::$app->request->post());
        if ($rows != null) {
            return Help::JsonCode(Help::SUCCESS, '成功', $rows);
        }
        return Help::JsonCode(Help::ERROR, '失败');
    }

    /*
     * 楼盘详细信息
     * */
    public function actionDetails()
    {
        $model = new HouseServer();
        $publiHouse = $model->PublicDetails();
//            p($publiHouse);
        $rows = $model->ParamsDetails();
        return $this->render('details', ['public' => $publiHouse, 'model' => $rows]);
    }

    /*
     * 楼盘资讯
     * */
    public function actionNews()
    {

        $model = new HouseServer();

        $publiHouse = $model->PublicDetails();
        $news = $model->HouseNewsList();

        $IndexModel = new IndexServer();

        $hotHouse = $IndexModel->HotHouse();            //热销楼盘
        //大家都在看
        $query = \common\models\News::find();
        $query->select('subject,id');
        $query->limit = 10;
        $newsClick = $query->orderBy(['clicks' => SORT_DESC])->asArray()->all();
//		dump($news);die;
        return $this->render('news', ['public' => $publiHouse, 'news' => $news, 'hotHouse' => $hotHouse, 'newsClick' => $newsClick]);
    }

    public function actionPeriphery()
    {
        return $this->render('periphery');
    }
    
    

    /*
     * 楼盘相册页面
     * */
    public function actionAlbum()
    {
        $model = new HouseServer();
        $publiHouse = $model->PublicDetails();
//        $album = $model->Album();
        $album = $model->Album();
//		p($album);die;
        return $this->render('album', ['public' => $publiHouse, 'album' => $album]);
    }
	
	/**
	 * 楼盘户型详情
	 * @return int|mixed|string|\yii\console\Response
	 * @throws \yii\base\InvalidRouteException
	 * @throws \yii\console\Exception
	 */
	public function actionTypedetails()
	{
		$model = new HouseServer();
		$publiHouse = $model->PublicDetails();
		//楼盘相关户型信息
		$model = new HouseServer();
		$input = Yii::$app->request->get();
		$input['type_id'] = 'all';
		
		$typelist = $model->TypeAll($input,false);
		
		return $this->render('typedetails',['public'=>$publiHouse,'data'=>$typelist]);
	}

    /*
     * 楼盘所有相册
     * */
    public function actionAlbumlist()
    {
        $model = new HouseServer();

        $album = $model->AlbumAll();
        if ($album != null) {
            return Help::JsonCode(Help::SUCCESS, '成功', $album);
        }
    }

    /*
     * 楼盘相册获取
     * */
    public function actionGetalbumlist()
    {

        $model = new HouseServer();
        $album = $model->GetAlbumAll(Yii::$app->request->get());
        if ($album != null) {
            return Help::JsonCode(Help::SUCCESS, '成功', $album);
        }
    }

    /*
     * 楼盘首页底部---推荐楼盘 同价位楼盘 同区域楼盘
     * */
    public function actionTall()
    {
        $model = new HouseServer();
        $res = $model->distinguishHouse(Yii::$app->request->post());
        if (!empty($res)) {
            return Help::JsonCode(Help::SUCCESS, '成功', $res);
        }
    }

    // 楼盘点评(废弃)
    public function actionRemark()
    {
//            $m = new \common\models\House();
//            if(empty($m->HouseIsshow(Yii::$app->request->get('hid'))))
//            {
//                return  Yii::$app->runAction('public/showhouse');
//            }
//
//            $model = new HouseServer();
//            $publiHouse = $model->PublicDetails();
//
//            $album = $model->Album();
//            return $this->render('remark',['public'=>$publiHouse,'album'=>$album]);
    }


    public function actionRemarkfrom()
    {
        $input = Yii::$app->request->post();
        $model = new HouseComment();
        $input['ip'] = Yii::$app->request->userIP;

        $wordMatcher = new WordMatcher();
        $sensitivewords = new Sensitivewords();
        $senWordsInfo = $sensitivewords->getList();
        $list = explode("、", $senWordsInfo['info']);
        foreach ($list as $val) {
            $wordMatcher->addWord($val);
        }
        $wordMatcher->match($input['content'], $matched);
        if (!empty($matched)) {
            return Help::JsonCode(Help::ERROR, '点评内容存在敏感词汇', $matched);
        }
        $true = $model->Iplimit($input);
        if ($true === false) return Help::JsonCode(Help::ERROR, '一个楼盘最多只能点评2次');
        $input['initiator'] = 2;
        $input['is_show'] = 2;
        if ($model->load($input, '') && $model->save()) {
            $curlArr = array(
                "mobile" => $input['mobile'],
                "source" => $input['source'],
                "equipment" => 2,
                "hid" => $input['hid'],
            );
            $curl = new curl\Curl();
            $url = 'http://www.yigouf.com/enroll/signup';
            $response = $curl->reset()->setOption(CURLOPT_POSTFIELDS, http_build_query($curlArr))->post($url);
            return Help::JsonCode(Help::SUCCESS, Yii::t('app', '点评成功'));
        }
        return Help::JsonCode(Help::ERROR, Yii::t('app', '点评失败'), $model->errors);
    }

    public function actionRemarklikesfrom()
    {
        $input = Yii::$app->request->post();
        $model = new HouseCommentLikes();
        $input['ip'] = Yii::$app->request->userIP;
        $true = $model->Iplimit($input);
        if ($true === false) return Help::JsonCode(Help::ERROR, '一条点评最多只能赞一次');

        if ($model->load($input, '') && $model->save()) {
            $model->hid = $input['hid'];
            $model->hcid = $input['hcid'];
            $total = $model->Total();
            return Help::JsonCode(Help::SUCCESS, Yii::t('app', 'add_success'), $total);
        }
        return Help::JsonCode(Help::ERROR, Yii::t('app', 'add_error'), $model->errors);
    }

    // 楼盘点评
    public function actionHouseremark()
    {
        $input = Yii::$app->request->get();

        $model = new HouseServer();
        $houseComment = new HouseComment();
        $rows = $model->Details();
        $publiHouse = $model->PublicDetails();
//            $album = $model->Album();
//            ,'album'=>$album
        $getHouseList = $model->getHouseRemarkList($input, 10);
        $houseComment->hid = $input['hid'];
        $getHouseListTotal = $houseComment->getHouseListTotal();
        return $this->render('houseremark', ['model' => $rows, 'hid' => Yii::$app->request->get('hid'), 'xuqiu' => $houseComment->xuqiu, 'commentList' => $getHouseList, 'getHouseListTotal' => $getHouseListTotal, 'public' => $publiHouse]);
    }


    public function actionSendcode()
    {
        $input = Yii::$app->request->post();
        $input['purpose'] = '视频播放验证';
        $smsServer = new \frontend\server\SendCode();

        return $smsServer->send($input);
    }

    public function actionCheckcode()
    {
        $input = Yii::$app->request->post();

        $session = Yii::$app->session;
        $skey = 'live_' . $input['mobile'];
        if (empty($session[$skey])) {
            return Help::JsonCode(Help::ERROR, '请输入正确手机号');
        }
        //验证码有效期5分钟
        if ($session[$skey]['expire_time'] < time()) {
            return Help::JsonCode(Help::ERROR, '验证码已失效');
        }
        if ($input['code'] != $session[$skey]['code']) {
            return Help::JsonCode(Help::ERROR, '验证码不正确');
        }

        Yii::$app->session->set('adopt', $input['mobile']);
        if (!empty(Yii::$app->session['adopt']) && !empty(Yii::$app->session[$skey])) {
            $record = Sendcoderecord::find()->andWhere(['mobilephone' => $input['mobile'], 'code' => $session[$skey]['code']])->one();
            $record->status = 2;
            $record->save();
        }

        return Help::JsonCode(Help::SUCCESS, '验证通过');//验证通过继续播放视频
    }

    // 众趣播放页面
    public function actionZhongqu()
    {
        $input = Yii::$app->request->get();
        $url = '#';
        if (!empty($input['h'])) {
            $url = $input['h'];
        }
        return $this->render('zhongqu', ['url' => $url]);
    }
}