<?php
/**
 * Created by PhpStorm.
 * User: xiaofeng
 * Date: 2018/3/11
 * Time: 下午3:08
 */

namespace backend\server;

use common\models\CategoryAlbum;
use common\models\CategoryFacilities;
use common\models\CategoryHousetype;
use common\models\House;
use common\models\HouseDetail;
use common\models\HouseAlbum;
use common\models\HouseType;
use common\models\HouseFacilities;
use common\models\HousePermit;
use common\models\HousePriceRecord;
use common\models\Characteristic;
use common\models\CategoryLabel;
use common\models\CategoryCity;
use yii\base\Component;
use common\models\Synchouserecord;
use Yii;

class SyncHouse extends Component
{
    //楼盘添加或修改处理
    public function HouseOpe($input)
    {
        if (empty($input) || !is_array($input)) return false;
        //判断楼盘是否同步过
//        $url = Yii::$app->basePath . '/runtime/ceshi.json';
//        $datas = json_encode($input);
//        file_put_contents($url, $datas);
//        return false;

        $s = Synchouserecord::find()->select(['own_hid'])->andWhere(['unid' => $input['unid']])->one();

        if (!empty($s)) {
            $record = House::find()->select(['id as hid'])->andWhere(['del' => 1])->andWhere(['id' => $s['own_hid']])->asArray()->one();
        }

        if (empty($record['hid'])) {
            //楼盘未同步过,但是存在情况
            $record = House::find()->select(['id as hid'])->andWhere(['name' => $input['house_name']])->andWhere(['del' => 1])->asArray()->one();
        }

        if (!empty($record['hid']) && is_numeric($record['hid'])) {


            return $this->Edit($input, $record['hid']);
        } else {
            if (!isset($input['house_data']) && empty($input['house_data'])) return '检测到无该楼盘信息,请先添加楼盘信息,在添加楼盘相关相册,户型,配套,预售证,历史价格等信息。';
            return $this->Add($input);
        }

    }

    //楼盘修改逻辑
    public function Edit($input, $hid)
    {
        $Transaction = Yii::$app->db->beginTransaction();
        try {

            if (isset($input['house_data']) && !empty($input['house_data'])) {
                $this->HouseParams($input, $hid);
            }

            if (isset($input['housealbum']) && !empty($input['housealbum'])) {
                $this->HouseAlbum($input, $hid);
            }

            if (isset($input['housetype']) && !empty($input['housetype'])) {
                $this->HouseType($input, $hid);
            }

            if (isset($input['housepeitao']) && !empty($input['housepeitao'])) {
                $this->HouseFacilities($input, $hid);
            }

            if (isset($input['housepermit']) && !empty($input['housepermit'])) {
                $this->HousePermit($input, $hid);
            }

            if (isset($input['houseprice']) && !empty($input['houseprice'])) {
                $this->HousePriceRecord($input, $hid);
            }

            $m = new Synchouserecord();
            $m->own_hid = $hid;
            $m->unid = $input['unid'];
            $m->state = 2;
            $m->create_at = $_SERVER['REQUEST_TIME'];
            $m->content = json_encode($input);
            $m->name = $input['user_name'];

            if ($m->save() == false) throw new \Exception('请联系管理员');
            $Transaction->commit();
            return true;
        } catch (\Exception $e) {
            $Transaction->rollBack();
            return $e->getMessage();
        }


    }

