<?php
//require_once(dirname(__FILE__) . '/Config.php');
class InsertDao{
    public static function insert_tospur_house($params){
        global $wpdb;
        DBManager::insert(Config::TOSPUR_HOUSE_TABLE, $params);
        if($wpdb->last_error){
            return $wpdb->last_error;
        }
        $houseId = $wpdb->insert_id;
        if(!InsertDao::setHouseNumber($houseId,$params['house_type'],$params['city_id'])){
            return "房源代码生成失败";
        }
        return $houseId;
    }

    public static function setHouseNumber($houseId,$houseType,$cityId){
        switch($houseType){
            case 0:
                $prefix = "xf";
                break;
            case 1:
                $prefix = "CS";
                break;
            case 2:
                $prefix = "CZ";
                break;
        }
        $house_number = $prefix.str_pad($cityId,4,'0',STR_PAD_LEFT).str_pad($houseId,8,'0',STR_PAD_LEFT);
        return DBManager::update(Config::TOSPUR_HOUSE_TABLE,
            array(
                'house_number' => $house_number
            ),
            array(
                "id" => $houseId
            )
        );
    }

    public static function insert_tospur_image($params){
        global $wpdb;
        DBManager::insert(Config::TOSPUR_IMAGE_TABLE, $params);
        if($wpdb->last_error){
            return $wpdb->last_error;
        }
        $imgId = $wpdb->insert_id;
        return $imgId;
    }
    public static function insert_a_district_area($params){
        global $wpdb;
        DBManager::insert(Config::A_DISTRICT_AREA_TABLE, $params);
        if($wpdb->last_error){
            return $wpdb->last_error;
        }
        return $wpdb->insert_id;
    }

    public static function insert_a_house_image($params){
        global $wpdb;
        DBManager::insert(Config::A_HOUSE_IMAGE_TABLE, $params);
        if($wpdb->last_error){
            return $wpdb->last_error;
        }
        return $wpdb->insert_id;
    }

    public static function  insert_a_house_recommend($params){
        global $wpdb;
        DBManager::insert(Config::A_HOUSE_RECOMMEND_TABLE, $params);
        if($wpdb->last_error){
            return $wpdb->last_error;
        }
        return $wpdb->insert_id;
    }

    public static function  insert_a_house_user($params){
        global $wpdb;
        DBManager::insert(Config::A_HOUSE_USER_TABLE, $params);
        if($wpdb->last_error){
            return $wpdb->last_error;
        }
        return $wpdb->insert_id;
    }

    public static function addMainImage($houseId,$data){
        global $wpdb;
        //图片信息
        $uploadedfile = $_FILES['files'];
        $frontCover = $_POST["frontCover"];
        $result = 1;
        //主力房源的图片与房子信息关联插入数据库
        if(isset($uploadedfile["name"])){
            foreach($uploadedfile["name"] as $key=> $value) {
                $uploadParam = array(
                    "name" => $uploadedfile["name"][$key],
                    "type" => $uploadedfile["type"][$key],
                    "tmp_name" => $uploadedfile["tmp_name"][$key],
                    "error" => $uploadedfile["error"][$key],
                    "size" => $uploadedfile["size"][$key]
                );
                //因为file提交过来有一个空的数组，所以这里判断在filename不为空的情况下，再做后续操作
                if ($uploadParam["name"] != "") {
                    //上传图片
                    if (!function_exists('wp_handle_upload')) {
                        require_once(ABSPATH . 'wp-admin/includes/file.php');
                    }
                    $overrides = array('test_form' => false);
                    $movefile = wp_handle_upload($uploadParam, $overrides);
                    $str = preg_replace('#^https?://#', '', $movefile["url"]);
                    $length = strpos($str, "/",strpos($str, "/")+1);
                    $url = substr($str,$length);
                    if ($movefile && !isset($movefile['error'])) {
                        $uploadFileName = end(explode("/",$url));
                        //上传成功后将图片信息存入tospur_image表
                        $insert_image_array = array(
                            'name' => $uploadFileName,
                            'path' => $url,
                            'creattime' => date("Y-m-d H:i:s"),
                            'alt' => "",
                            'image_type' =>$data[$key]["type"]
                        );
                        $imagePath = get_home_path().$url;
                        Image::makeImage($uploadFileName,$imagePath);
                        //插入图片表
                        DBManager::insert('tospur_image', $insert_image_array);
                        if ($wpdb->last_error) {
                           return $wpdb->last_error;
                        }

                        //获取插入图片的id
                        $imgid = $wpdb->insert_id;
                        if($_POST["frontCover"] == $key){
                            $frontCover =$imgid;
                        }

                        //房源类型、面积与图片关联表
                        if($data[$key]["mainHouse"] == "0"){
                            $houseTypeArea = array(
                                'house_id' => $houseId,
                                "buildproperty_id" => $data["$key"]["buildProperty"],
                                "house_area" => $data["$key"]["housearea"],
                                "image_id" => $imgid
                            );
                            DBManager::insert(Config::A_DISTRICT_AREA_TABLE, $houseTypeArea);
                            if ($wpdb->last_error) {
                                return $wpdb->last_error;
                            }
                        }
                        //将房源id与图片id储存到关联表中
                        $house_img_array = array(
                            'house_id' => $houseId,
                            'image_id' => $imgid,
                        );
                        DBManager::insert(Config::A_HOUSE_IMAGE_TABLE, $house_img_array);
                        if ($wpdb->last_error) {
                            return $wpdb->last_error;
                        }
                    } else {
                        return $movefile['error'];
                    }
                }
            }
        }
        DBManager::update(Config::TOSPUR_HOUSE_TABLE,array("frontCover_id"=>$frontCover),array("id"=>$houseId));
        if ($wpdb->last_error) {
            return $wpdb->last_error;
        }
        return $result;
    }

