<?php
//require_once(dirname(__FILE__) . '/Config.php');
class InsertDao{
    public static function insert_tospur_house($params){
        global $wpdb;
        $houseRes =  $wpdb->insert(Config::TOSPUR_HOUSE_TABLE, $params);
        $houseId = $wpdb->insert_id;
        if(!InsertDao::setHouseNumber($houseId,$params['house_type'],$params['city_id'])){
            return 510;
        }
        if($houseRes){
            return $houseId;
        }else{
            return 500;
        }
    }

    public static function setHouseNumber($houseId,$houseType,$cityId){
        global $wpdb;
        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 $wpdb->update(Config::TOSPUR_HOUSE_TABLE,
            array(
                'house_number' => $house_number
            ),
            array(
                "id" => $houseId
            )
        );
    }

    public static function insert_tospur_image($params){
        global $wpdb;
        $imgRes = $wpdb->insert(Config::TOSPUR_IMAGE_TABLE, $params);
        $imgId = $wpdb->insert_id;
        if($imgRes){
            return $imgId;
        }else{
            return 501;
        }
    }
    public static function insert_a_district_area($params){
        global $wpdb;
        $districtAreaRes = $wpdb->insert(Config::A_DISTRICT_AREA_TABLE, $params);
        if($districtAreaRes){
            return $districtAreaRes;
        }else{
            return 502;
        }
    }

    public static function insert_a_house_image($params){
        global $wpdb;
        $houseImageRes = $wpdb->insert(Config::A_HOUSE_IMAGE_TABLE, $params);
        if($houseImageRes){
            return $houseImageRes;
        }else{
            return 503;
        }
    }

    public static function  insert_a_house_recommend($params){
        global $wpdb;
        $houseImageRes = $wpdb->insert(Config::A_HOUSE_RECOMMEND_TABLE, $params);
        if($houseImageRes){
            return $houseImageRes;
        }else{
            return 504;
        }
    }

    public static function  insert_a_house_user($params){
        global $wpdb;
        $houseUserRes = $wpdb->insert(Config::A_HOUSE_USER_TABLE, $params);
        if($houseUserRes){
            return $houseUserRes;
        }else{
            return 505;
        }
    }

    public static function addMainImage($houseId,$data){
        global $wpdb;
        //图片信息
        $uploadedfile = $_FILES['files'];
        $frontCover = $_POST["frontCover"];
        //主力房源的图片与房子信息关联插入数据库
        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);
                        //插入图片表
                        $imgRes = $wpdb->insert('tospur_image', $insert_image_array);
                        if (!$imgRes) {
                            return 501;
                        }

                        //获取插入图片的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
                            );
                            $houseTypeAreaRes = $wpdb->insert(Config::A_DISTRICT_AREA_TABLE, $houseTypeArea);
                            if (!$houseTypeAreaRes) {
                                return 502;
                            }
                        }
                        //将房源id与图片id储存到关联表中
                        $house_img_array = array(
                            'house_id' => $houseId,
                            'image_id' => $imgid,
                        );
                        $houseImgRes = $wpdb->insert(Config::A_HOUSE_IMAGE_TABLE, $house_img_array);
                        if (!$houseImgRes) {
                            return 503;
                        }
                    } else {
                        return $movefile['error'];
                    }
                }
            }
        }
        $wpdb->update(Config::TOSPUR_HOUSE_TABLE,array("frontCover_id"=>$frontCover),array("id"=>$houseId));
    }

    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
                );
                $a_house_recommendRes = $wpdb->insert(Config::A_HOUSE_RECOMMEND_TABLE, $a_house_recommendArray);
                if(!$a_house_recommendRes){
                    return 504;
                }
            }
        }
    }

    public static function addRecConsultant($houseId,$data){
        global $wpdb;
        if($data["recConsultant"]){
            //插入推荐置业顾问user_id与新房id到关联表a_house_recommend
            foreach($data["recConsultant"] as $val){
                $a_house_userArray = array(
                    "user_id" => $val,
                    "house_id" => $houseId,
                    "user_type" =>1
                );
                $a_house_userRes = $wpdb->replace(Config::A_HOUSE_USER_TABLE,$a_house_userArray);
                if(!$a_house_userRes){
                    return 505;
                }
            }
        }
    }
    public static function addHouseFeature($houseId,$houseFeature){
        global $wpdb;
        if($houseFeature){
            foreach($houseFeature as $val){
                $a_house_feature = array(
                    "house_id" => $houseId,
                    "tag_id" =>$val
                );

                $a_house_featureRes = $wpdb->insert(Config::A_HOUSE_TAG_TABLE,$a_house_feature);
                if(!$a_house_featureRes){
                    return 506;
                }
            }
        }
    }


    public static function addHouseTag($house_id, $houseTag)
    {
        global $wpdb;
        $wpdb->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 ($houseTag) {
            foreach ($houseTag as $val) {
                $a_house_tag = array(
                    "house_id" => $house_id,
                    "tag_id" => $val
                );
                $wpdb->insert(Config::A_HOUSE_TAG_TABLE, $a_house_tag);
            }
        }
    }

    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;
    }
}




?>