    public function Add($input)
    {
        $Transaction = Yii::$app->db->beginTransaction();
        try {
            $house = new House();
            $houseDetails = new HouseDetail();
            if (!empty($input['house_data']['characteristic'])) {
                $name['name'] = $input['house_data']['characteristic'];

                $CharSub = $this->CharacteristicSubject($name);
                if (!empty($CharSub)) {
                    $SubFlip = array_flip($CharSub);
                    $input['house_data']['characteristic'] = '["' . implode('","', $SubFlip) . '"]';
                } else {
                    $input['house_data']['characteristic'] = '';
                }

            }

            if (!empty($input['house_data']['type'])) {
                $name['name'] = $input['house_data']['type'];
                $CharSub = $this->Label($name, 1);
                if (!empty($CharSub)) {
                    $SubFlip = array_flip($CharSub);
                    $input['house_data']['type'] = '["' . implode('","', $SubFlip) . '"]';
                } else {
                    $input['house_data']['type'] = '';
                }
            }

            if (!empty($input['house_data']['architecture_type'])) {
//                $input =  $this->LebelMerge($input,2,$houseRow);
                $name['name'] = $input['house_data']['architecture_type'];
                $CharSub = $this->Label($name, 2);
                if (!empty($CharSub)) {
                    $SubFlip = array_flip($CharSub);
                    $input['house_data']['architecture_type'] = '["' . implode('","', $SubFlip) . '"]';
                } else {
                    $input['house_data']['architecture_type'] = '';
                }
            }

            if (!empty($input['house_data']['property_tag'])) {
//                $input =  $this->LebelMerge($input,3,$houseDetailsRow);
                $name['name'] = $input['house_data']['property_tag'];
                $CharSub = $this->Label($name, 3);
                if (!empty($CharSub)) {
                    $SubFlip = array_flip($CharSub);
                    $input['house_data']['property_tag'] = '["' . implode('","', $SubFlip) . '"]';
                } else {
                    $input['house_data']['property_tag'] = '';
                }
            }

            $area = $this->CityId($input['house_data']['area_name'], 3);
            if ($area) {
                $input['house_data']['area'] = $area['id'];
            }

            $province = $this->CityId($input['house_data']['province_name'], 1);
            if ($province) {
                $input['house_data']['province'] = $province['id'];
            }


            $city = $this->CityId($input['house_data']['city_name'], 2)['id'];
            if ($city) {
                $input['house_data']['city'] = $this->CityId($input['house_data']['city_name'], 2)['id'];
            } else {
                if (isset($input['house_data']['main_city']) && !empty($input['house_data']['main_city'])) {
                    $input['house_data']['city'] = $this->CityId($input['house_data']['main_city'], 2)['id'];
                }
            }

            if ($input['house_data']['city_name'] == '迪拜') {
                $c = \common\models\CategoryCity::find()->select(['id'])->andWhere(['city_name' => $input['house_data']['city_name']])->andWhere(['del' => 1])->andWhere(['<>', 'pid', 0])->one();
                if ($c) {
                    $input['house_data']['city'] = $c['id'];
                }
            }

            if (empty($input['house_data']['city'])) throw new \Exception('检测到无该区域信息,请先添加区域信息。');

            unset($input['house_data']['id']);
            unset($input['house_data']['hid']);
            unset($input['house_data']['click_num']);
            unset($input['house_data']['sort']);
            unset($input['house_data']['create_at']);
            unset($input['house_data']['update_at']);
//        $url = Yii::$app->basePath . '/runtime/house.json';
//        $data = json_encode($input['house_data']);
//        file_put_contents($url, $data);
            $house->load($input['house_data'], '');
            $b = $house->save(false);
//                var_dump($b);
            if ($b != true) throw new \Exception('楼盘资料添加失败。');
            $houseDetails->hid = $house->attributes['id'];
            $hid = $house->attributes['id'];
            $houseDetails->load($input['house_data'], '');
            $a = $houseDetails->save(false);
//                var_dump($a);
            if ($a != true) throw new \Exception('楼盘资料添加失败。');

            if (!empty($input['housealbum'])) {

                $this->HouseAlbum($input, $hid);
            }

            if (!empty($input['housetype'])) {
                $this->HouseType($input, $hid);
            }

            if (!empty($input['housepeitao'])) {

                $this->HouseFacilities($input, $hid);
            }

            if (!empty($input['housepermit'])) {
                $this->HousePermit($input, $hid);
            }

            if (!empty($input['houseprice'])) {
                $this->HousePriceRecord($input, $hid);
            }
            $m = new Synchouserecord();
            $m->own_hid = $hid;
            $m->unid = $input['house_data']['uniqid'];
            $m->state = 1;
            $m->create_at = $_SERVER['REQUEST_TIME'];
            $m->content = json_encode($input);
            $m->name = $input['user_name'];

            if ($m->save() == false) throw new \Exception('请联系管理员');
            $Transaction->commit();
            return true;
        } catch (\Exception $e) {
            $Transaction->rollBack();
            return $e->getMessage();
        }
    }