    public static function addRecommend($houseId,$data){
        global $wpdb;
        if(isset($data["recommend"])){
            //插入推荐房源id与添加新房id到关联表a_house_recommend
            foreach($data["recommend"] as $value){
                $a_house_recommendArray = array(
                    "house_id" => $houseId,
                    "recommend_id" =>$value
                );
                DBManager::insert(Config::A_HOUSE_RECOMMEND_TABLE, $a_house_recommendArray);
                if( $wpdb->last_error){
                    return $wpdb->last_error;
                }
            }
        }
        return 1;
    }

    public static function addRecConsultant($houseId, $consultant){
        global $wpdb;
        if($consultant){
            DBManager::delete(Config::A_HOUSE_USER_TABLE,array("house_id" => $houseId));
            //插入推荐置业顾问user_id与新房id到关联表a_house_recommend
            foreach($consultant as $val){
                $a_house_userArray = array(
                    "user_id" => $val,
                    "house_id" => $houseId,
                    "user_type" => 1
                );
                DBManager::replace(Config::A_HOUSE_USER_TABLE,$a_house_userArray);
                if( $wpdb->last_error){
                    return $wpdb->last_error;
                }
            }
            $res =DBManager::get_row("select subsidiaryId from ".Config::TOSPUR_CONSULTANT." where id =".$consultant[0]);
            DBManager::update(Config::TOSPUR_HOUSE_TABLE,array("organizationId"=>$res->subsidiaryId),array("id"=>$houseId));
            if( $wpdb->last_error){
                return $wpdb->last_error;
            }
        }
        return 1;
    }

    public static function addHouseFeature($houseId,$houseFeature){
        global $wpdb;
        if($houseFeature){
            foreach($houseFeature as $val){
                $a_house_feature = array(
                    "house_id" => $houseId,
                    "tag_id" =>$val
                );
                DBManager::insert(Config::A_HOUSE_TAG_TABLE,$a_house_feature);
                if( $wpdb->last_error){
                    return $wpdb->last_error;
                }
            }
        }
        return 1;
    }


    public static function addHouseTag($house_id, $houseTag)
    {
        global $wpdb;
        DBManager::query(
            $wpdb->prepare("DELETE FROM " . Config::A_HOUSE_TAG_TABLE .
                " WHERE tag_id in(select tag_id from (select tag_id,tt.type from " . Config::A_HOUSE_TAG_TABLE . " as aht" .
                " left JOIN " . Config::TOSPUR_TAG_TABLE . " tt on aht.tag_id = tt.id) as a" .
                " where house_id = %d and a.type = 0);", $house_id)
        );
        if( $wpdb->last_error){
            return $wpdb->last_error;
        }
        if ($houseTag) {
            foreach ($houseTag as $val) {
                $a_house_tag = array(
                    "house_id" => $house_id,
                    "tag_id" => $val
                );
                DBManager::insert(Config::A_HOUSE_TAG_TABLE, $a_house_tag);
                if( $wpdb->last_error){
                    return $wpdb->last_error;
                }
            }
        }
        return 1;
    }

    public static function arrayToString($array)
    {
        $string = "(";
        $length = count($array);
        $i = 0;
        foreach ($array as $key => $value) {
            $i++;
            $string .= "'" . $value . "'";
            if ($i != $length) {
                $string .= ",";
            }
        }
        $string .= ")";
        return $string;
    }
}


?>