<?php


namespace mobile\controllers;

use common\fm\HouseHandle;
use common\models\CategoryCity;
use common\models\CategoryTelCity;
use common\models\Characteristic;
use common\models\House;
use common\models\HousePermit;
use common\models\News;
use common\models\PushHothouse;
use mobile\base\Help;
use mobile\base\BaseController;
use mobile\server\HouseServer;
use mobile\server\IndexServer;
use Yii;


class JsonController extends BaseController
{
    /**
     * @var bool
     */
    public $enableCsrfValidation = false;

    
    /**
     * 移动首页热销楼盘
     * @return mixed
     */
    public function actionGethousem()
    {
//        $hothouse = (new PushHothouse())->getHotHouse(2, 4);
	    $hothouse = (new IndexServer())->getHotHouse(13,6);
        if (!empty($hothouse)) {
            return Help::JsonCode(Help::SUCCESS, '成功', $hothouse);
        }
        return Help::JsonCode(Help::ERROR, '暂无数据');
    }

    /**
     * 楼盘列表
     * @return mixed
     */
    public function actionSearchdata()
    {
        $model = new HouseServer();
        $input = Yii::$app->request->get();
        $rows = $model->SearchForm($input);
        if (!empty($rows['data'])) {
            return Help::JsonData(Help::SUCCESS, '成功', $rows['count'], $rows['data']);
        }
        return Help::JsonCode(Help::ERROR, '暂无相关楼盘数据');
    }

    /**
     * 获取区域子类信息
     * @return mixed
     */
    public function actionSoncity()
    {
        $CityModel = new CategoryCity();
        $r = $CityModel->GetAllSon(Yii::$app->request->post('pid'), ['city_name', 'id', 'pinyin', 'pid'], 2);
        return Help::JsonCode(Help::SUCCESS, '成功', $r);
    }


    /**
     * @return mixed
     * 获取楼盘ID,返回楼盘预售证书信息
     */
    public function actionLicence()
    {
        $input = Yii::$app->request->post();
        if (!empty($input['hid'])) {
            $model = new HousePermit();
            $rows = $model->getList($input);
            if ($rows != null) {
                return Help::JsonCode(Help::SUCCESS, '成功', $rows);
            }
        }
        return Help::JsonCode(Help::ERROR, '失败');
    }

    /**
     * 楼盘所有相册
     * @return mixed
     */
    public function actionAlbumlist()
    {
        $model = new HouseServer();
        $rows = $model->HouseAlbumAll();
        if (!empty($rows)) {
            return Help::JsonCode(Help::SUCCESS, '成功', $rows);
        }
        return Help::JsonCode(Help::ERROR, '暂无楼盘相册信息');
    }

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


    /**
     * 首页-底部 拨打电话图标
     * @return mixed
     */
    public function actionTelrand()
    {
        $input = Yii::$app->request->post();
        //没有选择区域的情况下
        if (empty($input['city']) || $input['city'] == 0) {
            //调取广东的电话
            $tel = new CategoryTelCity();
            $tel->cid = 68;
            $resultTel = $tel->CityTelOne();
            if (!empty($resultTel)) {
                $telArr = explode(',', $resultTel['tel']);
                $index = array_rand($telArr, 1);
                if (!empty($telArr[$index])) {
                    return Help::JsonCode(Help::SUCCESS, '成功', ['tel' => $telArr[$index]]);
                }
            }
        }

        //有选择区域的情况下
        if (!empty($input['city']) && $input['city'] != 0) {
            $city = CategoryCity::findOne($input['city']);
            $tel = new CategoryTelCity();
            $tel->cid = $input['city'];

            //选择的是省
            if ($city['pid'] == 0) {
                $resultTel = $tel->CityTelOne();
                if (!empty($resultTel)) {
                    $telArr = explode(',', $resultTel['tel']);
                    $index = array_rand($telArr, 1);
                    if (!empty($telArr[$index])) {
                        return Help::JsonCode(Help::SUCCESS, '成功', ['tel' => $telArr[$index]]);
                    }
                }
            }

            //选择的是市县
            if ($city['pid'] != 0) {
                $resultTel = $tel->CityTelOne();
                if (!empty($resultTel)) {
                    $telArr = explode(',', $resultTel['tel']);
                    $index = array_rand($telArr, 1);
                    if (!empty($telArr[$index])) {
                        return Help::JsonCode(Help::SUCCESS, '成功', ['tel' => $telArr[$index]]);
                    }
                } else { //如果为空,返回省的电话
                    $telmodel = new CategoryTelCity();
                    $telmodel->cid = $city['pid'];
                    $result = $telmodel->CityTelOne();
                    if (!empty($result)) {
                        $telArr = explode(',', $result['tel']);
                        $index = array_rand($telArr, 1);
                        if (!empty($telArr[$index])) {
                            return Help::JsonCode(Help::SUCCESS, '成功', ['tel' => $telArr[$index]]);
                        }
                    }
                }
            }
        }

        return Help::JsonCode(Help::SUCCESS, '成功', ['tel' => Yii::$app->params['default_dialtel']]);
    }