    //楼盘内容参数--修改逻辑
    public function HouseParams($input, $hid)
    {
        $house = new House();
        $houseRow = $house->FindById($hid);
        $houseDetails = new HouseDetail();
        $houseDetailsRow = $houseDetails->FindById($houseRow['id']);

        if (isset($input['house_data']['characteristic']) && !empty($input['house_data']['characteristic'])) {
            $input = $this->CharacteristicMerge($input, $houseRow);
        }

        if (isset($input['house_data']['type']) && !empty($input['house_data']['type'])) {
            $input = $this->LebelMerge($input, 1, $houseRow);
        }

        if (isset($input['house_data']['architecture_type']) && !empty($input['house_data']['architecture_type'])) {
            $input = $this->LebelMerge($input, 2, $houseRow);
        }

        if (isset($input['house_data']['property_tag']) && !empty($input['house_data']['property_tag'])) {
            $input = $this->LebelMerge($input, 3, $houseDetailsRow);
        }


        unset($input['house_data']['id']);
        unset($input['house_data']['hid']);
        unset($input['house_data']['click_num']);
        unset($input['house_data']['sort']);
        unset($input['house_data']['create_at']);
        unset($input['house_data']['update_at']);

        $area = $this->CityId($input['house_data']['area_name'], 3);
        if ($area) {
            $input['house_data']['area'] = $area['id'];
        }

        $province = $this->CityId($input['house_data']['province_name'], 1);
        if ($province) {
            $input['house_data']['province'] = $province['id'];
        }

        $city = $this->CityId($input['house_data']['city_name'], 2)['id'];
        if ($city) {
            $input['house_data']['city'] = $this->CityId($input['house_data']['city_name'], 2)['id'];
        } else {
            if (isset($input['house_data']['main_city']) && !empty($input['house_data']['main_city'])) {
                $input['house_data']['city'] = $this->CityId($input['house_data']['main_city'], 2)['id'];
            }
        }


        if ($input['house_data']['city_name'] == '迪拜') {
            $c = \common\models\CategoryCity::find()->select(['id'])->andWhere(['city_name' => $input['house_data']['city_name']])->andWhere(['del' => 1])->andWhere(['<>', 'pid', 0])->one();
            if ($c) {
                $input['house_data']['city'] = $c['id'];
            }
        }

//        $input['house_data']['city'] = $this->CityId($input['house_data']['city_name'])['id'];
        if (empty($input['house_data']['city'])) throw new \Exception('检测到无该区域信息,请先添加区域信息。');
        $houseRow->load($input['house_data'], '');
        $houseDetailsRow->load($input['house_data'], '');
        if ($houseRow->save(false) == false) throw new \Exception('楼盘信息修改失败。');
        if ($houseDetailsRow->save(false) == false) throw new \Exception('楼盘信息修改失败。');;

    }

    public function HouseParamsAdd($input)
    {
        $house = new House();
    }


    //楼盘相册修改逻辑;
    public function HouseAlbum($input, $hid)
    {
        $cat = CategoryAlbum::find()->select(['name', 'id'])->andWhere(['del' => 1])->asArray()->all();
        $catId = array_column($cat, 'id', 'name');
        $arr = [];
        foreach ($input['housealbum'] as $key => $val) {
            if (isset($catId[$val['name']]) && !empty($catId[$val['name']])) {
                $arr[$key]['title'] = $val['title'];
                $arr[$key]['img'] = $val['img'];
                $arr[$key]['album_id'] = $catId[$val['name']];
                $arr[$key]['hid'] = $hid;
                $arr[$key]['sort'] = $val['sort'];
            }
        }
        if (!empty($arr)) {
            $model = new HouseAlbum();
            HouseAlbum::updateAll(['del' => 2], ['hid' => $hid]);
            foreach ($arr as $val) {
                $_model = clone $model;
                $row = $_model::find()->andWhere(['album_id' => $val['album_id']])->andWhere(['img' => $val['img']])->andWhere(['hid' => $hid])->andWhere(['del' => 1])->exists();
                if ($row == false) {
                    $_model->title = $val['title'];
                    $_model->img = $val['img'];
                    $_model->album_id = $val['album_id'];
                    $_model->hid = $val['hid'];
                    $_model->sort = $val['sort'];
                    if ($_model->save(false) == false) throw new \Exception('楼盘相册添加失败。');
                }
            }
        }

    }

