<?php
require_once(PLUGIN_DIR . 'Dao/SearchDao.php');
require_once(PLUGIN_DIR . 'Dao/InsertDao.php');
require_once(PLUGIN_DIR . 'Tools/Image.php');
class SecHandHouse extends Tospur_House{
    //二手房信息
    public static function secHandHouse_html(){
        global $wpdb;
        $type = $_POST["type"];
        $context = array();
        $context['siteUrl'] = get_site_url();
        $insert_tospur_house_array = array(
            'name' => $_POST['housename'],
            'total_price' =>$_POST['total_price'],
            'average_price' => $_POST['average_price'],
            'buildproperty_id'=>$_POST['roomNum'],
            'covered_area' =>$_POST['covered_area'],
            'floor' =>$_POST['floor'],
            'faceto'=>$_POST['faceto'],
            'decoration' => $_POST['decoration'],
            'age'=>$_POST['age'],
            'suite'=>$_POST["suite"],
            'overview' => $_POST['overview'],
            'city_id' => $_POST['baseCity'],
            'district_id' => $_POST['baseAreaId'],
            'plate_id' => $_POST["basePlateId"],
            'room_id' => $_POST['baseRoom'],
            'address' => $_POST['address'],
            'community_name'=>$_POST['community_name'],
            'traffic' => $_POST['traffic'],
            'periphery' => $_POST['periphery'],
            'owner_name'=>$_POST['owner_name'],
            'owner_phone'=>$_POST['owner_phone'],
            "location" => $_POST["location"],
            "totalFloor"=>$_POST["totalFloor"],
            "useArea"=>$_POST["useArea"],
            "street"=>$_POST["street"],
            "propertyProof"=>$_POST["propertyProof"],
            "roomNum"=>$_POST["roomNum"],
            "livingRoom"=>$_POST["livingRoom"],
            "bathRoom"=>$_POST["bathRoom"],
            "kitchen"=>$_POST["kitchen"],
            "balcony"=>$_POST["balcony"],
            "propertyRight"=>$_POST["propertyRight"],
            "structure"=>$_POST["structure"],
            "key"=>$_POST["key"],
            "matching_facilities"=>$_POST["matching_facilities"],
            "garage"=>$_POST["garage"],
            "entrustDay"=>$_POST["entrustDay"],
            "deadLine"=>$_POST["deadLine"],
            "property_money"=>$_POST["property_money"],
            "mortgage" =>$_POST["mortgage"],
            "parking_spaces"=>$_POST["parking_spaces"]
        );

        if($type==2){
            $wpdb->query("START TRANSACTION");
            if(isset($_POST['houseId'])){
                //首先判断是经理修改还是职业顾问做不同的操作，接着判断置业顾问是否修改了状态
                if($_POST["userType"] == 0){
                    //经理
                    //通过
                    if($_POST["status"] != -2){
                        $insert_tospur_house_array["status"] =$_POST["status"];
                        $insert_tospur_house_array["approval"] = -2;
                    }else{
                        //退回
                        $insert_tospur_house_array["approval"] = $_POST["status"];
                    }
                }else{
                    //置业顾问
                    $currentStatus = SearchDao::getDetailInfo($_POST["userType"]);
                    //修改了状态
                    if($currentStatus["result"]->status != $_POST["status"]){
                        $insert_tospur_house_array["approval"] = $_POST["status"];
                    }else {
                        //没有修改状态
                        //没有申请审批
                        if($currentStatus["result"]->approval == -2){
                            $insert_tospur_house_array["approval"] = $currentStatus["result"]->status;
                        }else{
                            //申请了审批，没有修改状态，approval保持原来的
                            $insert_tospur_house_array["approval"] = $currentStatus["result"]->approval;
                        }
                    }
                }
                $result = SecHandHouse::data_update($_POST['houseId'],$insert_tospur_house_array);
                if(!is_numeric($result)){
                    $wpdb->query("ROLLBACK");
                    print_r( $result);;
                    echo "二手房房源修改失败";
                }else{
                    $wpdb->query("COMMIT");
                    echo "二手房房源修改成功";
                }

            }else {
                $insert_tospur_house_array["status"] = 0;
                $insert_tospur_house_array["approval"] = 1;
                $result = SecHandHouse::secHouseData_insert($insert_tospur_house_array);
                if (!is_numeric($result)) {
                    $wpdb->query("ROLLBACK");
                    print_r( $result);;
                    echo "二手房房源新增失败";
                } else {
                    $wpdb->query("COMMIT");
                    echo "二手房房源新增成功";
                }
            }
            exit;
        }else if(isset($_GET['edit'])){
            $context['houseId'] = $_GET['id'];
            $context = array_merge($context,SearchDao::getDetailInfo($_GET['id']));
            $context["district"] = SearchDao::searchCity($context['result']->city_id);
            $context["plate"] = SearchDao::searchCity($context['result']->city_id,$context['result']->district_id);
        }
        $context['canApproval'] = House::canApproval();
        $context["city"] = SearchDao::searchCity();
        $context["buildProperty"] = SearchDao::searchBuildProperty();
        $context["room"] = SearchDao::searchRoom();
        $context["photoType"] = SearchDao::searchPhotoType();
        $context["status"] = searchDao::searchStatusType(2);
        $context["house_type"] = 1;
        Timber::render("secHandHouse.html",$context);

    }