    /**
     * 楼盘名称搜索
     * @return mixed
     */
    public function actionSearchname()
    {
        $model = new HouseServer();
        $row = $model->SearchHouseName(Yii::$app->request->get());
        if (!empty($row)) {
            return Help::JsonCode(Help::SUCCESS, '成功', $row);
        }
        return Help::JsonCode(Help::ERROR, '暂无搜索数据');
    }

    /**
     * 楼盘首页底部-推荐楼盘 同价位楼盘 周边楼盘
     * @return mixed
     */
    public function actionTall()
    {
        $model = new House();
        $input = Yii::$app->request->post();
        if (!empty($input['city'])) {
            $model->city = $input['city'];
        }
        if ($input['price'] == 0) {
            $input['price'] = "";
        }
        $rows = $model->randList(3, $input);
        if (count($rows) < 3) { // start 20181019 当同地区同价格楼盘小于3
            $cityModel = new CategoryCity();
            $parentCity = $cityModel->CityIdentical($input['city']);
            $cityId = array_column($parentCity, 'id');
            $key = array_search($input['city'], $cityId);
            unset($cityId[$key]);
            $model->city = $cityId;
            $row = $model->randList(2, $input);
            $rows = array_merge($rows, $row);
        }
        if (!empty($rows)) {
            foreach ($rows as &$val) {
                $val['characteristic'] = HouseHandle::Subject(json_decode($val['characteristic']), 3);
                $val['tel'] = HouseHandle::RandTel($val['city']);
                $val['thumb'] = Yii::$app->params['httpImg']['hosts'] . Yii::$app->params['httpImg']['housesch'] . $val['thumb'] . '/same';
                $val['state'] = Yii::$app->params['HouseSalesStatus'][$val['state']];
            }
            return Help::JsonCode(Help::SUCCESS, '成功', $rows);
        }

    }

    /**
     * 传入父ID获取子城市
     * @return mixed
     */
    public function actionGetcity()
    {
        $model = new CategoryCity();
        $input = Yii::$app->request->post();
        $model->pid = $input['city'];
        $rows = $model->getList([], ['id', 'city_name', 'll']); //获取所有子类
        $rows = $this->houseCount($rows);
        if (!empty($rows)) return Help::JsonCode(Help::SUCCESS, Yii::t('app', 'get_success'), $rows);
    }

    /**
     * 地图找房
     * @param $city
     * @return bool
     */
    private function houseCount($city)
    {
        if (!is_array($city)) return false;
        $rows = [];
        $input = [];
        $cityId = array_column($city, 'id');
        $query = House::find();
        $query->select(["count('city') as num", 'city']);
        $query->andWhere(['city' => $cityId]);
        $query->andWhere(['del' => 1]);
        $query->andWhere(['is_view' => 1]);
        $query->groupBy('city');
        $cityCount = $query->asArray()->all();
        if ($cityCount) {
            $cityRows = array_column($cityCount, 'num', 'city');
            foreach ($city as &$val) {
                $val['number'] = isset($cityRows[$val['id']]) ? $cityRows[$val['id']] : 0;
                $val['point'] = $val['ll'];
                $val['name'] = $val['city_name'];
            }
            return $city;
        }
        return false;
    }