    //楼盘户型图  后期看可否统一删除从新加载
    public function HouseType($input, $hid)
    {
        $cat = CategoryHousetype::find()->select(['huxing_name', 'id'])->andWhere(['del' => 1])->asArray()->all();
        $catId = array_column($cat, 'id', 'huxing_name');
        $arr = [];
        foreach ($input['housetype'] as $key => $val) {
            if (isset($catId[$val['huxing_name']]) && !empty($catId[$val['huxing_name']])) {
                $arr[$key]['img'] = $val['img'];
                $arr[$key]['title'] = $val['title'];
                $arr[$key]['type_id'] = $catId[$val['huxing_name']];
                $arr[$key]['hid'] = $hid;
                $arr[$key]['area'] = $val['area'];
                $arr[$key]['indoor_info'] = $val['indoor_info'];
            }
        }


        if (!empty($arr)) {
            HouseType::updateAll(['del' => 2], ['hid' => $hid]);

            $model = new HouseType();

            foreach ($arr as $val) {
                $_model = clone $model;
                $row = $_model::find()->andWhere(['type_id' => $val['type_id']])
                    ->andWhere(['img' => $val['img']])
                    ->andWhere(['hid' => $hid])
                    ->andWhere(['del' => 1])
                    ->andWhere(['title' => $val['title']])
                    ->andWhere(['area' => $val['area']])
                    ->andWhere(['indoor_info' => $val['indoor_info']])
                    ->exists();
                if ($row == false) {
                    $_model->img = $val['img'];
                    $_model->title = $val['title'];
                    $_model->type_id = $val['type_id'];
                    $_model->hid = $hid;
                    $_model->area = $val['area'];
                    $_model->indoor_info = $val['indoor_info'];
                    $t = $_model->save(false);
                    if ($t == false) throw new \Exception('户型操作失败。');
                }
            }

        }


    }

    //周边配套
    public function HouseFacilities($input, $hid)
    {

        $cat = CategoryFacilities::find()->select(['name', 'id'])->andWhere(['del' => 1])->asArray()->all();
        $catId = array_column($cat, 'id', 'name');
        $arr = [];

        foreach ($input['housepeitao'] as $key => $val) {
            if (isset($catId[$val['name']]) && !empty($catId[$val['name']]) && !empty($val['pname'])) {
                $arr[$key]['fid'] = $catId[$val['name']];
                $arr[$key]['hid'] = $hid;
                $arr[$key]['latitude_longitude'] = $val['latitude_longitude'];
                $arr[$key]['distance'] = $val['distance'];
                $arr[$key]['name'] = $val['pname'];
            }
        }

        if (!empty($arr)) {
            HouseFacilities::deleteAll(['hid' => $hid]);
            $model = new HouseFacilities();
            foreach ($arr as $val) {
                $_model = clone $model;
                $_model->name = $val['name'];
                $_model->distance = $val['distance'];
                $_model->latitude_longitude = $val['latitude_longitude'];
                $_model->fid = $val['fid'];
                $_model->hid = $hid;
                $t = $_model->save(false);
                if (!$t) throw new \Exception('周边配套添加失败。');
            }
        }


    }

    //预售证
    public function HousePermit($input, $hid)
    {
        $model = new HousePermit();
        if (!empty($input['housepermit'])) {
            HousePermit::updateAll(['del' => 2], ['hid' => $hid]);
        }
        foreach ($input['housepermit'] as $val) {
            $_model = clone $model;
            $row = $_model::find()->andWhere(['hid' => $hid])->andWhere(['permit' => $val['permit']])->andWhere(['building_num' => $val['building_num']])->andWhere(['del' => 1])->exists();
            if ($row == 0) {

                $_model->permit = $val['permit'];
                $_model->time = $val['time'];
                $_model->building_num = $val['building_num'];
                $_model->hid = $hid;
                if ($_model->save(false) == false) throw new \Exception('预售证添加失败。');
            }
        }
    }