    public static function secHouseData_insert($params)
    {
        global $wpdb;
        //房源与类型以及面积信息
        $data = $_POST["data"];
        $params['user_id'] = get_current_user_id();
        $params['creattime'] = date("Y-m-d H:i:s");
        $params['house_type'] = 1;
        //获取新房信息，存入tospur_house表
        $res = $wpdb->get_results('SELECT * FROM tospur_house WHERE address="' .$params['address'] . '" and owner_name="' .$params['owner_name'] . '" and owner_phone="'.$params['owner_phone'].'" and house_type=1', OBJECT);
        if(!$res){
            $houseId = InsertDao::insert_tospur_house($params);
            if(is_numeric($houseId)){
                $mainImageRes = InsertDao::addMainImage($houseId,$data);

                $recommendRes = InsertDao::addRecommend($houseId,$data);

                $recConsultantRes = InsertDao::addRecConsultant($houseId,$data['recConsultant']);

                InsertDao::addHouseTag($houseId, $data['houseTag']);

                $houseFeatureRes = InsertDao::addHouseFeature($houseId, $data['houseFeature']);

                $customerTrackRes = CustomerTrackingDao::insert($houseId, $_REQUEST);

                if(!is_numeric($mainImageRes)){
                    return $mainImageRes;
                }else if(!is_numeric($recommendRes)){
                    return $recommendRes;
                }else if(!is_numeric($recConsultantRes)){
                    return $recConsultantRes;
                }else if(is_numeric($customerTrackRes)){
                    return $customerTrackRes;
                }else if(is_numeric($houseFeatureRes)){
                    return $houseFeatureRes;
                }
            }
            return $houseId;
        }else{
            return "房源已存在";
        }
    }

    public static function data_update($houseId,$params){
        global $wpdb;
        $data = $_POST["data"];
        $res = $wpdb->update(Config::TOSPUR_HOUSE_TABLE,$params,array("id" => $houseId));
        $result = 201;

        InsertDao::addMainImage($houseId,$data);

        $exists_photo_ids = array();
        if(isset($_POST['exists_photo'])){
            foreach($_POST['exists_photo'] as $id => $item){
                $wpdb->update(Config::TOSPUR_IMAGE_TABLE,array(
                    "image_type" => $item['type'],
                ),array("id" => $id));
                $exists_photo_ids[] = $id;
            }
        }
        $old_exists_photo_ids = explode(",",$_POST['exists_photo_ids']);
        $delete_photo_ids = array();
        foreach(array_diff($old_exists_photo_ids,$exists_photo_ids) as $key => $id){
            $delete_photo_ids[] = $id;
        }
        $delete_photo_ids = implode(",",$delete_photo_ids);
        $wpdb->query("delete from ".Config::A_HOUSE_IMAGE_TABLE." where house_id = {$houseId} and image_id in ({$delete_photo_ids});");

        $wpdb->delete(Config::A_HOUSE_RECOMMEND_TABLE,array("house_id" => $houseId));
        $result = InsertDao::addRecommend($houseId,$data);
        if(!is_numeric($result)){
            return $result;
        }
        $wpdb->delete(Config::A_HOUSE_USER_TABLE,array("house_id" => $houseId));
        $result = InsertDao::addRecConsultant($houseId, $data['recConsultant']);
		if(!is_numeric($result)){
            return $result;
        }

        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM a_house_tag
                WHERE tag_id in(select tag_id from (select tag_id,tt.type from a_house_tag as aht
                left JOIN tospur_tag tt on aht.tag_id = tt.id) as a
                where house_id = %d and a.type = 1);", $houseId)
        );
		InsertDao::addHouseTag($houseId, $data['houseTag']);

        $result = InsertDao::addHouseFeature($houseId, $data['houseFeature']);
		if(!is_numeric($result)){
            return $result;
        }
		CustomerTrackingDao::insert($_POST['houseId'], $_REQUEST);
        return $result;
    }

}