    /**
     * 地图找房加载楼盘
     * @return mixed
     */
    public function actionHouselist()
    {
        $model = new House();
        $input = Yii::$app->request->post();
        $input['limit'] = 20;
        if (isset($input['city']) && !empty($input['city'])) {
            $city = (new CategoryCity())->getCityNameTurnId($input);
            if ($city) {
                $model->city = $city['id'];
            }
        }

        $data = $model->PcHouseList($input, ['pfg_cn_category_city.city_name', 'pfg_cn_category_city.ll', 'pfg_cn_house.id', 'pfg_cn_house.city', 'pfg_cn_house.price', 'pfg_cn_house.name', 'pfg_cn_house_detail.address', 'pfg_cn_house_detail.main_units', 'pfg_cn_house_detail.price_unit', 'pfg_cn_house_detail.longitude_latitude', 'pfg_cn_house.thumb', 'pfg_cn_house.sale_price', 'pfg_cn_house.characteristic']);

        if ($data != null) {
            $characteristic = new Characteristic();
            $charList = $characteristic->getList([]);
            $characteristicId = array_column($charList, 'name', 'id');
            $chara = array_column($data, 'characteristic', 'id');
            $charaArrs = [];
            //处理特色主题
            foreach ($chara as $key => $val) {
                $arr = json_decode($val, true);
                if (is_array($arr) && !empty($arr)) {
                    foreach ($arr as $k => $v) {
                        if (isset($characteristicId[$v])) {
                            $charaArrs[$key][$k] = $characteristicId[$v];
                        }
                    }
                }
            }

            $Tel = new CategoryTelCity();
            $telRow = $Tel->QgetAll();

            $cityTel = [];
            foreach ($telRow as &$v) {
                $cityTel[$v['cid']] = explode(',', $v['tel']);
            }

            $randArr = [];
            foreach ($data as &$val) {
                $val['thumb'] = Yii::$app->params['httpImg']['hosts'] . Yii::$app->params['httpImg']['housesch'] . $val['thumb'];
                if (isset($charaArrs[$val['id']])) {
                    //随机选择3个特色主题
                    if (count($charaArrs[$val['id']]) > 3) {
                        $ranChar = array_rand($charaArrs[$val['id']], 3);
                        $randArr[] = $charaArrs[$val['id']][$ranChar[0]];
                        $randArr[] = $charaArrs[$val['id']][$ranChar[1]];
                        $randArr[] = $charaArrs[$val['id']][$ranChar[2]];
                        $val['characteristic'] = $randArr;
                        $randArr = [];
                    } else {
                        $val['characteristic'] = $charaArrs[$val['id']];
                    }

                }

                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'];
                }
            }
            $rows = ['data' => $data];
        }

        if (!empty($rows)) {
            return Help::JsonCode(Help::SUCCESS, '成功', $rows);
        }
        return Help::JsonCode(Help::ERROR, '暂无数据');
    }

    /**
     * 地图找房楼盘详情
     * @return mixed
     */
    public function actionDetails()
    {
        $model = new HouseServer();
        $row = $model->Details();
        $arr = [];
        if (!empty($row)) {
            $arr['id'] = $row['house']['id'];
            $arr['name'] = $row['house']['name'];
            $arr['state'] = $row['house']['state'];
            $arr['thumb'] = Yii::$app->params['httpImg']['hosts'] . Yii::$app->params['httpImg']['housesch'] . $row['house']['thumb'] . '/pfgwatermark';
            $arr['sale_price'] = $row['house']['sale_price'];
            $arr['price_unit'] = $row['house']['price_unit'];
            $arr['main_units'] = $row['house']['main_units'];
            $arr['city_name'] = $row['house']['city_name'];
            $arr['characteristic'] = $row['characteristic'];
            return Help::JsonCode(Help::SUCCESS, '成功', $arr);
        }
        return Help::JsonCode(Help::ERROR, '暂无相关楼盘数据');
    }

    /**
     * 资讯列表
     * @return mixed
     */
    public function actionHomeform()
    {
        $model = new News();
        if (is_numeric(Yii::$app->request->get('cid'))) {
            $model->category = Yii::$app->request->get('cid');
            if ($model->category == 0) $model->category = null;
        }
        $newsList = $model->Mhomelist(Yii::$app->request->get());
        if (!empty($newsList)) {
            foreach ($newsList as &$val) {
                if (!empty($val['thumb'])) {
                    $val['thumb'] = json_decode($val['thumb']);
                }
            }
            $arr['url'] = Yii::$app->params['httpImg']['host'] . Yii::$app->params['httpImg']['newsthumb_cn'];
            $arr['data'] = $newsList;
            return Help::JsonCode(Help::SUCCESS, '成功', $arr);
        }
        return Help::JsonCode(Help::ERROR, '失败');
    }


}