    //历史价格
    public function HousePriceRecord($input, $hid)
    {
        $model = new HousePriceRecord();
        if (is_array($input['houseprice']) && !empty($input['houseprice'])) {
            if (is_numeric($hid)) {
                HousePriceRecord::deleteAll(['hid' => $hid]);
            }
            foreach ($input['houseprice'] as $val) {
                $_model = clone $model;
//                $row = $_model::find()->andWhere(['hid'=>$hid])->andWhere(['price'=>$val['price']])->andWhere(['del'=>1])->exists();
//                if($row == false)
//                {
                $_model->price = $val['price'];
                $_model->create_time = $val['create_time'];
                $_model->min_price = $val['min_price'];
                $_model->explain = $val['explain'];
                $_model->hid = $hid;
                $_model->hid = $hid;
                $_model->price_unit = $val['price_unit'];
                if ($_model->save(false) == false) throw new \Exception('历史价格添加失败。');
//                }
            }
        }
//        $model = new HousePriceRecord();
//        foreach ($input['houseprice'] as $val)
//        {
//            $_model = clone $model;
//            $row = $_model::find()->andWhere(['hid'=>$hid])->andWhere(['price'=>$val['price']])->andWhere(['del'=>1])->exists();
//            if($row == false)
//            {
//                $_model->price = $val['price'];
//                $_model->create_time = $val['create_time'];
//                $_model->min_price = $val['min_price'];
//                $_model->explain = $val['explain'];
//                $_model->hid = $hid;
//                $_model->hid = $hid;
//                $_model->price_unit = $val['price_unit'];
//                if($_model->save(false) == false) throw new \Exception('历史价格添加失败。');
//            }
//        }
    }

    //转换特色主题ID
    public function CharacteristicSubject($input)
    {
        $query = Characteristic::find();
        if (isset($input['id']) && !empty($input['id'])) {
            $query->andWhere(['id' => $input['id']]);
        } else if (isset($input['name']) && !empty($input['name'])) {
            $query->andWhere(['name' => $input['name']]);
        } else {
            return '';
        }
        $all = $query->asArray()->all();
        if (!empty($all)) {
            return array_column($all, 'name', 'id');
        }
        return '';
    }

    //合并转换后的楼盘特色主题
    public function CharacteristicMerge($input, $housrRow)
    {
        $char['name'] = $input['house_data']['characteristic'];
        $CharSub = $this->CharacteristicSubject($char);
        if (!empty($CharSub)) {
            $SubFlip = array_flip($CharSub);
            $input['house_data']['characteristic'] = '["' . implode('","', array_unique(array_values((array)$SubFlip))) . '"]';
        } else {
            $input['house_data']['characteristic'] = '';
        }
        return $input;
    }

    //标签,
    public function Label($input, $type)
    {
        $query = CategoryLabel::find();
        $query->andWhere(['type' => $type]);
        if (isset($input['id']) && !empty($input['id'])) {
            $query->andWhere(['id' => $input['id']]);
        } else if (isset($input['name']) && !empty($input['name'])) {
            $query->andWhere(['name' => $input['name']]);
        } else {
            return '';
        }

        $all = $query->asArray()->all();
        if ($all != null) {
            return array_column($all, 'name', 'id');
        }
        return '';
    }

    public function CityId($name, $level)
    {
        $query = CategoryCity::find();
        return $query->select(['id'])->andWhere(['city_name' => $name, 'level' => $level])->andWhere(['del' => 1])->asArray()->one();
    }

    //合并转换标签
    public function LebelMerge($input, $type, $housrRow)
    {
        switch ($type) {
            case 1:
                $char['name'] = $input['house_data']['type'];
                $CharSub = $this->Label($char, $type);
                if (!empty($CharSub)) {
                    $SubFlip = array_flip($CharSub);
                    $input['house_data']['type'] = '["' . implode('","', array_unique(array_values((array)$SubFlip))) . '"]';
                } else {
                    throw new \Exception('缺少物业类型:' . implode(',', $input['house_data']['type']) . ',请联系管理员添加。');
//                    $input['house_data']['type'] = '';
                }
                break;
            case 2:
                $char['name'] = $input['house_data']['architecture_type'];
                $CharSub = $this->Label($char, $type);
                if (!empty($CharSub)) {
                    //1
                    $SubFlip = array_flip($CharSub);
                    $input['house_data']['architecture_type'] = '["' . implode('","', array_unique(array_values((array)$SubFlip))) . '"]';
                } else {
                    throw new \Exception('缺少建筑类别:' . implode(',', $input['house_data']['architecture_type']) . ',请联系管理员添加。');
                }

                break;
            case 3:
                $char['name'] = $input['house_data']['property_tag'];
                $CharSub = $this->Label($char, $type);
                if (!empty($CharSub)) {
                    $SubFlip = array_flip($CharSub);
                    $input['house_data']['property_tag'] = '["' . implode('","', array_unique(array_values((array)$SubFlip))) . '"]';
                } else {
                    throw new \Exception('缺少楼盘标签:' . implode(',', $input['house_data']['property_tag']) . ',请联系管理员添加。');

                }
                break;
        }
        return $input;
    }
}